2017-05-30 11 views
0

私はまだまだ高度なアンドロイドの開発を始めています.APIとJSONデータをListViewにフェッチする方法についてもっと学びたいと思っています。JSONデータをAPIからListViewにフェッチするにはどうすればよいですか?

私は俳優を探して、彼が関わっていたすべての映画をリストビューで表示できるようにしたいとしましょう。私は改造を見ていましたが、私が探している仕事をしているかどうかはわかりません。

私はこの問題に関する情報を取ります。リンク、スニペット、名前を付けます。

+0

これを落としたあなたには、建設的な批判がないのは何ですか? – Eli

答えて

0

ステップ1:1つのインターフェースAsyncResponse.java

public interface AsyncResponse 
     { 
      void processFinish(Object output) throws JSONException; 
     } 

は別のファイルRequestResponseを作成-now

を作成-firstあなたRequestSenderFilesを作成します。activity_main.xml

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_height="fill_parent" 
    android:layout_width="fill_parent" 
    > 
    <ListView 
     android:id="@+id/actorslist" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:color="#ffffff" 
     android:divider="@null" 
     android:scrollbars="none" 
     /> 
</RelativeLayout> 

ステップ2を作成します。 Java

public class RequestResponse extends AsyncTask<String ,String,String> 
    { 

     Activity c; 
     public AsyncResponse delegate = null; 
     String req=""; 
     HashMap<String,String> params; 
     boolean connect=true; 
     int responseCode; 
     String url; 
     ProgressDialog Loader; 
     public RequestResponse(AsyncResponse AsyncResponse, Activity context, String RequestMethod) 
     { 
      delegate = AsyncResponse; 
      c=context; 
      req=RequestMethod; 
     } 
     public RequestResponse(AsyncResponse AsyncResponse, Activity context, String RequestMethod, HashMap<String, String> postparam) 
     { 
      delegate = AsyncResponse; 
      c=context; 
      req=RequestMethod; 
      params=postparam; 
     } 
     @Override 
     protected void onPreExecute() 
     { 
      super.onPreExecute(); 
      // your progressdialog your here 
       Loader=new ProgressDialog(c); 
       Loader.setMessage("Loading..."); 
       Loader.show(); 

     } 
     @Override 
     protected String doInBackground(String... params) 
     { 
      String json=""; 
      Log.i("REposnse",""+params[0]); 
      url=params[0]; 
      if(req.equals("GET")) 
      { 
       json=Client(params[0]); 
      } 
      else 
      { 
       json=ClientPost(params[0]); 
      } 
      Log.i("REposnse", "" + json); 

      return json; 



     } 
     @Override 
     protected void onPostExecute(String av) 
     { 
      super.onPostExecute(av); 
      if(connect) 
      { 
       try 
       { 
        delegate.processFinish(av); 
       } 
       catch (JSONException e) 
       { 
        e.printStackTrace(); 
       } 
       try 
       { 
        if ((this.Loader != null) && this.Loader.isShowing()) 
        { 
         this.Loader.dismiss(); 
        } 
       } 
       catch (final IllegalArgumentException e) 
       { 
        // Handle or log or ignore 
       } 
       catch (final Exception e) 
       { 
        // Handle or log or ignore 
       } 
       finally 
       { 
        this.Loader = null; 
       } 
      } 
      else 
      { 
       try 
       { 
        if ((this.Loader != null) && this.Loader.isShowing()) 
        { 
         this.Loader.dismiss(); 
        } 
       } 
       catch (final IllegalArgumentException e) 
       { 
        // Handle or log or ignore 
       } 
       catch (final Exception e) 
       { 
        // Handle or log or ignore 
       } 
       finally 
       { 
        this.Loader = null; 
       } 
       c.runOnUiThread(new Runnable() 
       { 
        public void run() 
        { 

         if(req.equals("GET")) 
         { 
          RequestResponse requestget= RequestResponse(delegate, c); 
          requestget.execute(url); 
         } 
         else 
         { 

          RequestResponse requestpost = new RequestResponse(delegate, c, req, params); 
          requestpost.execute(url); 
         } 
        } 
       }); 

      } 
     } 
     public String ClientPost(String url) 
     { 
      URL url1; 
      String response = ""; 
      try 
      { 
       url1 = new URL(url); 
       HttpURLConnection conn = (HttpURLConnection) url1.openConnection(); 
       conn.setReadTimeout(1500000); 
       conn.setConnectTimeout(1500000); 
       conn.setRequestMethod("POST"); 
       conn.setDoInput(true); 
       conn.setDoOutput(true); 
       conn.setUseCaches(true); 
       OutputStream os = conn.getOutputStream(); 
       BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); 
       writer.write(getPostDataString(params)); 
       writer.flush(); 
       writer.close(); 
       os.close(); 
       responseCode=conn.getResponseCode(); 
       Log.i("REposnse",""+responseCode); 
       if(responseCode == HttpsURLConnection.HTTP_OK) 
       { 
        String line; 
        BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream())); 
        while ((line=br.readLine()) != null) 
        { 
         response+=line; 
        } 
       } 
       else 
       { 
        connect=false; 
        response=""; 
       } 
      } 
      catch (Exception e) 
      { 
       connect=false; 

      } 

      return response; 
     } 
     public String Client(String url) 
     { 
      String result = ""; 
      try 
      { 
       URL apiurl =null; 
       HttpURLConnection conn; 
       String line; 
       BufferedReader rd; 
       apiurl = new URL(url); 
       conn = (HttpURLConnection) apiurl.openConnection(); 
       conn.setRequestMethod("GET"); 
       conn.setReadTimeout(1500000); 
       conn.setConnectTimeout(1500000); 

       responseCode=conn.getResponseCode(); 
       Log.i("REposnse",""+responseCode); 
       if(responseCode==HttpsURLConnection.HTTP_OK) 
       { 
        rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
        while ((line = rd.readLine()) != null) 
        { 
         result += line; 
        } 
        rd.close(); 

       } 
       else 
       { 

        connect=false; 
       } 

      } 
      catch (Exception e) 
      { 
       connect=false; 

      } 
      return result; 
     } 
     private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException 
     { 
      StringBuilder result = new StringBuilder(); 
      boolean first = true; 
      for(Map.Entry<String, String> entry : params.entrySet()) 
      { 
       if (first) 
        first = false; 
       else 
        result.append("&"); 

       result.append(URLEncoder.encode(entry.getKey(), "UTF-8")); 
       result.append("="); 
       result.append(URLEncoder.encode(entry.getValue(), "UTF-8")); 
      } 
      Log.i("REposnse",""+params); 
      return result.toString(); 
     } 
    } 

