2017-10-28 98 views
-1

你好,请帮我基于JSON响应型充气布局 我试图合并http://androidcss.com/android/fetch-json-data-android/本教程本https://github.com/codepath/android_guides/wiki/Heterogenous-Layouts-inside-RecyclerView如何从JSON响应创建异构布局

,但我遇到了一些问题

JSON响应形式

[ 
    { "type":"sports", 
     "image":"http://example.com/image.jpg", 
     "name":"Super Commando Dhruva" 
    }, 
    { 
"type":"health", 
     "image":"http://example.com/image.jp", 
     "name":"Parmanu" 
    } 
] 

MainActivity

package com.androidcss.jsonexample; 

import android.app.ProgressDialog; 
import android.os.AsyncTask; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.support.v7.widget.LinearLayoutManager; 
import android.support.v7.widget.RecyclerView; 
import android.widget.Toast; 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 
import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.URL; 
import java.util.ArrayList; 
import java.util.List; 

public class MainActivity extends AppCompatActivity { 

    // CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds 
    public static final int CONNECTION_TIMEOUT = 10000; 
    public static final int READ_TIMEOUT = 15000; 
    private RecyclerView mRVFishPrice; 
    private AdapterFish mAdapter; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     //Make call to AsyncTask 
     new AsyncLogin().execute(); 
    } 

    private class AsyncLogin extends AsyncTask<String, String, String> { 
     ProgressDialog pdLoading = new ProgressDialog(MainActivity.this); 
     HttpURLConnection conn; 
     URL url = null; 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 

      //this method will be running on UI thread 
      pdLoading.setMessage("\tLoading..."); 
      pdLoading.setCancelable(false); 
      pdLoading.show(); 

     } 

     @Override 
     protected String doInBackground(String... params) { 
      try { 

       // Enter URL address where your json file resides 
       // Even you can make call to php file which returns json data 
       url = new URL("http://example.com/response.json"); 

      } catch (MalformedURLException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
       return e.toString(); 
      } 
      try { 

       // Setup HttpURLConnection class to send and receive data from php and mysql 
       conn = (HttpURLConnection) url.openConnection(); 
       conn.setReadTimeout(READ_TIMEOUT); 
       conn.setConnectTimeout(CONNECTION_TIMEOUT); 
       conn.setRequestMethod("GET"); 

       // setDoOutput to true as we recieve data from json file 
       conn.setDoOutput(true); 

      } catch (IOException e1) { 
       // TODO Auto-generated catch block 
       e1.printStackTrace(); 
       return e1.toString(); 
      } 

      try { 

       int response_code = conn.getResponseCode(); 

       // Check if successful connection made 
       if (response_code == HttpURLConnection.HTTP_OK) { 

        // Read data sent from server 
        InputStream input = conn.getInputStream(); 
        BufferedReader reader = new BufferedReader(new InputStreamReader(input)); 
        StringBuilder result = new StringBuilder(); 
        String line; 

        while ((line = reader.readLine()) != null) { 
         result.append(line); 
        } 

        // Pass data to onPostExecute method 
        return (result.toString()); 

       } else { 

        return ("unsuccessful"); 
       } 

      } catch (IOException e) { 
       e.printStackTrace(); 
       return e.toString(); 
      } finally { 
       conn.disconnect(); 
      } 


     } 

     @Override 
     protected void onPostExecute(String result) { 

      //this method will be running on UI thread 

      pdLoading.dismiss(); 
      List<DataFeed> data=new ArrayList<>(); 

      pdLoading.dismiss(); 
      try { 

       JSONArray jArray = new JSONArray(result); 

       // Extract data from json and store into ArrayList as class objects 
       for(int i=0;i<jArray.length();i++){ 
        JSONObject json_data = jArray.getJSONObject(i); 
        DataFeed fishData = new DataFeed(); 
        fishData.fishImage= json_data.getString("image"); 
        fishData.fishName= json_data.getString("type"); 
        fishData.catName= json_data.getString("name"); 
        // fishData.sizeName= json_data.getString("size_name"); 
        //fishData.price= json_data.getInt("price"); 
        data.add(fishData); 
       } 

       // Setup and Handover data to recyclerview 
       mRVFishPrice = (RecyclerView)findViewById(R.id.fishPriceList); 
       mAdapter = new AdapterFish(MainActivity.this, data); 
       mRVFishPrice.setAdapter(mAdapter); 
       mRVFishPrice.setLayoutManager(new LinearLayoutManager(MainActivity.this)); 

      } catch (JSONException e) { 
       Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show(); 
      } 

     } 

    } 
} 

