代码之家  ›  专栏  ›  技术社区  ›  user2344665

运行时异常

  •  0
  • user2344665  · 技术社区  · 11 年前

    所以我正在构建一个应用程序,它只执行AsyncTask从网站抓取图像,然后我尝试使用JSON抓取文本。到目前为止,我已经有两个成功的教程完成了这两个工作应用程序。我现在正在尝试将两者合并,以便两者都得到。我遇到了一个错误,我认为这是一个简单的修复方法,但我不太确定如何解决。这是在搞乱“R”,我记得我被告知不要搞乱它。

    主要活动.java

    package com.jms.loadimagewithasynctask;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    import android.app.Activity;
    import android.app.ListActivity;
    import android.app.ProgressDialog;
    import android.content.Context;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.view.Menu;
    import android.widget.ListAdapter;
    import android.widget.ListView;
    import android.widget.SimpleAdapter;
    
    public class MainActivity extends ListActivity {
    
     /* JSON TEXT BELOW - i also changed (from) extends Activity*/
    private Context context;
    private static String url = "http://docs.blackberry.com/sampledata.json";
    
    private static final String TAG_VTYPE = "vehicleType";
    private static final String TAG_VCOLOR = "vehicleColor";
    private static final String TAG_FUEL = "fuel";
    private static final String TAG_TREAD = "treadType";
    private static final String TAG_OPERATOR = "approvedOperators";
    private static final String TAG_NAME = "name";
    private static final String TAG_POINTS = "experiencePoints";
    
    ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
    
    ListView lv ;
     /* JSON TEXT Above*/
    private String[] imageURLArray = new String[]{
            "http://iam.colum.edu/students/jordan.max/poker.png",
            "http://farm4.staticflickr.com/3777/9049174610_bf51be8a07_s.jpg",
            "http://farm8.staticflickr.com/7324/9046946887_d96a28376c_s.jpg",
            "http://farm3.staticflickr.com/2828/9046946983_923887b17d_s.jpg",
            "http://farm4.staticflickr.com/3810/9046947167_3a51fffa0b_s.jpg",
            "http://farm4.staticflickr.com/3773/9049175264_b0ea30fa75_s.jpg",
            "http://farm4.staticflickr.com/3781/9046945893_f27db35c7e_s.jpg",
            "http://farm6.staticflickr.com/5344/9049177018_4621cb63db_s.jpg",
            "http://farm8.staticflickr.com/7307/9046947621_67e0394f7b_s.jpg",
            "http://farm6.staticflickr.com/5457/9046948185_3be564ac10_s.jpg",
            "http://farm4.staticflickr.com/3752/9046946459_a41fbfe614_s.jpg",
            "http://farm8.staticflickr.com/7403/9046946715_85f13b91e5_s.jpg",
            "http://farm8.staticflickr.com/7315/9046944633_881f24c4fa_s.jpg",
            "http://farm4.staticflickr.com/3777/9049174610_bf51be8a07_s.jpg",
            "http://farm8.staticflickr.com/7324/9046946887_d96a28376c_s.jpg",
            "http://farm3.staticflickr.com/2828/9046946983_923887b17d_s.jpg",
            "http://farm4.staticflickr.com/3810/9046947167_3a51fffa0b_s.jpg",
            "http://farm4.staticflickr.com/3773/9049175264_b0ea30fa75_s.jpg",
            "http://farm4.staticflickr.com/3781/9046945893_f27db35c7e_s.jpg",
            "http://farm6.staticflickr.com/5344/9049177018_4621cb63db_s.jpg",
            "http://farm8.staticflickr.com/7307/9046947621_67e0394f7b_s.jpg",
            "http://farm6.staticflickr.com/5457/9046948185_3be564ac10_s.jpg",
            "http://farm4.staticflickr.com/3752/9046946459_a41fbfe614_s.jpg",
            "http://farm8.staticflickr.com/7403/9046946715_85f13b91e5_s.jpg"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        ListView listView = (ListView)this.findViewById(R.id.listView);
        ImageAdapter imageAdapter = new ImageAdapter(this, R.layout.imageitem, imageURLArray);
        listView.setAdapter(imageAdapter);
    
        new ProgressTask(MainActivity.this).execute(); //JSON TEXT//JSON TEXT//JSON TEXT//JSON TEXT
    }
    /* JSON CLASSES BELOW */
    private class ProgressTask extends AsyncTask<String, Void, Boolean> {
        private ProgressDialog dialog;
    
        private ListActivity activity;
    
        // private List<Message> messages;
        public ProgressTask(ListActivity activity) {
            this.activity = activity;
            context = activity;
            dialog = new ProgressDialog(context);
        }
    
        /** progress dialog to show user that the backup is processing. */
    
        /** application context. */
        private Context context;
    
        protected void onPreExecute() {
            this.dialog.setMessage("Progress start");
            this.dialog.show();
        }
    
        @Override
        protected void onPostExecute(final Boolean success) {
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
            ListAdapter adapter = new SimpleAdapter(context, jsonlist,
                    R.layout.list_item, new String[] { TAG_VTYPE, TAG_VCOLOR,
                            TAG_FUEL, TAG_TREAD }, new int[] {
                            R.id.vehicleType, R.id.vehicleColor, R.id.fuel,
                            R.id.treadType });
    
            setListAdapter(adapter);
    
            // selecting single ListView item
             lv = getListView();
    
    
    
    
    
    
        }
    
        protected Boolean doInBackground(final String... args) {
    
            JSONParser jParser = new JSONParser();
    
            // getting JSON string from URL
            JSONArray json = jParser.getJSONFromUrl(url);
    
            for (int i = 0; i < json.length(); i++) {
    
                try {
                    JSONObject c = json.getJSONObject(i);
                    String vtype = c.getString(TAG_VTYPE);
    
                    String vcolor = c.getString(TAG_VCOLOR);
                    String vfuel = c.getString(TAG_FUEL);
                    String vtread = c.getString(TAG_TREAD);
    
                    HashMap<String, String> map = new HashMap<String, String>();
    
                    // adding each child node to HashMap key => value
                    map.put(TAG_VTYPE, vtype);
                    map.put(TAG_VCOLOR, vcolor);
                    map.put(TAG_FUEL, vfuel);
                    map.put(TAG_TREAD, vtread);
                    jsonlist.add(map);
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
    
            return null;
    
        }
    
    }
    /* JSON CLASSES ABOVE */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
    }
    

    JSON解析器.java

    package com.jms.loadimagewithasynctask;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.UnsupportedEncodingException;
    
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.StatusLine;
    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.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    import android.util.Log;
    
    public class JSONParser {
    
    static InputStream is = null;
    static JSONArray jarray = null;
    static String json = "";
    
    // constructor
    public JSONParser() {
    
    }
    
    public JSONArray getJSONFromUrl(String url) {
    
           StringBuilder builder = new StringBuilder();
            HttpClient client = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            try {
              HttpResponse response = client.execute(httpGet);
              StatusLine statusLine = response.getStatusLine();
              int statusCode = statusLine.getStatusCode();
              if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                  builder.append(line);
                }
              } else {
                Log.e("==>", "Failed to download file");
              }
            } catch (ClientProtocolException e) {
              e.printStackTrace();
            } catch (IOException e) {
              e.printStackTrace();
            }
    
        // try parse the string to a JSON object
        try {
            jarray = new JSONArray( builder.toString());
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
    
        // return JSON String
        return jarray;
    
    }
    }
    

    (我也有一个ImageAdaptor类,但很明显,我怀疑这与我的问题有什么关系,因为在我把JSON内容放进去之前,它是有效的。)

    列表项.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">  
    <LinearLayout 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <!-- Name Label -->
        <TextView
            android:id="@+id/vehicleType"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textColor="#43bd00"
            android:textSize="16sp"
            android:textStyle="bold"
            android:paddingTop="6dip"
            android:paddingBottom="2dip" />
        <!-- Description label -->
        <TextView
            android:id="@+id/vehicleColor"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textColor="#acacac"
            android:paddingBottom="2dip">
        </TextView>
    
        <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <!-- Cost Label -->
        <TextView
              android:id="@+id/fuel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#5d5d5d"
            android:gravity="left"
            android:textStyle="bold"
            android:text="Mobile: " >
        </TextView>
        <!-- Price Label -->
        <TextView
            android:id="@+id/treadType"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#acacac" 
            android:textStyle="bold"
            android:gravity="left">
        </TextView>
        </LinearLayout>
    </LinearLayout>
    
    </LinearLayout>
    

    主.xml

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
    
    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
    </RelativeLayout>
    

    (再次,我确实有另一个.xml文件用于我的Async内容,但这与我的错误无关,如果需要,我会发布它。)

    我的错误是:

    FATAL EXCEPTION: main
    java.lang.RunTimeException: Unable to start activity
    ComponentInfo(com.jms.loadimagewithasynctask/com.jms.loadimagewithasynctask.MainActivity}:     java.lang.RuntimeException: Your content must have a List View whose id attribute is android.R.id.list
    

    更新的错误

    02-23 22:54:55.032: E/AndroidRuntime(534): FATAL EXCEPTION: main
    02-23 22:54:55.032: E/AndroidRuntime(534): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.jms.loadimagewithasynctask/com.jms.loadimagewithasynctask.MainActivity}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
    02-23 22:54:55.032: E/AndroidRuntime(534):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
    02-23 22:54:55.032: E/AndroidRuntime(534):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
    02-23 22:54:55.032: E/AndroidRuntime(534):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
    02-23 22:54:55.032: E/AndroidRuntime(534):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
    02-23 22:54:55.032: E/AndroidRuntime(534):  at android.os.Handler.dispatchMessage(Handler.java:99)
    02-23 22:54:55.032: E/AndroidRuntime(534):  at android.os.Looper.loop(Looper.java:123)
    02-23 22:54:55.032: E/AndroidRuntime(534):  at android.app.ActivityThread.main(ActivityThread.java:3683)
    02-23 22:54:55.032: E/AndroidRuntime(534):  at java.lang.reflect.Method.invokeNative(Native Method)
    02-23 22:54:55.032: E/AndroidRuntime(534):  at java.lang.reflect.Method.invoke(Method.java:507)
    02-23 22:54:55.032: E/AndroidRuntime(534):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
    02-23 22:54:55.032: E/AndroidRuntime(534):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
    02-23 22:54:55.032: E/AndroidRuntime(534):  at dalvik.system.NativeStart.main(Native Method)
    02-23 22:54:55.032: E/AndroidRuntime(534): Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
    02-23 22:54:55.032: E/AndroidRuntime(534):  at android.app.ListActivity.onContentChanged(ListActivity.java:243)
    02-23 22:54:55.032: E/AndroidRuntime(534):  at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:210)
    02-23 22:54:55.032: E/AndroidRuntime(534):  at android.app.Activity.setContentView(Activity.java:1657)
    02-23 22:54:55.032: E/AndroidRuntime(534):  at com.jms.loadimagewithasynctask.MainActivity.onCreate(MainActivity.java:67)
    02-23 22:54:55.032: E/AndroidRuntime(534):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
    02-23 22:54:55.032: E/AndroidRuntime(534):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
    02-23 22:54:55.032: E/AndroidRuntime(534):  ... 11 more
    
    4 回复  |  直到 11 年前
        1
  •  0
  •   ρяσѕρєя K    11 年前

    改变

    android:id="@+id/listView"
    

    android:id="@android:id/list"
    

    因为你正在扩展 ListActivity 所以您必须具有ListView id @android:id/list

        2
  •  0
  •   Raghunandan    11 年前

    你一定有

     <ListView android:id="@android:id/list"
    

    在您的 main.xml

    ListActivity 默认情况下,屏幕中央有一个全屏列表。

    所以如果你有 setContentView(R.layout.main); 那么您需要有一个具有如上所述id的listview。

    http://developer.android.com/reference/android/app/ListActivity.html

        3
  •  0
  •   rajshree    11 年前

    您需要更改列表视图

    从这个

      <ListView
      android:id="@+id/listView"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      />
    

    对此。。。。

    <ListView
      android:id="@android:id/list"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      />
    

    因为您正在扩展listactivity。。。

        4
  •  0
  •   Android Junkie    11 年前

    正如其他人所建议的,listview实现存在问题。

    你为什么不结账呢 Exhaustive ListView with simple examples