【问题标题】:Nothing is populated from ArrayList to ListView没有从 ArrayList 填充到 ListView
【发布时间】:2015-06-08 07:32:32
【问题描述】:

我正在尝试使用 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。

【问题讨论】:

  • 发布崩溃日志。
  • 我认为应该是 webservice 而不是 php,或者你可以说是用 PHP 实现的 web services。
  • 我认为您必须通过使用 ArrayAdapter&lt;FoodStores&gt; 扩展类来为您的问题制作自定义适配器。
  • 如果以下任一答案满足您的查询,请将其标记为已接受。

标签: java android listview


【解决方案1】:

你没有提供所有的课程,所以有些课程是我提供的。 你在这里:

选择类别.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;
    }

}

其余文件未动。

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 我这样做了,它说Cannot resolve constructor ArrayAdapter
    • 它在 lv.setAdapter 行给出 java.lang.NullPointerException
    • 这个Log Log.e("Response: ", " > " + json);
    • E/Response:﹕> {"storelistfood":[{"id":"1","STORENAME":"PizzaHut"}
    【解决方案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): 在 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,它是您布局中的TextView,ArrayAdapter需要显示内容。

    如果还没有完成,请记住重写 FoodStores 中的 toString() 方法以返回一些逻辑字符串,例如名称(如上面@Alex 所建议的那样)。

    希望这会有所帮助。

    【讨论】:

      【解决方案4】:

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

                   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 wouldnt想改变你的应用程序的架构,你应该在onPostExecute设置适配器后调用notifydatasetchanged()。

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

      【讨论】:

        【解决方案5】:

        我在这里看到了 3 个问题

        1. 您需要创建一个自定义适配器,该适配器从 阵列适配器 您不能直接使用 ArrayAdapter [在此处输入链接描述][1] [1]: http://developer.android.com/reference/android/widget/ArrayAdapter.html

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

        3. 如果您的 活动扩展了 listactivity 然后就像你在 xml 中做 listview 的 id 应该是 @android:id/list 但然后是 ListView lv = getListView() 或 您的活动只是扩展了活动,而 listview 的 id 在 xml 中 应该是 @+id/list 然后 ListView lv = (ListView)findViewById(R.id.list)

        【讨论】:

          【解决方案6】:

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2015-08-22
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-12-31
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多