我有 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();
}
}
}