简体   繁体   English

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

[英]App crashes when retrieving data from mysql into listview

I am trying to retrieve data from mysql and load into listview.But the app crashes when I try to run it.I am not able to solve the errors.The JSON response is working fine and the results are displayed in the browser.Please help.This is the MainActivity file 我正在尝试从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

        }


    });
    }
     }

The logcat looks like this 日志猫看起来像这样

    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

Please suggest me what changes should I do. 请建议我应该做哪些更改。

Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list' 由以下原因引起的:java.lang.RuntimeException:您的内容必须具有ID属性为“ android.R.id.list”的ListView。

You have 你有

public class MainActivity extends ListActivity {

And then 接着

setContentView(R.layout.activity_main);

So you need to have a ListView in activity_main.xml with id as below 因此,您需要在activity_main.xml具有一个ID为如下的ListView

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

Also remove 同时删除

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

You can use lv = getListView() 您可以使用lv = getListView()

Quoting docs 报价文件

ListActivity has a default layout that consists of a single, full-screen list in the center of the screen. ListActivity具有默认布局,该布局由位于屏幕中央的单个全屏列表组成。 However, if you desire, you can customize the screen layout by setting your own view layout with setContentView() in onCreate(). 但是,如果需要,可以通过使用onCreate()中的setContentView()设置自己的视图布局来自定义屏幕布局。 To do this, your own view MUST contain a ListView object with the id "@android:id/list" (or list if it's in code) 为此,您自己的视图必须包含ID为“ @android:id / list”(或列表,如果在代码中,则为List)的ListView对象

Apart of all these you are doing Network operation on the main ui thread. 除了这些,您还需要在主ui线程上进行网络操作。 You need to use a Thread or AsyncTask . 您需要使用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

You will get NetworkOnMainThreadException . 您将获得NetworkOnMainThreadException

The exception that is thrown when an application attempts to perform a networking operation on its main thread. 当应用程序尝试在其主线程上执行联网操作时引发的异常。

This is only thrown for applications targeting the Honeycomb SDK or higher. 仅针对面向Honeycomb SDK或更高版本的应用程序抛出此错误。 Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged 允许以较早版本的SDK为目标的应用程序在其主事件循环线程上进行联网,但不建议这样做

Edit: 编辑:

Seems there is lot of confusion. 似乎有很多混乱。 People want more accurate answer. 人们想要更准确的答案。 SO i will post an example 所以我会举一个例子

Example: 例:

In the below we have a TextView and a ListView 在下面,我们有一个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.java

Here MainActivity extends ListActivity and you have setContentView(R.layout.activity_main); 在这里MainActivity扩展了ListActivity并且您有setContentView(R.layout.activity_main); . activity_main.xml has other views apart from listview. activity_main.xml除了listview外还有其他视图。

So you need a listview with id android:id="@android:id/list" in your xml 因此,您需要在XML中使用ID为android:id="@android:id/list"的listview

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

    }

}

Snap 快照

See the snap it has a static textview. 查看快照,它具有静态textview。

在此处输入图片说明

Now i changed the id as below. 现在,我将ID更改如下。 I still had the TextView in my layout nothing else changed 我的布局中仍然有TextView

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

App crashes 应用程序崩溃

 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'

Well if people still don't understand and say its not clear and downvote they should mention the reason in the comment. 好吧,如果人们仍然不明白并说不清,并且投票不足,则应在评论中提及原因。 I will be happy to edit. 我将很高兴进行编辑。

If you don't want any other views other then the default list displayed there is no need for setContentView(R.layout.activity_main); 如果您不希望其他任何视图,那么将显示默认列表,则无需setContentView(R.layout.activity_main); . For example. 例如。

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

    }

}

In the above there are no other views except the default list displayed. 上面没有其他视图,只显示默认列表。

If you are using ListActivity then your layout must have ListView which id is @android:id/list 如果您使用的是ListActivity,则您的布局必须具有ID为@android:id/list ListView

Change your ListView in activity_main.xml activity_main.xml更改您的ListView

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

You can also use 您也可以使用

lv = getListView();

instead of 代替

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

Try this.. 尝试这个..

Rename the id of your ListView like below, 如下重命名ListView的ID,

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

For more Reference Link 有关更多参考链接

Do your ListView initialize like below 你的ListView初始化如下

ListView lv = getListView();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从SQLite数据库检索数据时Android应用程序崩溃 - Android app crashes when retrieving data from SQLite database 从 Firebase 数据库检索数据时应用程序崩溃 - App crashes when retrieving data from firebase database 当我单击执行数据库操作的按钮时,我的应用程序崩溃(在ListView中检索和显示数据) - My App crashes when I click on the button which perform DBoperation(Retrieving and displaying data in ListView) 从mysql崩溃的应用填充可扩展Listview - Populate Expandable Listview from mysql crashes app 用户输入所有数据后检索数据时应用程序崩溃? - App crashes when retrieving data after user input all data? 从Firebase数据库检索数据到Recyclerview时,应用程序崩溃 - App crashes while retrieving data from firebase database into Recyclerview 从另一个活动中的意图检索int时,Android应用程序崩溃 - Android app crashes when retrieving int from an intent in another activity Android应用程序从MySql数据库检索数据? - Android app retrieving data from MySql database? 从mysql检索数据时应用崩溃 - App crashing while retrieving data from mysql 当我尝试从Firestore提取数据并显示在listview片段中时,我的应用程序崩溃 - My app crashes when i try to fetch data from Firestore and display in the listview fragment
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM