1

Web サービス JSON からのデータをリストビューに表示することに成功しましたが、Ayntask を追加したいと考えています。コードにコード 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 のコードはどこに置くことができますか?

OK、サンプルコードを取得し、コードは次のようになりました

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: can't connect to server? を表示するにはどうすればよいですか?

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 に答える