English 中文(简体)
Asynctask HTTP没有在 ListView 中显示结果吗?
原标题:Android Asynctask HTTP not showing results in ListView?

I m pretty new to Android programming so any help would be great :) I m trying to get some dummy data remotely, parse the json response and display it within a listview.

这是 xml 版面布局文件 Im 试图与列表活动一起使用 : -

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <ListView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/list"
    />
</LinearLayout>

这是我的http搜索活动:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
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.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class searchResultActivity extends ListActivity {

    ListView listview;
    String result = null;
    InputStream is = null;
    StringBuilder sb = null;
    String url;
    String fd_name;
    ArrayList<String> listItems;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        /*setContentView(R.layout.test);
        listview = (ListView)findViewById(R.id.list);*/
        url = "http://pjchambers.comuf.com/index.php";
        new getData().execute();
    }

    public class getData extends AsyncTask<String, Void, ArrayList<String>> {

        protected ArrayList<String> doInBackground(String...urls) {
            // TODO Auto-generated method stub
            listItems = new ArrayList<String>();

            try {
                // Set of http statements setting up the connections to the php
                // and database
                HttpClient httpclient = new DefaultHttpClient();
                HttpGet httpget = new HttpGet(url);
                HttpResponse response = httpclient.execute(httpget);
                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() + "
");
                String line = "0";
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "
");
                }
                is.close();
                result = sb.toString();
            } catch (Exception e) {
                Log.e("log_tag", "Error converting result " + e.toString());
            }

            // paring data
            try {
                JSONArray jArray = new JSONArray(result);
                JSONObject json_data = null;
                for (int i = 0; i < jArray.length(); i++) {
                    json_data = jArray.getJSONObject(i);
                    fd_name = json_data.getString("Name");
                    listItems.add(fd_name);
                }
            } catch (JSONException e1) {
                Toast.makeText(getBaseContext(), "No Results Found",
                        Toast.LENGTH_LONG).show();
            } catch (ParseException e1) {
                e1.printStackTrace();
            }

            Log.d("debug", "- " + listItems.toString());
            return listItems;
        }

        protected void doPostExecute() {
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                    searchResultActivity.this, android.R.layout.simple_list_item_1, R.id.list, listItems);
            setListAdapter(adapter);
        }

    }

}

我花了数小时尝试不同的方法与方法, 使用几个不同的在线教义, 但最终结果都是一样的。 应用程序的当前功能是起作用的, 但是显示显示显示显示; 但是, 如果我宣布软件在软件上的方法布局会崩溃, 任何帮助或建议都会受到赞赏, 新的一双眼睛会立即注意到问题。

这是在我对这两个语句不作评论之后的日志

