我为什么收到致命的例外?

时间:2015-07-14 18:11:01

标签: android multithreading android-layout listview android-arrayadapter

我是android的新手,我正在尝试使用数组适配器,运行方法和multi threading创建列表视图,但我收到以下错误:

  

07-14 19:00:15.605 29316-29316 / com.protogeo.moves.demos.apps   W / dalvikvm:threadid = 1:线程退出未捕获的异常   (组= 0xa4b8f648)07-14 19:00:15.633   29316-29316 / com.protogeo.moves.demos.apps E / AndroidRuntime:FATAL   例外:主要       显示java.lang.NullPointerException               在android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)               在android.widget.ListView.onMeasure(ListView.java:1128)               在android.view.View.measure(View.java:15848)               在android.widget.RelativeLayout.measureChildHorizo​​ntal(RelativeLayout.java:728)               在android.widget.RelativeLayout.onMeasure(RelativeLayout.java:477)               在android.view.View.measure(View.java:15848)               在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)               在android.widget.FrameLayout.onMeasure(FrameLayout.java:310)               在android.view.View.measure(View.java:15848)               在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)               在com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:302)               在android.view.View.measure(View.java:15848)               在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)               在android.widget.FrameLayout.onMeasure(FrameLayout.java:310)               在com.android.internal.policy.impl.PhoneWindow $ DecorView.onMeasure(PhoneWindow.java:2189)               在android.view.View.measure(View.java:15848)               在android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1905)               在android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1104)               在android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1284)               在android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1004)               在android.view.ViewRootImpl $ TraversalRunnable.run(ViewRootImpl.java:5481)               在android.view.Choreographer $ CallbackRecord.run(Choreographer.java:749)               在android.view.Choreographer.doCallbacks(Choreographer.java:562)               在android.view.Choreographer.doFrame(Choreographer.java:532)               在android.view.Choreographer $ FrameDisplayEventReceiver.run(Choreographer.java:735)               在android.os.Handler.handleCallback(Handler.java:730)               在android.os.Handler.dispatchMessage(Handler.java:92)               在android.os.Looper.loop(Looper.java:137)               在android.app.ActivityThread.main(ActivityThread.java:5103)               at java.lang.reflect.Method.invokeNative(Native Method)               在java.lang.reflect.Method.invoke(Method.java:525)               在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:737)               在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)               在dalvik.system.NativeStart.main(本地方法)

我的MainActivity看起来像这样:

