Android App崩溃。将JSON数据放入Listview

时间:2013-03-07 18:51:37

标签: android json android-listview crash android-asynctask

我刚刚发布了昨天,但现在我试图获取我的数据并将其放入ListView而不是TextView。应用程序在显示listview活动后崩溃。如果有人对此有任何线索,将非常感谢帮助。

继承活动代码:

   package com.example.Accomplist;

import android.app.Activity;
import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.RemoteException;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: DESAI_628IL
 * Date: 3/1/13
 * Time: 7:34 PM
 * To change this template use File | Settings | File Templates.
 */
public class MainScreen extends ListActivity{
    JSONObject jsonObj= null;

    String[] eventArr= new String[10];
    int i=0;

   // HttpClient client;
    // url to make request
    String[] urlArr = new String[10];//"http://accomplist.herokuapp.com/api/v1/sharedevent/1/?format=json";


    //Following comment block is example of json object from above url
    {
    /*

    {
   "date":"2013-01-17T12:48:24.326859",
   "event":{
      "description":"I want to find work that I love so that I never have to work a day in my life.",
      "id":3,
      "resource_uri":"/api/v1/event/3/",
      "title":{
         "id":3,
         "listitem":"Get a Job I Enjoy",
         "resource_uri":"/api/v1/title/3/"
      },
      "user":{
         "date_joined":"2013-01-17T12:40:17.115755",
         "email":"sourabhdesai@gmail.com",
         "first_name":"",
         "id":3,
         "is_active":true,
         "is_staff":false,
         "is_superuser":false,
         "last_login":"2013-02-02T15:51:11.622505",
         "last_name":"",
         "password":"pbkdf2_sha256$10000$ETuiYJXQjvez$5yHd5IPaQpS0SvlissO/JydwXUHhMYDgadY7uyTyWg0=",
         "resource_uri":"/api/v1/user/3/",
         "username":"sourabhd"
      }
   },
   "id":2,
   "resource_uri":"/api/v1/sharedevent/2/",
   "votes":7
}

     */
    }
    private static final String TAG_EVENT="event"; //A JSON object within the JSON object that will be returned by JSONParse()
    private static final String TAG_DESCRIPTION="description"; //A JSON tag within the JSON object EVENT
    private static String eventString="Yo";

    protected void onCreate(Bundle savedInstanceState) {
        for(int b=0; b<urlArr.length; b++) {
            urlArr[b]= "http://accomplist.herokuapp.com/api/v1/sharedevent/"+(b+1)+"/?format=json";
        }
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_screen);
        ListView eventsList= getListView();
        new JSONParse().execute(urlArr[0],urlArr[1],urlArr[2],urlArr[3],urlArr[4],urlArr[5],urlArr[6],urlArr[7],urlArr[8]);
    }
private class JSONParse extends AsyncTask<String, Void, String> {
    HttpClient client=new DefaultHttpClient();


    @Override
    protected String doInBackground(String... jsonurl) {
//        StringBuilder url= new StringBuilder(String.valueOf(jsonurl));
        HttpUriRequest request= new HttpGet("http://accomplist.herokuapp.com/api/v1/sharedevent/2/?format=json");
        HttpResponse r= null;
        try {
            r = client.execute(request);
        } catch (ClientProtocolException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        int status= r.getStatusLine().getStatusCode();
        if (status==200){
            HttpEntity e=r.getEntity();
            String data= null;
            try {
                data = EntityUtils.toString(e);
            } catch (IOException e1) {
                e1.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
            try {
                jsonObj = new JSONObject(data);
            } catch (JSONException e1) {
                e1.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
            try {
                JSONObject eventJson= jsonObj.getJSONObject(TAG_EVENT);
                eventString= eventJson.getString(TAG_DESCRIPTION);
            }
            catch (JSONException e1) {
                eventString="Couldn't Parse Data";
            }
            return eventString;
        }
        else{
            return eventString;
        }
    }
    protected void onProgressUpdate() {
        Toast loadingToast= Toast.makeText(getApplicationContext(), "Loading", Toast.LENGTH_LONG);
        loadingToast.show();
    }
    protected void onPostExecute(String result) {
        eventString=result;
        eventArr[i]=eventString;
        i++;
        MainScreen.this.setListAdapter(new ArrayAdapter<String>(MainScreen.this,
                android.R.layout.simple_list_item_1,eventArr));

    }
}
}

继承LogCat错误消息:

02-26 15:57:21.692: WARN/InputMethodManagerService(324): Got RemoteException sending setActive(false) notification to pid 5900 uid 10048
02-26 15:57:31.964: WARN/dalvikvm(5918): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
02-26 15:57:32.042: ERROR/AndroidRuntime(5918): FATAL EXCEPTION: main
        java.lang.NullPointerException
        at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:394)
        at android.widget.ArrayAdapter.getView(ArrayAdapter.java:362)
        at android.widget.AbsListView.obtainView(AbsListView.java:2143)
        at android.widget.ListView.measureHeightOfChildren(ListView.java:1246)
        at android.widget.ListView.onMeasure(ListView.java:1158)
        at android.view.View.measure(View.java:15518)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
        at android.view.View.measure(View.java:15518)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
        at android.view.View.measure(View.java:15518)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:847)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
        at android.view.View.measure(View.java:15518)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
        at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2176)
        at android.view.View.measure(View.java:15518)
        at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1874)
        at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1089)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1265)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
        at android.view.Choreographer.doCallbacks(Choreographer.java:562)
        at android.view.Choreographer.doFrame(Choreographer.java:532)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
        at android.os.Handler.handleCallback(Handler.java:725)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:5041)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
        at dalvik.system.NativeStart.main(Native Method)

2 个答案:

答案 0 :(得分:1)

首先,这一行

eventsList= getListView();

应该在onCreate()内。但是将ListView eventsList声明为字段变量,因为您只是在onCreate()

中将其初始化

这是NPE来自ListView的来源,因为它从您Layout获得setContentView(),直到您拨打inflate或{{1}它带有inflater。因此,对getListView()的调用也需要在setContentView()

之后

ListView

还需要android:id="@android:id/list" Layout UI

我建议通过ListActivity Docs,因为在你理解它们之前它们可能是一件棘手的事情。我还建议观看Turbo Charge your UI,我相信我通过@Sam了解到了这一点。这个有点旧,但仍然有很多好的信息。它涉及ListView的不同部分,但提供了有关更有效地使用Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list' 的良好信息。

修改

正如它在这里所说:

ListView

这就是为什么我最初在我的答案中添加了这一行:)

  

您还需要android:id="@android:id/list" Layout   在<ListView android:id="@android:id/list" //this is the important part android:layout_width="match_parent" android:layout_height="match_parent" android:background="#00FF00" android:layout_weight="1" android:drawSelectorOnTop="false"/>

The example from the Docs

{{1}}

答案 1 :(得分:0)

使用MainScreen上下文为ListView设置适配器,因为您在ListActivity活动中将MainScreen扩展为:

protected void onPostExecute(String result) {
        eventString=result;
        eventArr[i]=eventString;
        i++;
        MainScreen.this.setListAdapter(new ArrayAdapter<String>(MainScreen.this, 
                   android.R.layout.simple_list_item_1,eventArr));

    }