【问题标题】:ListView items doesn't loaded using AsyncTaskListView 项目未使用 AsyncTask 加载
【发布时间】:2012-10-06 07:12:58
【问题描述】:

首先,我要感谢曾经在这个社区中帮助过我的每一个人。

我正在尝试在我的 Activity 中加载 Listview 项目(从服务器下载)。因为我使用的是 GingerBread,所以我尝试在没有 AsyncTask 的情况下执行此操作,并且效果很好。

当我尝试在 AsyncTask 中执行此操作时,列表仍然为空。 我还尝试将某些部分从 DoInBackground 移动到 onPostExecute 并且没有任何变化。所以你能帮帮我吗。

这是我的代码(在第二个答案后更新)

MAIN



import java.util.ArrayList;
import java.util.HashMap;

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



import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class StudentMSG extends ListActivity {
    // url to make request
    private static String url = "http://www.xxxxxxxxxxxxx?requsted=xxxxxxxxx";
    // JSON Node names
    private static final String TAG_CONTACTS = "contacts";
    private static final String TAG_ID = "message_id";
    private static final String TAG_NAME = "sender_id";
    private static final String TAG_EMAIL = "title";
    private static final String TAG_ADDRESS = "message_id";
    private static final String TAG_GENDER = "READ";
    private static final String TAG_PHONE = "message_id";
    private static final String TAG_PHONE_MOBILE = "message_id";
    private static final String TAG_PHONE_HOME = "message_id";
    private static final String TAG_PHONE_OFFICE = "message_id";
    ListView lv;
    ArrayList<HashMap<String, String>> contactList ;
    JSONObject json ;
    ListAdapter adapter;
    // contacts JSONArray
    JSONArray contacts = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        load task=new load();
        task.execute();





    }



    public class load extends AsyncTask<Void, Void , Void>
    {
        @Override
        protected Void doInBackground(Void... params) {

            // Hashmap for ListView
            contactList = new ArrayList<HashMap<String, String>>();

            // Creating JSON Parser instance
            JSONParser jParser = new JSONParser();

            // getting JSON string from URL
             json = jParser.getJSONFromUrl(url);
                try {
                    contacts = json.getJSONArray(TAG_CONTACTS);
                // looping through All Contacts
                for(int i = 0; i < contacts.length(); i++){
                    JSONObject c = contacts.getJSONObject(i);

                    // Storing each json item in variable
                    String id = c.getString(TAG_ID);
                    String name = c.getString(TAG_NAME);
                    String email = c.getString(TAG_EMAIL);
                    String address = c.getString(TAG_ADDRESS);
                    String gender = c.getString(TAG_GENDER);

                    // Phone number is agin JSON Object


                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_ID, id);
                    map.put(TAG_NAME, name);
                    map.put(TAG_EMAIL, email);
                    map.put(TAG_GENDER, gender);


                    // adding HashList to ArrayList
                    contactList.add(map);
                }
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            return null;



        }
        protected void onPostExecute() {

            String[] s = { TAG_NAME, TAG_EMAIL , TAG_GENDER};
            int[] n = {R.id.name, R.id.email , R.id.mobile };
          adapter = new SimpleAdapter(StudentMSG.this, contactList,R.layout.list_item,s,n );
            setListAdapter(adapter);
    }
}
}

这是 JSON 解析器类

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();           

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //"ISO-8859-1,utf-8;q=0.7,*;q=0.7"
        //"iso-8859-1"
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "utf-8"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

最好的问候。