public class MainActivity extends FragmentActivity implements OnClickListener{
...
    public void updateResponse() {
        runOnUiThread(new Runnable() {


        @Override
        public void run() {
            StorylineAdapter adapter = null;
            try {
                adapter = new StorylineAdapter(MainActivity.this, R.layout.item_storyline, summary);

            // mEditTextResponse.setAdapter(adapter);
                mEditTextResponse.setAdapter(adapter);
            } catch (Exception e) {
                e.printStackTrace();
            }

我的ArrayAdapter课程如下:

public class StorylineAdapter extends ArrayAdapter<SummaryData>{
    private Context context;
    private Runnable runnable;
private ArrayList<StorylineData> storylineData;

public StorylineAdapter(Context context, int resource, ArrayList<SummaryData> objects) {
    super(context, resource, objects);
    this.context = context;
    this.runnable = runnable;
    this.summary = objects;
}



@Override
public View getView(int position, View convertView, ViewGroup parent){

    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.item_storyline, parent, false);


    /*LayoutInflater inflater =
            (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.item_storyline, parent, false);
    */

    //Display in the TextView widget
    SummaryData summary1 = summary.get(position);
    TextView tv = (TextView) view.findViewById(R.id.textView1);
    tv.setText(summary1.getActivity());

    return view;
}
}

这是我的解析器类:

public class StorylineData extends ArrayList<StorylineData> {

...Getters/Setters...

    /** ******************* Parser methods    

    /**
     * Parse a {@link org.json.JSONObject} from storyline {@link org.json.JSONArray}, then return the corresponding {@link StorylineData} object.
     *
     * @param jsonObject : the storyline JSON object received from server
     * @return corresponding {@link StorylineData}
     */
    public static StorylineData parse(JSONObject jsonObject) throws JSONException {
        if (jsonObject != null) {

            StorylineData storylineData = new StorylineData();


            storylineData.date = jsonObject.optString("date");
            storylineData.caloriesIdle = jsonObject.optInt("caloriesIdle");
            storylineData.lastUpdate = jsonObject.optString("lastUpdate");
            storylineData.summary = new ArrayList<SummaryData>();
            storylineData.segments = new ArrayList<SegmentData>();



            /**Get the data associated with the array named summary **To get a specific JSONArray: Summary*/
            JSONArray summariesJsonArray = jsonObject.optJSONArray("summary");

            if (summariesJsonArray != null)
            for (int i = 0; i < summariesJsonArray.length(); i++) {


                /**each time through array will need to get a reference of current object*/
                JSONObject summaryJsonObject = summariesJsonArray.optJSONObject(i);//declare instance of class object ob //array object called getJSONObject //passin indexvalu of (i)

                        if (summaryJsonObject != null) {
                        /**===============Translate data from json to Java=================*/
                            /**Create a new OBJECT OF ARRAY STORYLINE/SUMMARY*/
                            ArrayList<SummaryData> summary = new ArrayList<SummaryData>(); // initialisation must be outside the loop
                            storylineData.setSummary(summary);

                            /**Get summary from json into java*/
                            summariesJsonArray.getJSONObject(i).getString("distance");

                            /**Get date from json into java*/
                            String date = summaryJsonObject.optString("date");
                            storylineData.setDate(date);

                            /**Get group from json into java*/
                            String group = summaryJsonObject.optString("group");//Get name using key e.g. date
                            storylineData.setGroup(group);

                            /**Get distance from json into java*/
                            Integer distance = summaryJsonObject.optInt("distance");//Get name using key e.g. date
                            storylineData.setDistance(distance);

                            /**Get duration from json into java*/
                            Integer duration = summaryJsonObject.optInt("duration");
                            storylineData.setDuration(duration);

                            /**Get activity from json into java*/
                            String activity = summaryJsonObject.optString("activity");//Get name using key e.g. date
                            storylineData.setActivity(activity);


                            storylineData.summary.add(SummaryData.parse(summaryJsonObject));
                            Log.d("StorylineDataCls \t sJo", summaryJsonObject.toString() + "Log\n");
                            System.out.println("print distance" + summariesJsonArray.getJSONObject(i).getString("distance"));
                            System.out.println("print summary" + summaryJsonObject);


                    }
                }

            JSONArray segmentsJsonArray = jsonObject.optJSONArray("segments");
            if (segmentsJsonArray != null) {

                for (int i = 0; i < segmentsJsonArray.length(); i++) {
                    JSONObject segment = segmentsJsonArray.optJSONObject(i);

                    if (segment != null) {

                        ArrayList<SegmentData> segments = new ArrayList<SegmentData>(); // initialisation must be outside the loop
                        storylineData.setSegments(segments);

                        String type = segment.optString("type");
                        storylineData.setType(type);

                        String startTime = segment.optString("startTime");
                        storylineData.setStartTime(startTime);


                        String endTime = segment.optString("endTime");
                        storylineData.setEndTime(endTime);

                        /**Get steps from json into java*/
                        Integer activities = segment.optInt("place");
                        storylineData.setSteps(activities);


                        Integer calories = segment.optInt("calories");
                        storylineData.setCalories(calories);

                        String lastUpdate = segment.optString("lastUpdate");
                        storylineData.setLastUpdate(lastUpdate);
                        /**Get group from json into java*/
                        Integer caloriesIdle = segment.optInt("caloriesIdle");
                        storylineData.setCaloriesIdle(caloriesIdle);

                        storylineData.segments.add(SegmentData.parse(segment));


                        Log.d("StorylineDataCls \t sSo", segment.toString());

                    }
                }
            }
            return storylineData;
        }
        return null;


    }





}

2 个答案:

答案 0 :(得分:1)

看起来像&#34;摘要&#34;一片空白。在创建和设置适配器之前检查null。

if (summary == null) {
    // handle the error
    Toast.makeText(this, "Error: no result", Toast.LENGTH_LONG).show();
} else {
    StorylineAdapter adapter = new StorylineAdapter(MainActivity.this, R.layout.item_storyline, summary);
    mEditTextResponse.setAdapter(adapter);
}

答案 1 :(得分:0)

您应该在适配器中添加getCount方法。这可能看起来像这样:

 public class StorylineAdapter extends ArrayAdapter<SummaryData>{
//Keep your other methods as they stand
...

@Override
public int getCount()
{
   if (summary!=null)
   {
   return summary.size();
   }
   else
   {
   Log.e("Adapter","Summary array is null");
   return 0;
   }
}