适配器

package com.androidcss.jsonexample; 

import android.content.Context; 
import android.support.v4.content.ContextCompat; 
import android.support.v7.widget.RecyclerView; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.ImageView; 
import android.widget.TextView; 
import com.bumptech.glide.Glide; 
import com.squareup.picasso.Picasso; 

import java.util.Collections; 
import java.util.List; 

public class AdapterFish extends RecyclerView.Adapter<RecyclerView.ViewHolder> { 

    private Context context; 
    private LayoutInflater inflater; 
    List<DataFeed> data= Collections.emptyList(); 
    DataFeed current; 
    int currentPos=0; 
    private final int USER = 0, IMAGE = 1; 
    // create constructor to innitilize context and data sent from MainActivity 
    public AdapterFish(Context context, List<DataFeed> data){ 
     this.context=context; 
     inflater= LayoutInflater.from(context); 
     this.data=data; 
    } 


    // return total item from List 
    @Override 
    public int getItemCount() { 
     return data.size(); 
    } 

    @Override 
    public int getItemViewType(int position) { 
     DataFeed current=data.get(position); 
     if (data.get(position) instanceof DataFeed) { 
      return USER; 
     } else if (data.get(position) instanceof String) { 
      return IMAGE; 
     } 
     return -1; 
    } 






    @Override 
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { 

     RecyclerView.ViewHolder viewHolder; 
     LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext()); 

     switch (viewType) { 
      case USER: 
       View v1 = inflater.inflate(R.layout.layout_viewholder1, viewGroup, false); 
       viewHolder = new ViewHolder1(v1); 
       break; 
      case IMAGE: 
       View v2 = inflater.inflate(R.layout.layout_viewholder2, viewGroup, false); 
       viewHolder = new ViewHolder2(v2); 
       break; 
      default: 
       View v = inflater.inflate(R.layout.container_fish, viewGroup, false); 
       viewHolder = new MyHolder(v); 
       break; 
     } 
     return viewHolder; 
    } 

    @Override 
    public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) { 
     switch (viewHolder.getItemViewType()) { 
      case USER: 
       ViewHolder1 vh1 = (ViewHolder1) viewHolder; 
       configureViewHolder1(vh1, position); 
       break; 
      case IMAGE: 
       ViewHolder2 vh2 = (ViewHolder2) viewHolder; 
       configureViewHolder2 (vh2, position, int); 
       break; 
      //default: 
       // RecyclerViewSimpleTextViewHolder vh = (RecyclerViewSimpleTextViewHolder) viewHolder; 
       // configureDefaultViewHolder(vh, position); 
       // break; 
     } 
    } 

    //private void configureDefaultViewHolder(RecyclerViewSimpleTextViewHolder vh, int position) { 
     // vh.getLabel().setText((CharSequence) items.get(position)); 
    //} 

    private void configureViewHolder1(ViewHolder1 vh1, int position) { 
     DataFeed current = data.get(position); 
     if (current != null) { 
      vh1.getLabel1().setText("Name: " + current.fishName); 
      //vh1.getLabel2().setText("Hometown: " + current.hometown); 
     } 
    } 

    private void configureViewHolder2(ViewHolder2 vh2) { 
     vh2.getImageView().setImageResource(R.drawable.robbie); 
    } 




    class MyHolder extends RecyclerView.ViewHolder{ 

     TextView textFishName; 
     ImageView ivFish; 
     TextView textSize; 
     TextView textType; 
     TextView textPrice; 

     // create constructor to get widget reference 
     public MyHolder(View itemView) { 
      super(itemView); 
      textFishName= (TextView) itemView.findViewById(R.id.textFishName); 
      ivFish= (ImageView) itemView.findViewById(R.id.banner); 

     } 

    } 

} 

回答

0

试试这个

String type="sports"; 
String type1="health"; 

JSONObject json_data = jArray.getJSONObject(i); 


type = json_data.getString("type"); 

if (Objects.equals(type,type)){ 
    fishData.fishImage= json_data.getString("image"); 
} 

else if (Objects.equals(type,type1)){ 
    fishData.fishImage= json_data.getString("image"); 
}