从mysql检索数据到listview时,应用程序崩溃

时间:2014-03-25 07:18:31

标签: android mysql listview

我正在尝试从mysql中检索数据并加载到listview中。但是当我尝试运行它时应用程序崩溃。我无法解决错误.JSON响应工作正常,结果显示在浏览器中。请帮忙。这是MainActivity文件

    package com.example.triallistview;

    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    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.app.ListActivity;
    import android.net.ParseException;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.ArrayAdapter;
    import android.widget.ListView;
    import android.widget.Toast;

    public class MainActivity extends ListActivity {
int ct_id;
String[] ct_name = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    String result = null;
    InputStream is = null;
    StringBuilder sb = null;
    ListView lv;
    lv = (ListView)findViewById(R.id.list);
    // http post
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://127.0.0.1/example/city.php");
       // httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection" + e.toString());
    }
    // convert response to string
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        sb = new StringBuilder();
        sb.append(reader.readLine() + "\n");
        String line = "0";
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();
    } catch (Exception e) {
        Log.e("log_tag", "Error converting result " + e.toString());
    }
    // paring data
    JSONArray jArray;
    try {
        jArray = new JSONArray(result);
        JSONObject json_data = null;
        ct_name = new String[jArray.length()];
        for (int i = 0; i < jArray.length(); i++) {
            json_data = jArray.getJSONObject(i);
            ct_id = json_data.getInt("CITY_ID");
            ct_name[i] = json_data.getString("CITY_NAME");
        }
    } catch (JSONException e1) {
        Toast.makeText(getBaseContext(), "No City Found", Toast.LENGTH_LONG)
                .show();
    } catch (ParseException e1) {
        e1.printStackTrace();
    }


    lv = getListView();
    lv.setAdapter(new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, ct_name));
    lv.setTextFilterEnabled(true);
    lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(int  position, long id) {
            // When clicked, show a toast with the TextView text
            Toast.makeText(getApplicationContext(),
                    ct_name[position] + " wasClicked", Toast.LENGTH_SHORT)
                    .show();
        }

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub

        }


    });
    }
     }

logcat看起来像这样

    03-25 02:42:03.195: E/AndroidRuntime(2380): FATAL EXCEPTION: main
    03-25 02:42:03.195: E/AndroidRuntime(2380): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.triallistview/com.example.triallistview.MainActivity}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
    03-25 02:42:03.195: E/AndroidRuntime(2380):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
    03-25 02:42:03.195: E/AndroidRuntime(2380):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
    03-25 02:42:03.195: E/AndroidRuntime(2380):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
    03-25 02:42:03.195: E/AndroidRuntime(2380):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
    03-25 02:42:03.195: E/AndroidRuntime(2380):     at android.os.Handler.dispatchMessage(Handler.java:99)
    03-25 02:42:03.195: E/AndroidRuntime(2380):     at android.os.Looper.loop(Looper.java:137)
    03-25 02:42:03.195: E/AndroidRuntime(2380):     at android.app.ActivityThread.main(ActivityThread.java:5103)
    03-25 02:42:03.195: E/AndroidRuntime(2380):     at java.lang.reflect.Method.invokeNative(Native Method)
    03-25 02:42:03.195: E/AndroidRuntime(2380):     at java.lang.reflect.Method.invoke(Method.java:525)
    03-25 02:42:03.195: E/AndroidRuntime(2380):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
    03-25 02:42:03.195: E/AndroidRuntime(2380):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
    03-25 02:42:03.195: E/AndroidRuntime(2380):     at dalvik.system.NativeStart.main(Native Method)
    03-25 02:42:03.195: E/AndroidRuntime(2380): Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
    03-25 02:42:03.195: E/AndroidRuntime(2380):     at  android.app.ListActivity.onContentChanged(ListActivity.java:243)
    03-25 02:42:03.195: E/AndroidRuntime(2380):     at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:270)
    03-25 02:42:03.195: E/AndroidRuntime(2380):     at android.app.Activity.setContentView(Activity.java:1895)
    03-25 02:42:03.195: E/AndroidRuntime(2380):     at com.example.triallistview.MainActivity.onCreate(MainActivity.java:34)
    03-25 02:42:03.195: E/AndroidRuntime(2380):     at android.app.Activity.performCreate(Activity.java:5133)
    03-25 02:42:03.195: E/AndroidRuntime(2380):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
    03-25 02:42:03.195: E/AndroidRuntime(2380):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
    03-25 02:42:03.195: E/AndroidRuntime(2380):     ... 11 more