05-22 12:12:20.234: D/debug(631): - [The Arena, Empire]
05-22 12:12:42.004: I/dalvikvm(691): threadid=3: reacting to signal 3
05-22 12:12:42.244: I/dalvikvm(691): Wrote stack traces to  /data/anr/traces.txt 
05-22 12:12:42.404: D/gralloc_goldfish(691): Emulator without GPU emulation detected.
05-22 12:12:48.415: I/dalvikvm(691): threadid=3: reacting to signal 3
05-22 12:12:48.424: I/dalvikvm(691): Wrote stack traces to  /data/anr/traces.txt 
05-22 12:12:50.595: D/AndroidRuntime(691): Shutting down VM
05-22 12:12:50.595: W/dalvikvm(691): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
05-22 12:12:50.614: E/AndroidRuntime(691): FATAL EXCEPTION: main
05-22 12:12:50.614: E/AndroidRuntime(691): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.project.barcrawl/com.project.barcrawl.searchResultActivity}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is  android.R.id.list 
05-22 12:12:50.614: E/AndroidRuntime(691):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
05-22 12:12:50.614: E/AndroidRuntime(691):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
05-22 12:12:50.614: E/AndroidRuntime(691):  at android.app.ActivityThread.access$600(ActivityThread.java:123)
05-22 12:12:50.614: E/AndroidRuntime(691):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
05-22 12:12:50.614: E/AndroidRuntime(691):  at android.os.Handler.dispatchMessage(Handler.java:99)
05-22 12:12:50.614: E/AndroidRuntime(691):  at android.os.Looper.loop(Looper.java:137)
05-22 12:12:50.614: E/AndroidRuntime(691):  at android.app.ActivityThread.main(ActivityThread.java:4424)
05-22 12:12:50.614: E/AndroidRuntime(691):  at java.lang.reflect.Method.invokeNative(Native Method)
05-22 12:12:50.614: E/AndroidRuntime(691):  at java.lang.reflect.Method.invoke(Method.java:511)
05-22 12:12:50.614: E/AndroidRuntime(691):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
05-22 12:12:50.614: E/AndroidRuntime(691):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
05-22 12:12:50.614: E/AndroidRuntime(691):  at dalvik.system.NativeStart.main(Native Method)
05-22 12:12:50.614: E/AndroidRuntime(691): Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is  android.R.id.list 
05-22 12:12:50.614: E/AndroidRuntime(691):  at android.app.ListActivity.onContentChanged(ListActivity.java:243)
05-22 12:12:50.614: E/AndroidRuntime(691):  at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:254)
05-22 12:12:50.614: E/AndroidRuntime(691):  at android.app.Activity.setContentView(Activity.java:1835)
05-22 12:12:50.614: E/AndroidRuntime(691):  at com.project.barcrawl.searchResultActivity.onCreate(searchResultActivity.java:41)
05-22 12:12:50.614: E/AndroidRuntime(691):  at android.app.Activity.performCreate(Activity.java:4465)
05-22 12:12:50.614: E/AndroidRuntime(691):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
05-22 12:12:50.614: E/AndroidRuntime(691):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
05-22 12:12:50.614: E/AndroidRuntime(691):  ... 11 more
05-22 12:12:51.004: I/dalvikvm(691): threadid=3: reacting to signal 3
05-22 12:12:51.024: I/dalvikvm(691): Wrote stack traces to  /data/anr/traces.txt 
最佳回答

您在 XML 中的 id 应该 < code> id=" @android:id/ list" , 这样它应该起作用。 在您的代码中, 在“ 你” R. class 中创建了一个新的 id, 与 android. R.id. list 不同。 因此无法找到列表视图, 因此会丢弃例外 。

另外, ArrayAdapter 构建器的第三个参数应该是要填充数据的文本资源的代号。 您正在通过 R. id. list 错误的 。 对于 android. R.id. semple_ list_ item_ 1 定义的资源, 如果我没有弄错, 它应该是 android. R.id. text1

问题回答

暂无回答




相关问题
Android - ListView fling gesture triggers context menu

I m relatively new to Android development. I m developing an app with a ListView. I ve followed the info in #1338475 and have my app recognizing the fling gesture, but after the gesture is complete, ...

AsyncTask and error handling on Android

I m converting my code from using Handler to AsyncTask. The latter is great at what it does - asynchronous updates and handling of results in the main UI thread. What s unclear to me is how to handle ...

Android intent filter for a particular file extension?

I want to be able to download a file with a particular extension from the net, and have it passed to my application to deal with it, but I haven t been able to figure out the intent filter. The ...

Android & Web: What is the equivalent style for the web?

I am quite impressed by the workflow I follow when developing Android applications: Define a layout in an xml file and then write all the code in a code-behind style. Is there an equivalent style for ...

TiledLayer equivalent in Android [duplicate]

To draw landscapes, backgrounds with patterns etc, we used TiledLayer in J2ME. Is there an android counterpart for that. Does android provide an option to set such tiled patterns in the layout XML?

Using Repo with Msysgit

When following the Android Open Source Project instructions on installing repo for use with Git, after running the repo init command, I run into this error: /c/Users/Andrew Rabon/bin/repo: line ...

Android "single top" launch mode and onNewIntent method

I read in the Android documentation that by setting my Activity s launchMode property to singleTop OR by adding the FLAG_ACTIVITY_SINGLE_TOP flag to my Intent, that calling startActivity(intent) would ...

From Web Development to Android Development

I have pretty good skills in PHP , Mysql and Javascript for a junior developer. If I wanted to try my hand as Android Development do you think I might find it tough ? Also what new languages would I ...