使用Asynctask在listview中显示数据

时间:2012-05-15 03:37:23

标签: android listview android-asynctask

我在listview中成功显示来自Web服务JSON的数据,但我想添加Asyntask .. 我可以在我的代码中放置代码Asyntask ..

这是我在列表视图中显示数据的代码

public class Jadwal_remix extends ListActivity {
String v_date;
JSONArray r_js = null;
ArrayList<HashMap<String, String>> myArray = new ArrayList<HashMap<String,String>>();
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.main);





    String status ="";
    String date = "";
    String result = "";
    String url = "http://10.0.2.2/remix/view_list.php";
    JSONParser jParser = new JSONParser();
    JSONObject json = jParser.AmbilJson(url);
    try
    {
        r_js = json.getJSONArray("view_list");

        for (int i =0; i < r_js.length(); i++)
        {
            String my_array = "";
            JSONObject ar = r_js.getJSONObject(i);
            status = ar.getString("st");
            date = ar.getString("date");
            result = ar.getString("result");

            if (status.trim().equals("er"))
            {
                my_array += "Sorry "+result;
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("result", my_array);
                myArray.add(map);
            }
            else
            {
                my_array += "Date : "+date+" "+"Result : "+result;
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("result", my_array);
                myArray.add(map);
            }

        }
    }
    catch (JSONException e) 
    {
         e.printStackTrace();
    }
    adapter_listview();

}

public void adapter_listview() {

    ListAdapter adapter = new SimpleAdapter(this, jadwalRemix,R.layout.my_list,new String[] { "result"}, new int[] {R.id.txtResult});
    setListAdapter(adapter);
}
}

这个JSONParser

public class JSONParser {

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

// constructor
public JSONParser() {

}

public JSONObject AmbilJson(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();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 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;

}
 }

请帮助我,我可以为Asyntask提供代码.. 非常感谢..

好的,我收到示例代码,现在我的代码就像这样

public class Jadwal_remix extends ListActivity {
String v_date;
JSONArray r_js = null;
ArrayList<HashMap<String, String>> myArray = new ArrayList<HashMap<String,String>>();
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.main);

private class myProses extends AsyncTask<Void, Void, Void> {
    ProgressDialog dialog;

    protected void onPreExecute() {
        dialog = ProgressDialog.show(Jadwal_remix.this, "", "Loading... Please wait", true);

    }
protected Void doInBackground(Void... params) {



    String status ="";
    String date = "";
    String result = "";
    String url = "http://10.0.2.2/remix/view_list.php";
    JSONParser jParser = new JSONParser();
    JSONObject json = jParser.AmbilJson(url);
    try
    {
        r_js = json.getJSONArray("view_list");

        for (int i =0; i < r_js.length(); i++)
        {
            String my_array = "";
            JSONObject ar = r_js.getJSONObject(i);
            status = ar.getString("st");
            date = ar.getString("date");
            result = ar.getString("result");

            if (status.trim().equals("er"))
            {
                my_array += "Sorry "+result;
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("result", my_array);
                myArray.add(map);
            }
            else
            {
                my_array += "Date : "+date+" "+"Result : "+result;
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("result", my_array);
                myArray.add(map);
            }

        }
    }
    catch (JSONException e) 
    {
         e.printStackTrace();
    }
    return null;
protected void onPostExecute(Void unused) {
        adapter_listview();
        dialog.dismiss();
    }

}

public void adapter_listview() {

    ListAdapter adapter = new SimpleAdapter(this, jadwalRemix,R.layout.my_list,new String[] { "result"}, new int[] {R.id.txtResult});
    setListAdapter(adapter);
}
}

当服务器死亡时我遇到问题,它仍在加载.. 我怎么能显示消息ex:无法连接到服务器.. ??

3 个答案:

答案 0 :(得分:0)

检查AsyncTask的这些示例

1。  Tutorial: AsyncTask

2。 Developer page

答案 1 :(得分:0)

Working ASyncTask tutorial

Full ASyncTask Eclipse Project

