从ArrayList到ListView没有任何内容

时间:2015-06-08 07:32:33

标签: java android listview

我正在尝试使用ListView将一些项目从PHP填充到Android

    public class ChooseCategory extends ListActivity {

            private ListView lv;
            ArrayAdapter<FoodStores> arrayAdapter;

            private static final String TAG = MainActivity.class.getSimpleName();
            private ArrayList<FoodStores> storefoodList;
            // JSON parser class
            JSONParser jsonParser = new JSONParser();
            //ids
            private static final String TAG_SUCCESS = "success";
            private static final String TAG_MESSAGE = "message";
            private String URL_STORES = "http://www.123.com/get_stores.php";

        @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                //setContentView(R.layout.activity_main);
                //lv = (ListView) findViewById(R.id.list_item);
                 lv = (ListView)findViewById(android.R.id.list);
                storefoodList = new ArrayList<FoodStores>();
                new GetFoodStores().execute();


            arrayAdapter = new ArrayAdapter<FoodStores>  (this,R.layout.restaurant_list,storefoodList );


     private class GetFoodStores extends AsyncTask<Void,Void,Void> {
            @Override
            protected void onPreExecute(){
                super.onPreExecute();
            }

            @Override
            protected Void doInBackground(Void... arg0) {
                ServiceHandlerFood jsonParserFood = new ServiceHandlerFood();
                String json = jsonParserFood.makeServiceCall(URL_STORES, ServiceHandlerFood.GET);
                Log.e("Response: ", " > " + json);
                if(json != null){
                    try{
                        JSONObject jsonObj = new JSONObject(json);
                        if(jsonObj != null){
                            JSONArray storeListFood = jsonObj.getJSONArray("storelistfood");
                            for(int i = 0; i < storeListFood.length(); i++){
                                JSONObject storeFoodObj = (JSONObject) storeListFood.get(i);
                                FoodStores foodStores = new FoodStores(storeFoodObj.getInt("id"),storeFoodObj.getString("STORENAME"));
                                storefoodList.add(foodStores);

                            }
                        }
                    }catch(JSONException e){
                        e.printStackTrace();
                    }
                }else{
                    Log.e("JSON Data", "No data received from server");
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void result){
                super.onPostExecute(result);
                lv.setAdapter(arrayAdapter);
            }
        }
}

activity_main.xml中

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="{relativePackage}.${activityClass}" >

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

restaurant_list.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >
    <ImageView
        android:id="@+id/icon"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginBottom="5dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="5dp"
        android:src="@drawable/nasilemak2" />
    <TextView
        android:id="@+id/Itemname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:paddingTop="5dp"/>
</LinearLayout>

我得到的错误是它只显示空白屏幕并在一分钟后崩溃。我想使用PHP中的ArrayList填充ListView。

6 个答案:

答案 0 :(得分:7)

您没有提供所有课程,因此我提供了一些课程。 你在这里:

Screenshot

ChooseCategory.java:

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class ChooseCategory extends ListActivity {

    private ListView lv;
    ArrayAdapter<FoodStores> arrayAdapter;

    private static final String TAG = "XXX";
    private ArrayList<FoodStores> storefoodList;
    // JSON parser class
    // JSONParser jsonParser = new JSONParser();
    // ids
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";
    private String URL_STORES = "http://echo.jsontest.com/id/1/STORENAME/Perogi";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lv = (ListView) findViewById(android.R.id.list);
        storefoodList = new ArrayList<FoodStores>();
        new GetFoodStores().execute();

        arrayAdapter = new ArrayAdapter<FoodStores>(this,
                R.layout.restaurant_list, R.id.Itemname, storefoodList);
        lv.setAdapter(arrayAdapter);
    }

    private class GetFoodStores extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... arg0) {
            ServiceHandlerFood jsonParserFood = new ServiceHandlerFood();
            String json = jsonParserFood.makeServiceCall(URL_STORES,
                    "TEST");
                    //ServiceHandlerFood.GET);
            Log.e("Response: ", " > " + json);
            if (json != null) {
                try {
                    JSONObject jsonObj = new JSONObject(json);
                    if (jsonObj != null) {
                        JSONArray storeListFood = jsonObj
                                .getJSONArray("storelistfood");
                        for (int i = 0; i < storeListFood.length(); i++) {
                            JSONObject storeFoodObj = (JSONObject) storeListFood
                                    .get(i);
                            FoodStores foodStores = new FoodStores(
                                    storeFoodObj.getInt("id"),
                                    storeFoodObj.getString("STORENAME"));
                            storefoodList.add(foodStores);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("JSON Data", "No data received from server");
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            lv.setAdapter(arrayAdapter);
        }
    }
}

Foodstores.java:

public class FoodStores {

    int id;
    String name;
    public FoodStores(int id, String string) {
        this.id=id;
        name=string;
    }
    @Override
    public String toString(){
        return name;
    }

}

ServiceHandlerFood.java:

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.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;

public class ServiceHandlerFood {

    public static final String GET = "GET";

    public String makeServiceCall(String uRL_STORES, String get2) {
        if ("TEST".equals(get2))
            return "{'storelistfood':[{'id':1, 'STORENAME':'Arbys'},{'id':2, 'STORENAME':'Perogi'},{'id':3, 'STORENAME':'McDonalds'}]}";

        DefaultHttpClient httpclient = new DefaultHttpClient(
                new BasicHttpParams());
        HttpPost httppost = new HttpPost(uRL_STORES);
        httppost.setHeader("Content-type", "application/json");

        InputStream inputStream = null;
        String result = null;
        try {
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();

            inputStream = entity.getContent();
            // json is UTF-8 by default
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    inputStream, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();

            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            result = sb.toString();
        } catch (Exception e) {
            // Oops
        } finally {
            try {
                if (inputStream != null)
                    inputStream.close();
            } catch (Exception squish) {
            }
        }
        return result;
    }

}

其余文件没有动过。

答案 1 :(得分:3)

在onPost方法中移动此行:

arrayAdapter = new ArrayAdapter<FoodStores>  `(this,R.layout.restaurant_list,storefoodList );`

喜欢这个

 @Override
            protected void onPostExecute(Void result){
                super.onPostExecute(result);
arrayAdapter = new ArrayAdapter<FoodStores>  (this,R.layout.restaurant_list,storefoodList );
                lv.setAdapter(arrayAdapter);
            }

修改:

并将"this"更改为getApplicationContext(),就像这样

arrayAdapter = new ArrayAdapter<FoodStores>  (getApplicationContext(),R.layout.restaurant_list,storefoodList );

修改1:

将以下内容替换为

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

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

答案 2 :(得分:3)

代码的主要问题是,ArrayAdapter的默认实现需要一个TextView,在其中它将列表项显示为字符串。如果没有提供,它将抛出异常,如

  

06-22 21:22:42.535:E / AndroidRuntime(6531):致命异乎寻常:主要   06-22 21:22:42.535:E / AndroidRuntime(6531):   java.lang.IllegalStateException:ArrayAdapter需要资源ID   成为TextView 06-22 21:22:42.535:E / AndroidRuntime(6531):at   android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:386)   06-22 21:22:42.535:E / AndroidRuntime(6531):at   android.widget.ArrayAdapter.getView(ArrayAdapter.java:362)

最简单的解决方案就是替换

arrayAdapter = new ArrayAdapter<FoodStores>  (this,R.layout.restaurant_list,storefoodList );

arrayAdapter = new ArrayAdapter<FoodStores>  (this,R.layout.restaurant_list,R.id.Itemname,storefoodList);

请注意附加参数 R.id.Itemname ,它是布局中TextAdapter需要显示内容的TextView。

还请记得覆盖FoodStores中的toString()方法,如果没有完成,则返回一些逻辑字符串,如上面的@Alex所示。

希望这会有所帮助。

答案 3 :(得分:2)

我不确定,但这条线不好,因为:

             storefoodList = new ArrayList<FoodStores>();
            new GetFoodStores().execute();
        arrayAdapter = new ArrayAdapter<FoodStores>  (this,R.layout.restaurant_list,storefoodList );

您将一个空的arrayList提供给适配器,因为AsyncTaks仍在加载内容。所以在这种情况下,适配器缓存一个空列表,然后s going to provide to the listview when you call the lw.setAdapter(adapter) at onPostExecute. If you wouldn想改变应用程序的体系结构,在onPostExecute中设置适配器后,应该调用 notifydatasetchanged ()

或者您可以使用更新的列表onPostExecute初始化适配器,并将其设置为ListView。

答案 4 :(得分:0)

我在这里看到3个问题

  1. 您需要创建一个从中扩展的自定义适配器 ArrayAdapter     你不能直接使用ArrayAdapter [在这里输入链接描述] [1] [1]: http://developer.android.com/reference/android/widget/ArrayAdapter.html

  2. 要么在onPostExecute中创建数组适配器,要么就是你     需要告诉你的适配器arraylist已经改变了

  3. 如果你的         当你在xml中执行listview的id时,activity会扩展listactivity         应该是@android:id / list但是然后ListView lv = getListView()或         你的活动只是扩展Activity而listview的id是xml         应该是@ + id / list然后ListView lv =         (ListView的)findViewById(R.id.list)

答案 5 :(得分:0)

尝试使用Picasso实现图像,并做更多的事情,请做任何其他Web服务,所以请在此代码中检查此Web服务,以便清除代码将正常工作。在那之后,对你来说更容易。如果有的话,请告诉我。