0

我昨天刚刚发布,但现在我试图将我的数据放入 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)
4

2 回答 2

1

首先,这条线

eventsList= getListView();

应该在你的onCreate(). 但是声明ListView eventsList为一个字段变量,因为你只是在初始化它onCreate()

这就是你NPE的来源,因为它ListView从你Layout那里得到你直到你打电话setContentView()inflateinflater. 所以电话getListView()也需要在之后setContentView()

你还需要一个ListViewwithandroid:id="@android:id/list"在你的Layout

我建议阅读ListActivity Docs,因为在您理解它们之前它们可能是一件棘手的事情。我还建议观看Turbo Charge 你的 UI,我相信我是通过 @Sam 了解到的。这个有点旧,但仍然有很多很好的信息。它处理不同的部分,但有关于更有效地UI使用的很好的信息。ListView

编辑

正如这里所说:

Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'

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

你还需要一个ListViewwithandroid: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"/>
于 2013-03-07T18:57:27.510 回答
0

使用MainScreen上下文设置适配器,因为您在ActivityListView中扩展为:ListActivityMainScreen

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));

    }
于 2013-03-07T19:26:08.513 回答