ステップ3:作成アクティビティMainActivity.java

public class MainActivity extends Activity 
{ 
    ListView list; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) 
    { 
     try 
     { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.activity_main.xml); 
      list = (ListView) findViewById(R.id.actorslist); 
      request();  
     } 
     catch (Exception e) 
     { 
      e.printStackTrace(); 
     } 
    } 
    public void request() 
    { 
    // for POST Request 
     //suppose you need to send some data to server to fetch the response from server 
     HashMap<String,String> data=new HashMap<String,String>(); 
     data.put("id","12"); 
     try 
     { 
      RequestResponse crr = new RequestResponse(new AsyncResponse() 
      { 
       @Override 
       public void processFinish(Object output) throws JSONException 
       { 
        output.toString();//your response 
        // for example you got the response like this 
        String actors = "{"data":[{"actorname":"A"},{"actorname","B"}]}"; 
        fetchandapplydata(actors); 

       } 
      }, this,"POST",data); 
      crr.execute(yourserversideurltofetchdata); 
     } 
     catch (Exception e) 
     { 
      e.printStacktrace(); 
     } 

    // for GET Request 
     try 
       { 
      RequestResponse crr = new RequestResponse(new AsyncResponse() 
      { 
       @Override 
       public void processFinish(Object output) throws JSONException 
       { 
        output.toString();//your response 
        // for example you got the response like this 
        String actors = "{"data":[{"actorname":"A"},{"actorname","B"}]}"; 
        fetchandapplydata(actors); 

       } 
      }, this,"GET"); 
      crr.execute(yourserversideurltofetchdata); 
     } 
     catch (Exception e) 
     { 
      e.printStacktrace(); 
     } 

    //Depend upon the request method use the code and comment the rest code. 

    } 
    public void fetchandapplydata(String data) 
    { 
     JSONObject object=new JSONObject(data); 
     JSONArray actors=object.getJSONArray("data"); 
     ArrayList<HashMap<String,String>> actorsdata=new ArrayList<HashMap<String, String>>(); 
     for(int i=0;i<actors.length();i++) 
     { 
      JSONObject actor=actors.getJSONObject(i); 
      HashMap<String,String> actorsnames=new HashMap<String,String>(); 
      actorsnames.put("name",actor.getString("actorname")); 
      actorsdata.add(actorsnames); 
     } 
     ActorAdapter actoradapter = new ActorAdapter(this, actorsdata); 
     list.setAdapter(actoradapter); 
    } 
} 

ステップ4:これがステップバイステップでactor_item.xmlを作成

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:id="@+id/main"> 

    <TextView 
     android:layout_width="wrap_parent" 
     android:layout_height="wrap_parent" 
     android:id="@+id/name" /> 

</RelativeLayout> 

:ActorAdapter.java

public class ActorAdapter extends BaseAdapter 
{ 

    private ArrayList<HashMap<String, String>> data; 
    private static LayoutInflater inflater=null; 
    private Activity activity; 
    public ActorAdapter(Activity a, ArrayList<HashMap<String, String>> d) 
    { 
     activity = a; 
     data=d; 
     inflater = (LayoutInflater)Ced_activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

    } 
    public int getCount() 
    { 
     return data.size(); 
    } 
    public Object getItem(int position) 
    { 
     return position; 
    } 
    public long getItemId(int position) 
    { 
     return position; 
    } 

    @Override 
    public View getView(final int position, View convertView, ViewGroup parent) 
    { 
     try 
     { 
      View vi; 
      vi = inflater.inflate(R.layout.actor_item, null); 
      TextView name= (TextView) vi.findViewById(R.id.name); 
      HashMap<String, String> actor = new HashMap<String, String>(); 
      actor = data.get(position); 
      name.setText(actor.get("name")); 
      return vi; 
     } 
     catch (Exception e) 
     { 
      e.printStackTrace(); 
     } 
     return null; 
    } 
} 

ステップ5を作成あなたの疑問にお答えします。

+0

私はこれが可能な解決策であることを疑うことはないが、返事をありがとう、それ以上の説明なしに(または少なくともいくつかのコメント)本当に助けにはならない。 ClientPostは混乱です。 – Eli

+0

あなたはどんなエラーに直面していますか? – MageNative

+0

このコードを試してみましたか? clientPOstは、ポストリクエストを送信するために使用されます。 – MageNative

関連する問題