当前位置: 动力学知识库 > 问答 > 编程问答 >

android - JSON parsing and displaying into a recycler-card view fragment

问题描述:

I am trying to parse json with volley and display with recycler-card view in my tabbed fragment class in android. The json response is not displayed in the fragment. No errors or exceptions are shown. The app runs fine but no data is displayed. Take a look at the code below and tell me where I went wrong.

My Fragment Class

public class Latest_News extends Fragment {

private RecyclerView recyclerView;

private List<NewsItems> newsItemsList = new ArrayList<>();

private static final String TAG = Latest_News.class.getSimpleName();

private NewsItems newsItems;

public Latest_News() {

// Required empty public constructor

}

@Override

public void onCreate(@Nullable Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

networkAvailable();

}

@Override

public View onCreateView(LayoutInflater inflater, final ViewGroup container,

Bundle savedInstanceState) {

// Inflate the layout for this fragment

View mView = inflater.inflate(R.layout.fragment_latest__news, container, false);

recyclerView = (RecyclerView) mView.findViewById(R.id.latestNews_recyclerView);

recyclerView.setHasFixedSize(true);

LinearLayoutManager llMan = new LinearLayoutManager(getContext());

llMan.setOrientation(LinearLayoutManager.VERTICAL);

recyclerView.setLayoutManager(llMan);

//recyclerView.setAdapter(new HomeFrag_RecyclerAdapter(getActivity(), newsItemsList));

if (networkAvailable()){

String url = "www.goal.com/api"; // fake url, pls dont mind

RequestQueue mRequestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null,

new Response.Listener<JSONObject>() {

@Override

public void onResponse(JSONObject response) {

try {

JSONObject newsObject = new JSONObject(response.toString());

String title = newsObject.getString("title");

String time = newsObject.getString("time");

String date = newsObject.getString("date");

String link = newsObject.getString("link");

String content = newsObject.getString("content");

String image = newsObject.getString("image" + "");

newsItems = new NewsItems();

newsItems.setImage_Id(Integer.parseInt(image));

newsItems.setNewsDate(date);

newsItems.setNewTitle(title);

newsItems.setNewsDesc(content);

newsItems.setNewsUrl(link);

newsItems.setNewsTime(time);

newsItemsList.add(newsItems);

} catch (JSONException e) {

e.printStackTrace();

}

recyclerView.setAdapter(new HomeFrag_RecyclerAdapter(getActivity(), newsItemsList));

}

}, new Response.ErrorListener() {

@Override

public void onErrorResponse(VolleyError error) {

Log.i(TAG,"Error is: " + error.toString());

}

});

mRequestQueue.add(jsonObjectRequest);

}

else{

Toast.makeText(getActivity(), "Turn On Mobile Data or Wifi", Toast.LENGTH_SHORT).show();

}

return mView;

}

private boolean networkAvailable() {

ConnectivityManager cm = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo networkInfo = cm.getActiveNetworkInfo();

boolean isAvailable = false;

if (networkInfo != null && networkInfo.isConnected()){

isAvailable = true;

}

return isAvailable;

}

}

Fragment Adapter Code is Shown Below:

public class HomeFrag_RecyclerAdapter extends RecyclerView.Adapter<HomeFrag_RecyclerAdapter.MyHolder> {

private Context context;

List<NewsItems> newsItemsList;

public HomeFrag_RecyclerAdapter(Context context, List<NewsItems> newsItemsList) {

this.context = context;

this.newsItemsList = newsItemsList;

}

@Override

public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {

View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.tab_frags_customview,parent,false);

return new MyHolder(v);

}

@Override

public void onBindViewHolder(MyHolder holder, int position) {

holder.title.setText(newsItemsList.get(position).getNewTitle());

holder.descn.setText(newsItemsList.get(position).getNewsDesc());

holder.time.setText(newsItemsList.get(position).getNewsTime());

holder.date.setText(newsItemsList.get(position).getNewsDate());

int i = position;

Picasso.with(context).load(newsItemsList.get(i).getImage_Id())

.centerCrop()

.error(R.drawable.ic_toc_black_24dp)

.into(holder.coverImg);

}

@Override

public int getItemCount() {

return newsItemsList.size();

}

