【发布时间】:2015-01-17 22:33:32
【问题描述】:
在我对用户进行身份验证后(使用 volley 库),我的 ServerConnection 类将带有用户名称的回调发送到我的 Fragment。我想在TextView 中显示用户名,但应用程序总是崩溃。
public class DrawerFragment extends Fragment implements ServerConnection.AuthenticationSuccessful {
TextView vDrawerName;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.drawer_default, container, false);
vDrawerName = (TextView) view.findViewById(R.id.drawerName);
vDrawerName.setText("Test"); // works
ListView drawerList = (ListView) view.findViewById(R.id.drawerList);
drawerList.setAdapter(new ArrayAdapter<>(this.getActivity(), android.R.layout.simple_list_item_1,
new String[]{"Hallo", "test"}));
return view;
}
@Override
public void onSuccess(String firstName, int id) {
vDrawerName.setText(firstName); // view is null
}
}
ServerConnection.class
private AuthenticationSuccessful successful;
public ServerConnection(FragmentActivity activity, SharedPreferences sharedPreferences) {
this.activity = activity;
this.sharedPreferences = sharedPreferences;
queue = Volley.newRequestQueue(activity);
successful = new DrawerFragment();
}
public void authenticate(){
//...
successful.onSuccess("Name", 1);
}
public interface AuthenticationSuccessful {
public void onSuccess(String firstName, int id);
}
在主活动中
ServerConnection connection = new ServerConnection(this,
getSharedPreferences(ServerConnection.LOGIN_PREFERENCE, 0));
connection.authenticate();
日志猫
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.polat.mete.worknote.fragments.DrawerFragment.onSuccess(DrawerFragment.java:40)
at com.polat.mete.worknote.ServerConnection$3.onResponse(ServerConnection.java:124)
at com.polat.mete.worknote.ServerConnection$3.onResponse(ServerConnection.java:116)
at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5223)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
【问题讨论】:
-
你试过把
TextView vDrawerName;改成final TextView vDrawerName;吗? -
在服务器连接中,您创建了一个新片段 instance。在尝试调用
onSuccess之前,您是否真的在事务中提交了它?片段不依赖于连接,所以在外部和之前提交它。 -
@Leigh 如果您的实例是本地对象,则无法在全局范围内将对象设置为最终对象。
标签: android android-fragments android-asynctask