2012-10-06 2 views
1

나는 android에서 새삼이다. 나는 ListView를 원하고 json으로부터 데이터를 얻는다. 많은 자습서를 찾았지만 AsyncTask가 없습니다. 나는이 코드에 AsyncTask를 어떻게 추가 할까?json으로 안드로이드 ListView - Howto AsyncTask?

package de.test.ListView; 

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

import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 
import android.app.ListActivity; 
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.SimpleAdapter; 
import android.widget.Toast; 

public class MeinListViewActivity extends ListActivity { 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.listplaceholder); 

     ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>(); 


     JSONObject json = jsonFunctions.getJSONfromURL("http://api.geonames.org/earthquakesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username=demo"); 

     try{ 

      JSONArray earthquakes = json.getJSONArray("earthquakes"); 

      for(int i=0;i<earthquakes.length();i++){       
       HashMap<String, String> map = new HashMap<String, String>();  
       JSONObject e = earthquakes.getJSONObject(i); 

       map.put("id", String.valueOf(i)); 
       map.put("name", "Earthquake name:" + e.getString("eqid")); 
       map.put("magnitude", "Magnitude: " + e.getString("magnitude")); 
       mylist.add(map);    
      }  
     }catch(JSONException e)  { 
      Log.e("log_tag", "Error parsing data "+e.toString()); 
     } 

     ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.main, 
         new String[] { "name", "magnitude" }, 
         new int[] { R.id.item_title, R.id.item_subtitle }); 

     setListAdapter(adapter); 

     final ListView lv = getListView(); 
     lv.setTextFilterEnabled(true); 
     lv.setOnItemClickListener(new OnItemClickListener() { 
      public void onItemClick(AdapterView<?> parent, View view, int position, long id) {    
       @SuppressWarnings("unchecked") 
       HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);     
       Toast.makeText(MeinListViewActivity.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show(); 

      } 
     }); 
    } 
} 

과 jsonFunctions

package de.test.ListView; 

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.HttpClient; 
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 jsonFunctions { 


    public static JSONObject getJSONfromURL(String url){ 
     InputStream is = null; 
     String result = ""; 
     JSONObject jArray = null; 

     //http post 
     try{ 
       HttpClient httpclient = new DefaultHttpClient(); 
       HttpPost httppost = new HttpPost(url); 
       HttpResponse response = httpclient.execute(httppost); 
       HttpEntity entity = response.getEntity(); 
       is = entity.getContent(); 

     }catch(Exception e){ 
       Log.e("log_tag", "Error in http connection "+e.toString()); 
     } 

     //convert response to string 
     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(); 
       result=sb.toString(); 
     }catch(Exception e){ 
       Log.e("log_tag", "Error converting result "+e.toString()); 
     } 

     try{ 

      jArray = new JSONObject(result);    
     }catch(JSONException e){ 
       Log.e("log_tag", "Error parsing data "+e.toString()); 
     } 

     return jArray; 
    } 
} 

답변

1
는 비동기 작업과 당신이 할 갈까요 모두 넣어 그것을 확인하고자하는 경우 GSON 지금

public void executeHttpGet() throws Exception { 

    BufferedReader in = null; 
    try { 
     HttpClient client = new DefaultHttpClient(); 
     HttpGet request = new HttpGet(); 
     request.setURI(new URI(
       "http://cardsplatform.appspot.com/cardeckplatform_details")); 
     HttpResponse response = client.execute(request); 
     in = new BufferedReader(new InputStreamReader(response.getEntity() 
       .getContent())); 
     StringBuffer sb = new StringBuffer(""); 
     String line = ""; 
     String NL = System.getProperty("line.separator"); 
     while ((line = in.readLine()) != null) { 
      sb.append(line + NL); 
     } 
     in.close(); 
     String json = sb.toString(); 
     System.out.println(json); 
     Gson gson = new Gson(); 
     Type collectionType = new TypeToken<MyClass>() { 
     }.getType(); 
     MyClass myclass= gson.fromJson(json, collectionType); 
     GameEnvironment.get().getHandler().post(new Runnable() { 

      @Override 
      public void run() { 
       addElementsToTableLayout();     
      } 
     }); 
    } finally { 
     if (in != null) { 
      try { 
       in.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
} 

뭔가를 얻기를 위해 내 코드를 사용할 수 있습니다

그것 on onBackground 메서드

예 :

private class DownloadFile extends 
     AsyncTask<PluginDetails, Integer, MyBoolean> { 
    MyBoolean downloaded; 
    ProgressDialog mProgressDialog; 
    boolean canceled=false; 
    public DownloadFile(MyBoolean downloaded) { 
     this.downloaded=downloaded; 
    } 
    @Override 
    protected MyBoolean doInBackground(PluginDetails... pluginDetail) { 
     try { 

      URL url = new URL("http://cardsplatform.appspot.com" 
        ); 
      URLConnection connection = url.openConnection(); 
      connection.connect(); 
      // this will be useful so that you can show a typical 0-100% 
      // progress bar 
      long fileLength = getSize(); 

      // download the file 
      InputStream input = new BufferedInputStream(
        connection.getInputStream()); 
      FileOutputStream output = StaticFunctions 
        .getPluginOutputStream(pluginDetail[0].getFilename()); 

      byte data[] = new byte[4096]; 
      long total = 0; 
      int count; 
      while ((count = input.read(data)) != -1 && !canceled) { 
       total += count; 
       System.out.println((int) (total * 100/fileLength)); 
       // publishing the progress.... 
       publishProgress((int) (total * 100/fileLength)); 
       output.write(data, 0, count); 
      } 
      output.flush(); 
      output.close(); 
      input.close(); 
      if(!canceled) 
       downloaded.setFlag(true); 
      else{//case its was canceled 

      } 
     } catch (Exception e) { 
      cannotMakeConnection(); 
      e.printStackTrace(); 
     } 
     return null; 
    } 
enter code here 
+0

이제 목록보기에 추가하려는 경우 새 항목을 listview에 추가 할 수있는 핸들러가 필요합니다 ... –