【问题讨论】:

    标签: java android json listview android-asynctask


    【解决方案1】:
    replace ur code by this=
    import java.util.ArrayList;
    import java.util.HashMap;
    
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    
    
    import android.app.Activity;
    import android.app.ListActivity;
    import android.content.Intent;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.ListAdapter;
    import android.widget.ListView;
    import android.widget.ProgressBar;
    import android.widget.SimpleAdapter;
    import android.widget.TextView;
    import android.widget.Toast;
    
    public class StudentMSG extends ListActivity {
        // url to make request
        private static String url = "XXXXXXXXXXXXXXXXXXXX/json.php";
        // JSON Node names
        private static final String TAG_CONTACTS = "contacts";
        private static final String TAG_ID = "message_id";
        private static final String TAG_NAME = "sender_id";
        private static final String TAG_EMAIL = "title";
        private static final String TAG_ADDRESS = "message_id";
        private static final String TAG_GENDER = "READ";
        private static final String TAG_PHONE = "message_id";
        private static final String TAG_PHONE_MOBILE = "message_id";
        private static final String TAG_PHONE_HOME = "message_id";
        private static final String TAG_PHONE_OFFICE = "message_id";
        ListView lv;
        ArrayList<HashMap<String, String>> contactList ;
        JSONObject json ;
        ListAdapter adapter;
        // contacts JSONArray
        JSONArray contacts = null;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            load task=new load();
            task.execute();
    
    
    
    
    
        }
    
    
    
        public class load extends AsyncTask<Void, Void , Void>
        {
            @Override
            protected Void doInBackground(Void... params) {
    
                // Hashmap for ListView
                contactList = new ArrayList<HashMap<String, String>>();
    
                // Creating JSON Parser instance
                JSONParser jParser = new JSONParser();
    
                // getting JSON string from URL
                 json = jParser.getJSONFromUrl(url);
                    try {
                        contacts = json.getJSONArray(TAG_CONTACTS);
                    // looping through All Contacts
                    for(int i = 0; i < contacts.length(); i++){
                        JSONObject c = contacts.getJSONObject(i);
    
                        // Storing each json item in variable
                        String id = c.getString(TAG_ID);
                        String name = c.getString(TAG_NAME);
                        String email = c.getString(TAG_EMAIL);
                        String address = c.getString(TAG_ADDRESS);
                        String gender = c.getString(TAG_GENDER);
    
                        // Phone number is agin JSON Object
    
    
                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();
    
                        // adding each child node to HashMap key => value
                        map.put(TAG_ID, id);
                        map.put(TAG_NAME, name);
                        map.put(TAG_EMAIL, email);
                        map.put(TAG_GENDER, gender);
    
    
                        // adding HashList to ArrayList
                        contactList.add(map);
                    }
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                return null;
    
    
    
            }
            protected void onPostExecute() {
    
                String[] s = { TAG_NAME, TAG_EMAIL , TAG_GENDER};
                int[] n = {R.id.name, R.id.email , R.id.mobile };
              adapter = new SimpleAdapter(StudentMSG.this, contactList,R.layout.list_item,s,n );
                setListAdapter(adapter);
    
        }
    }
    

    【讨论】:

    • 同样的事情 :( 。我提供了我的问题的完整代码 :( 感谢 Shyam 参与
    【解决方案2】:

    你不能通知 SimpleAdapter 您需要使用 ArrayAdapter 来通知数据... 如果你想在每个列表项中有不同的视图,你需要通过 BaseAdapter

    【讨论】:

    • 当我将前 4 行放入 onCreate 时它崩溃了!我把所有的代码都放在 PostExcute 里面,同样的结果是空的
    • 也 eclipse 要求我将适配器转换成这样 ((BaseAdapter) 适配器).notifyDataSetChanged();
    【解决方案3】:

    本教程表明我想要什么和意思.. http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/ 感谢所有参与者..

    【讨论】:

      【解决方案4】:

      关于你的帖子执行方法:

      protected void onPostExecute() {
          runOnUiThread(new Runnable() {
             public void run() {
                   String[] s = { TAG_NAME, TAG_EMAIL , TAG_GENDER};
                   int[] n = {R.id.name, R.id.email , R.id.mobile };
                   adapter = new SimpleAdapter(StudentMSG.this, contactList,R.layout.list_item,s,n );
                   setListAdapter(adapter);
      }}};
      

      这将防止它崩溃。希望有帮助

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-09-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-05
        • 1970-01-01
        相关资源
        最近更新 更多