这里有一些代码我认为,当与上面的示例混合使用时,会得到你想要的列表的结果(你必须稍微调整一下你的需求)(注意清单)东西,即使这是来自自定义对话框:

    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("Kies Facebook-account");
        builder.setNegativeButton("Cancel", this);
        LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View dialogLayout = inflater.inflate(R.layout.dialog, null);
        builder.setView(dialogLayout);

        final String[] items = {"Red", "Green", "Blue" };

        builder.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items), 
                new DialogInterface.OnClickListener() {


            public void onClick(DialogInterface dialog, int which) {
                Log.v("touched: ", items[which].toString());

            }} 
            );


        return builder.create();

    }

答案 2 :(得分:0)

这是我的代码,请尝试这个,

MAinActivity.java

public class MyActivity extends Activity {

private ListView contests_listView;
private ProgressBar pgb;
ActivitiesBean bean;
ArrayList<Object> listActivities;
ActivityAdapter adapter;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_listview);

    contests_listView = (ListView) findViewById(R.id.activity_listView);
    pgb = (ProgressBar) findViewById(R.id.contests_progressBar);
    listActivities = new ArrayList<Object>();

    new FetchActivitesTask().execute();


}

public class FetchActivitesTask extends AsyncTask<Void, Void, Void> {

    int i =0;
    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
         pgb.setVisibility(View.VISIBLE);
    }

    @Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub

        String url = "Your URL Here";
        String strResponse = util.makeWebCall(url);

        try {
            JSONObject objResponse = new JSONObject(strResponse);

            JSONArray jsonnodes = objResponse.getJSONArray(nodes);

            for (i = 0; i < jsonnodes.length(); i++) 
            {
                String str = Integer.toString(i); 
                Log.i("Value of i",str);

                JSONObject jsonnode = jsonnodes.getJSONObject(i); 

                JSONObject jsonnodevalue = jsonnode.getJSONObject(node);

                bean = new ActivitiesBean();

                bean.title = jsonnodevalue.getString(title);
                bean.image = jsonnodevalue.getString(field_activity_image_fid);

                listActivities.add(bean);

            }               
        }
        catch (JSONException e) {

            e.printStackTrace();
      }

        return null;
    }

    @Override
    public void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);

        pgb.setVisibility(View.GONE);
        displayAdapter();
    }
}

public void displayAdapter()
{
    adapter = new ActivityAdapter(this, listActivities);
    contests_listView.setAdapter(adapter);
    contests_listView.setOnItemClickListener(new OnItemClickListener() {

        //@Override
        public void onItemClick(AdapterView<?> arg0, View arg1,
                int position, long id) {
            // your onclick Activity
        }

    });

}
}

util.class

public static String makeWebCall(String url) {

    DefaultHttpClient client = new DefaultHttpClient();

    HttpGet httpRequest = new HttpGet(url);
  //  HttpPost post = new HttpPost(url);

    try {

        HttpResponse httpResponse = client.execute(httpRequest);

         final int statusCode = httpResponse.getStatusLine().getStatusCode();

         if (statusCode != HttpStatus.SC_OK) {

            return null;
         }

         HttpEntity entity = httpResponse.getEntity();

         InputStream instream = null;

         if (entity != null) {
              instream = entity.getContent();
         }

            return iStream_to_String(instream);
    }
    catch (IOException e) {
        httpRequest.abort();
      // Log.w(getClass().getSimpleName(), "Error for URL =>" + url, e);
    }

    return null;

 }

public static String iStream_to_String(InputStream is1) {
    BufferedReader rd = new BufferedReader(new InputStreamReader(is1), 4096);
    String line;
    StringBuilder sb = new StringBuilder();
    try {
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }
        rd.close();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    String contentOfMyInputStream = sb.toString();
    return contentOfMyInputStream;
}

}

ActivityBean.java

public class ActivitiesBean implements Serializable{

/**
 * 
 */
private static final long serialVersionUID = 1L;

public String title;
public String image;

public String getTitle() {
    return title;
}
public void setTitle(String title) {
    this.title = title;
}
public String getImage() {
    return image;
}
public void setImage(String image) {
    this.image = image;
}