使用Volley和Picasso使用imageview解析Json数据并在Recycler和Card View中显示

时间:2018-01-02 11:22:07

标签: android json android-recyclerview android-volley picasso

我的数据显示在logcat中,但在打开应用时没有显示任何内容。您可以进一步查看here.但我发现了一个问题"没有附加适配器:跳过布局"有这个问题的任何想法吗?

这是我的 MainActivity xml文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:card_view="http://schemas.android.com/tools">


<android.support.v7.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scrollbars="vertical"
    android:layout_marginLeft="5dp"
    android:layout_marginRight="5dp"
    android:layout_marginTop="5dp"
    android:layout_marginBottom="5dp"
    card_view:cardUseCompatPadding="true"
    card_view:cardElevation="5dp"
    card_view:cardCornerRadius="5dp">

</android.support.v7.widget.RecyclerView>

<ProgressBar
    android:id="@+id/progressBar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:indeterminateTint="@color/colorPrimary" />

</RelativeLayout>

CardView xml文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:card_view="http://schemas.android.com/apk/res-auto">

<android.support.v7.widget.CardView
 android:id="@+id/card_view"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:layout_gravity="center"
 android:elevation="3dp"
 card_view:cardUseCompatPadding="true"
 card_view:cardElevation="5dp"
 card_view:cardCornerRadius="5dp">

 <RelativeLayout
     android:layout_width="match_parent"
     android:layout_height="match_parent">

     <ImageButton android:id="@+id/imagebtn"
         android:layout_width="match_parent"
         android:layout_height="100dp"
         android:background="?attr/selectableItemBackgroundBorderless"
         android:clickable="true"
         android:scaleType="centerCrop" />

     <TextView android:id="@+id/description"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:textSize="15dp"
         android:layout_below="@+id/imagebtn"
         android:padding="5dp"
         android:textColor="#000"
         android:gravity="center"
         android:text="Hospital Name"/>

 </RelativeLayout>

</android.support.v7.widget.CardView>

</LinearLayout>

MainActivity java类文件:

 public class MainActivity extends AppCompatActivity implements 
 ExampleAdapter.OnItemClickListener {
 public  static final String EXTRA_CREATOR = "orga_organame";
 public  static final String EXTRA_URL = 
 "http://xelwel.com.np/hamrosewaapp/uploads/images/logo/civil.png";

 private RecyclerView mRecyclerview;
 private ExampleAdapter mExampleAdapter;
 private List<UserInfo> mExampleList;
 private RequestQueue mRequestQueue;

ImageButton imageButton;
TextView textView;
ProgressBar progressbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    progressbar = findViewById(R.id.progressBar);
    progressbar.setVisibility(View.VISIBLE);

    imageButton = findViewById(R.id.imagebtn);
    textView = findViewById(R.id.description);

    mRecyclerview = findViewById(R.id.recycler_view);
    mRecyclerview.setHasFixedSize(true);
    mRecyclerview.setLayoutManager(new LinearLayoutManager(this));

    mExampleList = new ArrayList<>();

    mRequestQueue = Volley.newRequestQueue(this);

    jsonParse();
  }

 public void jsonParse() {

    final String url = 
  ("http://xelwel.com.np/hamrosewaapp/api/get_organization_list");

    final StringRequest request = new StringRequest(Request.Method.POST, 
   url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

            Log.i("response", url + "response:" + response);

            try {
                JSONObject jsonObject = new JSONObject(response);

                JSONArray jsonArray = jsonObject.getJSONArray("org_list");

                for (int i = 0; i < jsonArray.length(); i++) {

                    JSONObject obj = jsonArray.getJSONObject(i);

                    String hsname = obj.getString("orga_organame");
                    String image = obj.getString("logo_path" + "civil.png");

                    mExampleList.add(new UserInfo(hsname, image)); 
                }

                mExampleAdapter = new ExampleAdapter(MainActivity.this, 
              mExampleList);
                mRecyclerview.setAdapter(mExampleAdapter);
                mExampleAdapter.setOnItemClickListener(MainActivity.this);

                progressbar.setVisibility(View.GONE);

            } catch (JSONException e) {
                Toast.makeText(getApplicationContext(),"Error Parsing Data", 
         Toast.LENGTH_LONG);
                e.printStackTrace();
            }catch (Exception e) {
                Toast.makeText(getApplicationContext(),"Something went 
     wrong", Toast.LENGTH_LONG);
            }

        }

    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();         
        }
     }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<>();
            params.put("api_key", "123456789");
            return params;
        }
    };

    mRequestQueue.add(request);
  }

  @Override
  public void onItemClick(int position) {

    Intent detailIntent = new Intent(this, DetailActivity.class);
    UserInfo clickedItem = mExampleList.get(position);

    detailIntent.putExtra(EXTRA_URL, clickedItem.getImage_link());
    detailIntent.putExtra(EXTRA_CREATOR, clickedItem.getName());

    startActivity(detailIntent);
    }
  }

