Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/191.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从ArrayList到ListView没有填充任何内容_Java_Android_Listview - Fatal编程技术网

Java 从ArrayList到ListView没有填充任何内容

Java 从ArrayList到ListView没有填充任何内容,java,android,listview,Java,Android,Listview,我正在尝试使用ListView将一些项目从PHP填充到Android public class ChooseCategory extends ListActivity { private ListView lv; ArrayAdapter<FoodStores> arrayAdapter; private static final String TAG = MainActivity.class.get

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

在onPost方法中移动此行:

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

将以下内容替换为

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

我在这里看到三个问题

您需要创建一个扩展自的自定义适配器 定制 您不能直接使用ArrayAdapter[在此处输入链接说明][1][1]:

需要在onPostExecute中创建阵列适配器,或者 需要告诉适配器arraylist已更改

如果你的 活动扩展了listactivity,就像在xml中扩展listview的id一样 应该是@android:id/list,然后是ListView lv=getListView或 您的活动只是扩展了活动,listview的id是xml格式的 应为@+id/list,然后为ListView lv= ListViewfindViewByIdR.id.list
你没有提供所有的课程,所以有些课程是由我提供的。 给你:

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

}

其余文件未被触及。

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

06-22 21:22:42.535:E/AndroidRuntime6531:致命异常:主 06-22 21:22:42.535:E/AndroidRuntime6531: java.lang.IllegalStateException:ArrayAdapter需要资源ID 成为文本视图06-22 21:22:42.535:E/AndroidRuntime6531:at android.widget.ArrayAdapter.createViewFromResourceArrayAdapter.java:386 06-22 21:22:42.535:E/AndroidRuntime6531:at android.widget.ArrayAdapter.getViewArrayAdapter.java:362

最简单的解决办法就是更换

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

请注意附加参数R.id.Itemname,它是版面中ArrayAdapter显示内容所需的文本视图

还请记住在FoodStores中重写toString方法,以返回一些逻辑字符串,如名称(如果没有按照上面@Alex的建议执行)


希望这有帮助

尝试使用毕加索实现图像,并做更多一件事,请使用任何其他web服务,因此请检查此代码中的此web服务,以便清楚代码是否正常工作。在那之后,对你来说会更容易。如果有,一定要告诉我

我不确定,但这句话不好,因为:

             storefoodList = new ArrayList<FoodStores>();
            new GetFoodStores().execute();
        arrayAdapter = new ArrayAdapter<FoodStores>  (this,R.layout.restaurant_list,storefoodList );
您为适配器提供了一个空的arrayList,因为AsyncTaks仍在加载内容。因此,在本例中,适配器缓存一个空列表,当您在onPostExecute调用lw.setAdapteradapter时,它将提供给listview。 如果您不想更改应用程序的体系结构,则应在onPostExecute中设置适配器后调用notifydatasetchanged


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

我这样做了,它说无法解析构造函数ArrayAdapter在lv.setAdapter行上给出java.lang.NullPointerException此日志中的值是什么。eResponse:,>+json;E/答复:﹕ > {storelistfood:[{id:1,STORENAME:PizzaHut}让我们来发布崩溃日志。我认为应该是webservice而不是php,或者可以说是用php实现的web服务。我认为您必须通过使用ArrayAdapter扩展类来为您的问题定制适配器。如果以下任何答案满足您的查询,请将其标记为已接受。
public class FoodStores {

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

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

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