public class MyHolder extends RecyclerView.ViewHolder{

private TextView title, descn, time, date;

private ImageView coverImg;

public MyHolder(View itemView) {

super(itemView);

title = (TextView) itemView.findViewById(R.id.news_titleTxt);

descn = (TextView) itemView.findViewById(R.id.news_DescTxt);

time = (TextView) itemView.findViewById(R.id.news_TimeTxt);

date = (TextView) itemView.findViewById(R.id.newsDateTxt);

coverImg = (ImageView) itemView.findViewById(R.id.newsImage);

}

}

}

Sample JSON to be parsed

<pre>

{

"0": {

"image": null,

"title": "Suresh Raina to miss 2nd ODI against New Zealand ",

"time": "08:29 pm ",

"date": "18 Oct ",

"content": "Indian cricketer Suresh Raina will miss the second ODI against New Zealand at Delhi on Thursday. ...",

"link": "https://full-story.newsinshorts.com/v1/article/a659a7be-0c4d-408c-851d-689da6b95498-1 "

},

"1": {

"image": null,

"title": "Harley-Davidson net income falls by 18.67% to $114 mn ",

"time": "08:29 pm ",

"date": "18 Oct ",

"content": "Motorcycle manufacturer Harley-Davidson on Tuesday reported an 18.67% year-on-year decline in net ...",

"link": "https://full-story.newsinshorts.com/v1/article/448cc170-1d42-4109-9c50-0fe3a3c36f44-1 "

},

"2": {

"image": null,

"title": "JNU to get 200 solar power operated street lights ",

"time": "08:27 pm ",

"date": "18 Oct ",

"content": "The Jawaharlal Nehru University in Delhi is set to get 200 solar power operated street lights, Vice ...",

"link": "https://full-story.newsinshorts.com/v1/article/96db26c8-be8f-4313-8d51-27fee9bd084d-1 "

},

"3": {

"image": null,

"title": "Patiala Court dismisses fake degree case against Irani ",

"time": "08:22 pm ",

"date": "18 Oct ",

"content": "Patiala House Court today dismissed a case against Union Minister Smriti Irani for allegedly ...",

"link": null

},

</pre>

XML layout for the Fragment Class above:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context="com.example.joey.mydrawerapp.Fragments.HomeFragment_Fragments.Latest_News">

<!-- TODO: Update blank fragment layout -->

<include layout="@layout/recyclerview_layout"

android:id="@+id/latestNews_recyclerView"/>

<TextView

android:layout_width="match_parent"

android:layout_height="match_parent"

android:textSize="30sp"

android:gravity="center"

android:textStyle="bold"

android:text="Stay Tuned For Latest News" />

</RelativeLayout>

网友答案:

I generally don't parse Json by hand anymore, I always use Gson or jackson. Provided your json is correct, your onResponse can look something like this:

StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener() { @Override public void onResponse(String response) @Override public void onResponse(Stringresponse) {

         Gson gson = new Gson();
         Map<String,Item> map = gson.fromJson(response, new TypeToken<Map<String,Item>>(){}.getType());

         newsItemLists = new ArrayList();   // Clear the list if desired

         for (Item item : map.values()) {
            newsItems = new NewsItems();
             // Copy all item attributes to newsItems here.
             // if NewsItems is annotated correct, it can even be used to parse
             // the json instead of the Item class below.
            newsItemsList.add(newsItems);            
         }

      // Move this line into the onCreate() initializng the adapter with an empty list.
      //recyclerView.setAdapter(new HomeFrag_RecyclerAdapter(getActivity(), newsItemsList));
      // add this to notify the adapter that the list has changed.
      adapter.notifyDataSetChanged();
   }

You will need a pojo for the gson object:

 class Item {
      String image;
      String title;
      String time;
      String date;
      String content;
      String link;
   }

Update

I've updated my answer just a bit to make a StringRequest Volley instead of a JSONRequest. We'll use the whole string response and parse it as Json. Alternatively, you can change your Volley JsonObjectRequest to a JsonArrayRequest and receive a json array. Then you'll loop over each item in the array and parse it out.

分享给朋友:
您可能感兴趣的文章:
随机阅读: