1

我成功地在列表视图中显示了来自 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);
}
}

服务器死机时我遇到问题,它仍在加载。我如何显示消息前:无法连接到服务器?

4

2 回答 2

0

工作 ASyncTask 教程

完整的 ASyncTask Eclipse 项目

这里有一些代码,我认为,当与上面的示例混合时,会得到你想要的列表的结果(不过,你必须稍微调整它以适应你的需要(注意列表的东西,即使虽然这是来自自定义对话框:

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

    }
于 2012-05-15T04:09:46.413 回答
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
        }

    });

}
}

实用程序类

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;
}
于 2012-05-15T04:10:06.293 回答