DetailActivity java类文件:

 Intent intent = getIntent();
    String imageUrl = intent.getStringExtra(EXTRA_URL);
    String name = intent.getStringExtra(EXTRA_CREATOR);

    ImageView imageView = findViewById(R.id.image_view_detail);
    TextView textView = findViewById(R.id.text_view);

    Picasso.with(this).load(imageUrl).fit().centerInside().into(imageView);
    textView.setText(name);

ExampleAdapter java类文件:

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

  private Context mcontext;
  private List<UserInfo> mExampleList;
  private OnItemClickListener mListener;

  public interface OnItemClickListener{
     void onItemClick(int position);
  }

  public void setOnItemClickListener(OnItemClickListener listener){
     mListener = listener;
  }

  public ExampleAdapter(Context context, List<UserInfo> list) {

    mcontext = context;
    mExampleList = list;
  }

 @Override
 public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View itemView = 
   LayoutInflater.from(mcontext).inflate(R.layout.cardview,parent,false);
    return new ViewHolder(itemView);
   }

   @Override
   public void onBindViewHolder(ViewHolder holder, int position) {

    UserInfo info = mExampleList.get(position);

    String imageUrl = info.getImage_link();
    String hsname = info.getName();

    holder.textView.setText(hsname);

  Picasso.with(mcontext).load(imageUrl).fit().centerInside().
  into(holder.imageView);

  }

  @Override
  public int getItemCount() {
    return mExampleList.size();
  }

  public class ViewHolder extends RecyclerView.ViewHolder {

    public TextView textView;
    public ImageView imageView;

    public ViewHolder(View itemView) {
        super(itemView);
        textView = (TextView) itemView.findViewById(R.id.description);
        imageView = (ImageView) itemView.findViewById(R.id.image);

        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(mListener!= null){
                    int position = getAdapterPosition();
                    if (position!= RecyclerView.NO_POSITION){
                        mListener.onItemClick(position);
                    }
                }
             }
          });
        }
      }
    }

UserInfo java类文件:

    public class UserInfo {

    public String id, name, image_link;

    public UserInfo(String id, String name) {

    this.id = id;
    this.name = name;
   }

   public String getId() {
    return id;
  }

  public void setId(String id) {
    this.id = id;
  }

  public String getName() {
    return image_link;
  }

  public void setName(String image_link) {
    this.image_link = image_link;
 }

   public String getImage_link() {
    return image_link;
   }

 public void setImage_link(String image_link) {
    this.image_link = image_link;
    }
 }

这些是与这些问题相关的总代码。请通过一些特定的解决方案查看代码和响应...

2 个答案:

答案 0 :(得分:0)

试试这个

你在UserInfo类构造函数中犯了错误。

你添加了

 mExampleList.add(new UserInfo(hsname, image)); 

但是这里设置了id和name

 public UserInfo(String id, String name) {

   this.id = id;
   this.name = name;
   }

更改您的构造函数

  public UserInfo(String name, String image_link) {

   this.image_link = image_link;
   this.name = name;
   }

您没有在image_link变量中设置任何值,但在适配器类中访问

UserInfo info = mExampleList.get(position);
String imageUrl = info.getImage_link();
String hsname = info.getName();

答案 1 :(得分:0)

试试这个

try {
        JSONObject jsonObject = new JSONObject(response);

        String logoURL = jsonObject.getString("logo_path")

        JSONArray jsonArray = jsonObject.getJSONArray("org_list");

        for (int i = 0; i < jsonArray.length(); i++) {

           JSONObject obj = jsonArray.getJSONObject(i);

           String hsname = obj.getString("orga_organame");
           String imageurl = obj.getString("orga_image");
           String image = logoURL +"/"+ imageurl ;

           mExampleList.add(new UserInfo(hsname, image)); 
        }
}