我正在开发一个Android应用程序来从服务器获取数据。它崩溃了,我得到了NullPointerException
。任何人都可以帮我编辑我的代码/列出我的错误?
这是我的代码(我已经阅读了几篇论坛,但并不真正了解如何解决我的问题)
public class MainActivity extends AppCompatActivity {
ListView lvPost;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvPost = (ListView)findViewById(R.id.lvPost);
String url2 = "http://192.168.0.146/client/login.php?format=json";
PostResponseAsyncTask task2 = new PostResponseAsyncTask(MainActivity.this, new AsyncResponse() {
@Override
public void processFinish(String s) {
ArrayList<Post> postList =
new JsonConverter<Post>().toArrayList(s, Post.class);
ArrayList<String> titles = new ArrayList<String>();
for (Post value:postList) {
titles.add(value.post_title);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1, titles);
lvPost.setAdapter(adapter);
}
});
task2.execute(url2);
}
}
这是我的logcat
java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.Iterator java.util.ArrayList.iterator()' on a null object reference
at com.example.1231.t12.MainActivity$1.processFinish(MainActivity.java:40)
at com.kosalgeek.genasync12.PostResponseAsyncTask.onPostExecute(PostResponseAsyncTask.java:188)
at com.kosalgeek.genasync12.PostResponseAsyncTask.onPostExecute(PostResponseAsyncTask.java:27)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6075)
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:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
答案 0 :(得分:2)
看起来String s
参数为null,使用日志记录进行确认。在这种情况下,Gson.fromJson()
会返回null
。然后,您尝试遍历postList
列表null
,结果为NullPointerException
。