请告诉我应该做些什么改变。

3 个答案:

答案 0 :(得分:3)

  

引起:java.lang.RuntimeException:您的内容必须有   ListView的id属性为'android.R.id.list'

你有

public class MainActivity extends ListActivity {

然后

setContentView(R.layout.activity_main);

因此,您需要在activity_main.xml中使用ID为

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

同时删除

lv = (ListView)findViewById(R.id.list);

您可以使用lv = getListView()

引用文档

  

ListActivity的默认布局由单个布局组成,   屏幕中央的全屏列表。但是,如果你愿意,   您可以通过设置自己的视图布局来自定义屏幕布局   在onCreate()中使用setContentView()。要做到这一点,你自己的观点必须   包含一个ID为“@android:id / list”的ListView对象(或列出if   它在代码中)

除了所有这些,你在主ui线程上进行网络操作。您需要使用ThreadAsyncTask

 HttpClient httpclient = new DefaultHttpClient();
 HttpPost httppost = new HttpPost("http://127.0.0.1/example/city.php");
 // httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
 HttpResponse response = httpclient.execute(httppost); // must be in a thread

您将获得NetworkOnMainThreadException

  

应用程序尝试执行时抛出的异常   在其主线程上进行网络操作。

     

这仅适用于针对Honeycomb SDK或。的应用程序   更高。允许使用早期SDK版本的应用程序   他们的主要事件循环线程上的网络,但它是很重要的   泄气

编辑:

似乎有很多困惑。人们想要更准确的答案。我会发布一个例子

示例:

在下面我们有一个TextView和一个ListView

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.testall.MainActivity"
    tools:ignore="MergeRootFrame" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="150dp"
        android:layout_marginTop="22dp"
        android:text="Static TextView" />

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView1"
        android:layout_marginLeft="12dp"
        android:layout_marginTop="12dp" >
    </ListView>

</RelativeLayout>

MainActivity.java

此处MainActivity扩展ListActivity,您有setContentView(R.layout.activity_main);。除了listview之外,activity_main.xml还有其他观点。

因此,您需要在xml

中包含ID为android:id="@android:id/list"的列表视图
public class MainActivity extends ListActivity {

    String[] array ={"A","B","C","D","E"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView lv = getListView();
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,array);
        lv.setAdapter(adapter);

    }

}

对齐

请参见快照,它有静态文本视图。

enter image description here

现在我更改了如下ID。我的布局中仍然有TextView没有其他更改

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

App崩溃

 03-25 04:16:02.022: E/AndroidRuntime(1275): Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'

如果人们仍然不明白并且说不清楚并且不愿意,他们应该在评论中提到原因。我很乐意编辑。

如果您不想要其他任何其他视图,则显示的默认列表不需要setContentView(R.layout.activity_main);。例如。

public class MainActivity extends ListActivity {

    String[] array ={"A","B","C","D","E"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,array);
        setListAdapter(adapter);

    }

}

除了显示的默认列表外,上面没有其他视图。

答案 1 :(得分:1)

如果您使用的是ListActivity,那么您的布局必须包含ID为@android:id/list

的ListView

更改ListView

中的activity_main.xml
<ListView android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"/>

您也可以使用

lv = getListView();

而不是

lv = (ListView)findViewById(R.id.list);

答案 2 :(得分:1)

试试这个..

重命名ListView的ID,如下所示

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

更多参考Link

您的ListView初始化如下

ListView lv = getListView();