我有3个可滑动的空视图。第三视图是“ViewAll”。第一个视图工作正常,但是当我向第二个视图滑动时,它会显示此错误。
我试图在AsyncTask中显示我使用JSON加载的数据,但是存在此NullPointerException错误 而且我不知道如何解决它......
11-12 10:00:23.046: E/InputEventReceiver(12007): Exception dispatching input event.
11-12 10:00:23.046: E/MessageQueue-JNI(12007): Exception in MessageQueue callback: handleReceiveCallback
11-12 10:00:23.056: E/MessageQueue-JNI(12007): java.lang.NullPointerException
11-12 10:00:23.056: E/MessageQueue-JNI(12007): at com.example.rumorz.ViewAll$PostTask.onPreExecute(ViewAll.java:52)
11-12 10:00:23.056: E/MessageQueue-JNI(12007): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
这是我的代码:
public class ViewAll extends Fragment {
//URL to get JSON Array
private static String url = ""; //URL to my site with JSON-code
//JSON Node Names
private static final String TAG_USER = "user";
private static final String TAG_message= "message";
TextView tvuser ;
TextView tvmessage ;
JSONArray user = null;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
new PostTask().execute();
View rootView = inflater.inflate(R.layout.viewall, container, false);
return rootView;
}
private class PostTask extends AsyncTask<String, String, JSONObject> {
@Override
protected void onPreExecute() {
super.onPreExecute();
tvuser = (TextView)getView().findViewById(R.id.tvUser);
tvmessage = (TextView)getView().findViewById(R.id.tvmessage);
}
@Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
@Override
protected void onPostExecute(JSONObject json) {
try {
user = json.getJSONArray(TAG_USER);
JSONObject c = user.getJSONObject(0);
// Storing JSON item in a Variable
String users = c.getString(TAG_USER);
String message = c.getString(TAG_message);
tvuser.setText(users);
tvmessage.setText(message);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:2)
onPreExecute(),在执行任务后立即在UI线程上调用。 初始化
tvuser = (TextView)rootView.findViewById(R.id.tvUser);
tvmessage = (TextView)rootview.findViewById(R.id.tvmessage);
onCreateView 中的
答案 1 :(得分:0)
在onCreateView
初始化它。使用膨胀的视图对象初始化textview。或使用getView
中的onActivityCreated
来初始化textview。
由于textview被声明为类成员,因此您可以在onPostEecute
中使用它来将文本设置为相同。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.viewall, container, false);
tvuser = (TextView)rootView.findViewById(R.id.tvUser);
tvmessage = (TextView)rootview.findViewById(R.id.tvmessage);
new PostTask().execute();
return rootView;
}