2013-03-07 36 views
0

我刚刚发布了昨天,但现在我试图把我的数据,并把它放入ListView而不是TextView。该应用程序在启动listview活动后崩溃。如果有人对此有任何线索,将不胜感激。Android应用崩溃。把JSON数据放入列表视图

继承人的活动代码:

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":"[email protected]", 
     "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) 

回答

1

对于初学者来说,此行

eventsList= getListView(); 

应该是你onCreate()内。但声明ListView eventsList作为一个字段变量,你只是initalize它onCreate()

这是你的NPE是从,因为它会从你的LayoutListView你还没有得到,直到调用setContentView()inflate它与未来inflater。所以调用getListView()还需要跟从setContentView()

您也将需要一个android:id="@android:id/list"ListViewLayout

我建议去通过ListActivity Docs,因为他们可以是一个棘手的事,直到你了解他们。我还建议观看Turbo Charge your UI,我相信我通过@Sam了解了这些。这是一个古老的,但仍然有很多很好的信息。它涉及UI的不同部分,但具有关于更有效地使用ListView的良好信息。

编辑

正如这里说:

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

这就是为什么我最初添加此行我的答案:)

您还需要一个ListViewandroid:id="@android:id/list" 您的Layout

The example from the Docs

<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"/> 
+0

感谢您的帮助!我尝试了您的建议,并且仍然收到相同的崩溃错误。我会看看你的链接,看看我能不能找出答案。你有没有看到其他的错误? – sourdesi 2013-03-07 20:48:16

+0

现在哪条线路出现错误?如果你在膨胀包含'ListView'的布局下面插入代码,你不应该得到相同的错误。如果你是我会尝试清理并检查logcat哪个行给出了错误 – codeMagic 2013-03-07 21:05:34

+0

我刚刚更新了LogCat错误和我上面的代码。看起来它在第90行有一个问题,它只是我的setContentView(R.layout.main_screen);线。我现在很困惑 – sourdesi 2013-03-07 21:43:22

0

使用MainScreen上下文监守你在MainScreen活动延伸ListActivity作为设置ListView适配器:

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

    } 
+0

感谢您的帮助!我把它写入我的代码,但无济于事。我将更详细地阅读关于listview的文档,并了解其他人如何将JSON解析为listview。但同时,你是否看到其他可能会出错的东西? – sourdesi 2013-03-07 20:49:42

+0

@sourdesi:使用ArrayList而不是Array,因为数组的大小很大你已经声明了10,并且在onPostExecute中只添加了一个元素 – 2013-03-08 04:33:06