Parsing JSON news in Android - android

I am trying to display news received from a json data source. But, I am getting an error when I try to parse the data.
The json data looks something like this:
click here to view
Here is the class I wrote for parsing :
public class FragmentUniversityNews extends Fragment {
private String TAG = FragmentUniversityNews.class.getSimpleName();
private static final String endpoint = "https://api.myjson.com/bins/18smd";
private static final String endpoint_final = "http://srm-news-bot.herokuapp.com";
private SwipeRefreshLayout swipeRefreshLayout;
private SimpleStringRecyclerViewAdapter mAdapter;
private JsonObjectRequest req;
String[] titles = new String[15];
String[] snips = new String[15];
String[] links = new String[15];
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
RecyclerView recyclerView;
View rootView = inflater.inflate(R.layout.fragment_university_news, container, false);
//((ActivityMain) getActivity()).showFloatingActionButton();
recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view_university);
swipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_refresh_layout);
swipeRefreshLayout.setColorSchemeResources(R.color.red500, R.color.black, R.color.google_blue_900);
mAdapter = new SimpleStringRecyclerViewAdapter(getContext(), titles, snips, links);
// Calling another function which has the details
setupRecyclerView(recyclerView);
// Make it look like something is happening
swipeRefreshLayout.setRefreshing(true);
// Make the request!
makeJSONRequest();
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
// onRefresh action here
swipeRefreshLayout.setRefreshing(true);
makeJSONRequest();
}
});
return rootView;
}
private void setupRecyclerView(RecyclerView recyclerView) {
recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext()));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
}
public void makeJSONRequest() {
req = new JsonObjectRequest(endpoint_final,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
// Getting JSON Array node
JSONArray newsItems = response.getJSONArray("newsItems");
// UI
try {
for (int j = 0; j < newsItems.length(); j++) {
JSONObject newsItem = newsItems.getJSONObject(j);
titles[j] = newsItem.getString("title");
snips[j] = newsItem.getString("snip");
links[j] = newsItem.getString("link");
}
swipeRefreshLayout.setRefreshing(false);
} catch (JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
Toast.makeText(getContext(), "JSON Parsing error", Toast.LENGTH_LONG).show();
} mAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(getContext(), "Error Receiving News", Toast.LENGTH_LONG).show();
}
});
// Adding request to request queue
InitializeVolley.getInstance().addToRequestQueue(req);
}
public static class SimpleStringRecyclerViewAdapter extends RecyclerView.Adapter<SimpleStringRecyclerViewAdapter.ViewHolder> {
private String[] mTitles, mSnips, mLinks;
private Context mContext;
public static class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mTextViewTitle, mTextViewSnip;
public ViewHolder(View view) {
super(view);
mView = view;
mTextViewTitle = (TextView) view.findViewById(R.id.univ_news_title);
mTextViewSnip = (TextView) view.findViewById(R.id.univ_news_snip);
}
}
// Constructor
public SimpleStringRecyclerViewAdapter(Context context, String[] Titles, String[] Snips, String[] Links) {
mContext = context;
mTitles = Titles;
mSnips = Snips;
mLinks = Links;
}
public String getTitleAt(int position) {
return mTitles[position];
}
public String getSnipAt(int position) {
return mSnips[position];
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_view_univ, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.mTextViewTitle.setText(getTitleAt(position));
holder.mTextViewSnip.setText(getSnipAt(position));
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//startScan();
Context context = v.getContext();
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(mLinks[holder.getAdapterPosition()]));
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return mTitles.length;
}
}
}
The error I am getting in Android Studio is at the line "JSONArray newsItems = response.getJSONArray("newsItems");",
It's saying
Unhandled exception:org.json.JSONException
When I move JSONArray newsItems = response.getJSONArray("newsItems"); in "try" block, it says
`Cannot resolve constructor 'JsonObjectRequest(java.lang.String, anonymous com.android.volley.Response.Listener<org.json.JSONObject>, anonymous com.android.volley.Response.ErrorListener)'`

Isolating just the parsing part out of your code I couldn't reproduce the error, here is my code:
String jsonStr = "";//TODO insert JSON sample from link
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject(jsonStr);
JSONArray newsItems = jsonObj.getJSONArray("newsItems");
for (int j = 0; j < newsItems.length(); j++) {
JSONObject newsItem = newsItems.getJSONObject(j);
Log.d(TAG,
"Title: " +newsItem.getString("title") +
"\nSnip: " + newsItem.getString("snip") +
"\nLink: " +newsItem.getString("link")
);
}
} catch (JSONException e) {
e.printStackTrace();
}
There is either an error while retrieving the content directly as a JSONObject, or anything unrelated to the JSON parsing.
To help you out further it would be great to have an errorlog, as mentioned by Kris Roofe already.

I solved my problem by adding "null" in the JSONObjectRequest function. I didn't understand why.
public void makeJSONRequest() {
req = new JsonObjectRequest(endpoint_final, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());

Related

Recyclerview displaying only the last json data?

I am trying to display data in a recycler view in android. i but it keeps displaying only the last datas and i dont know why.i seem to be doing everything right. And the recycler view has a view pager.
this is my
Myadapter class
public class MyAdapter extends RecyclerView.Adapter<MyHolder> {
Context c;
List<Getter> getter;
public MyAdapter(List<Getter> getter, Context c) {
super();
this.c = c;
this.getter = getter;
}
//INITIALIZE VIEWHODER
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//VIEW OBJ
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.model,null);
//HOLDER
MyHolder holder=new MyHolder(v);
return holder;
}
//BIND VIEW TO DATA
#Override
public void onBindViewHolder(MyHolder holder, int position) {
String images[] = {getter.get(position).getUrl1(), getter.get(position).getUrl2()};
holder.gamename.setText(getter.get(position).getGame_name());
holder.cost.setText(getter.get(position).getCost());
holder.usname.setText(getter.get(position).getFull_name());
Picasso.with(c)
.load(getter.get(position).getPicture())
.placeholder(R.drawable.placeholder)
.error(R.drawable.error)
.transform(new CircleTransform())
.fit()
.into(holder.usimage);
CustomPagerAdapter mCustomPagerAdapter = new CustomPagerAdapter(c,images);
holder.mViewPager.setAdapter(mCustomPagerAdapter);
holder.indicator.setViewPager(holder.mViewPager);
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(View v, int pos) {
Snackbar.make(v,getter.get(pos).getGame_name(),Snackbar.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return getter.size();
}
}
This is my mainactivty class
public class All_timeline extends Fragment {
SqlHandler sqlHandler;
RecyclerView rv;
MyAdapter adapter;
private List<Getter> getter;
public All_timeline() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View x = inflater.inflate(R.layout.all_timeline, container, false);
sqlHandler = new SqlHandler(getActivity());
//recycler
rv = (RecyclerView) x.findViewById(R.id.mRecycler);
getter= new ArrayList<>();
rv.setLayoutManager(new LinearLayoutManager(getActivity()));
rv.setItemAnimator(new DefaultItemAnimator());
rv.addItemDecoration(new SimpleDividerItemDecoration(getResources()));
registerUser("arinzeaco#gmail.com");
adapter=new MyAdapter(getter,getActivity());
rv.setAdapter(adapter);
return x;
}
public void registerUser(final String email) {
OkHttpClient client = new OkHttpClient();
RequestBody body = new FormBody.Builder()
.add("username", email)
.build();
Request request = new Request.Builder().url("http://www.thethinker.com.ng/gamer/allpost.php").post(body).build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
Toast.makeText(getActivity(), "Registration failed",
Toast.LENGTH_SHORT).show();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
final String myResponse = response.body().string();
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject jso;
Getter contactListItems = new Getter();
try {
jso = new JSONObject(myResponse);
JSONArray categories = jso.getJSONArray("posts");
for (int i = 0; i < categories.length(); i++) {
String image1 = categories.getJSONObject(i).getString("image_1");
String image2 = categories.getJSONObject(i).getString("image_2");
String username = categories.getJSONObject(i).getString("username");
String video_url = categories.getJSONObject(i).getString("video_url");
String liked = categories.getJSONObject(i).getString("liked");
String cost = categories.getJSONObject(i).getString("cost");
String following = categories.getJSONObject(i).getString("following");
String game_name = categories.getJSONObject(i).getString("game_name");
String full_name = categories.getJSONObject(i).getString("full_name");
String userimage = categories.getJSONObject(i).getString("userimage");
contactListItems.setUsername(username);
contactListItems.setGame_name(game_name);
contactListItems.setCost(cost);
contactListItems.setFollowing(following);
contactListItems.setLiked(liked);
contactListItems.setFull_name(full_name);
contactListItems.setVideo(video_url);
contactListItems.setUrl1(image1);
contactListItems.setUrl2(image2);
contactListItems.setPicture(userimage);
getter.add(contactListItems);
}
} catch (JSONException e) {
e.printStackTrace();
}
}});
}
});
}
}
I have also check other stackoverflow questions like RecyclerView displaying the last item in the adapter several times. Need all adapter items to show in RecyclerView. but i just don't get what i am doing wrong.
I think it related to concurrency issue, please try to call http method after you set adapter, and don't forget to call notifyDataSetChanged() after all data inserted. One more think, make sure you insert different Getter instance for every item
for example in onCreateView
adapter=new MyAdapter(getter,getActivity());
rv.setAdapter(adapter);
registerUser("arinzeaco#gmail.com");
in onResponse:
#Override
public void onResponse(Call call, Response response) throws IOException {
final String myResponse = response.body().string();
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject jso;
try {
jso = new JSONObject(myResponse);
JSONArray categories = jso.getJSONArray("posts");
for (int i = 0; i < categories.length(); i++) {
Getter contactListItems = new Getter();
String image1 = categories.getJSONObject(i).getString("image_1");
String image2 = categories.getJSONObject(i).getString("image_2");
String username = categories.getJSONObject(i).getString("username");
String video_url = categories.getJSONObject(i).getString("video_url");
String liked = categories.getJSONObject(i).getString("liked");
String cost = categories.getJSONObject(i).getString("cost");
String following = categories.getJSONObject(i).getString("following");
String game_name = categories.getJSONObject(i).getString("game_name");
String full_name = categories.getJSONObject(i).getString("full_name");
String userimage = categories.getJSONObject(i).getString("userimage");
contactListItems.setUsername(username);
contactListItems.setGame_name(game_name);
contactListItems.setCost(cost);
contactListItems.setFollowing(following);
contactListItems.setLiked(liked);
contactListItems.setFull_name(full_name);
contactListItems.setVideo(video_url);
contactListItems.setUrl1(image1);
contactListItems.setUrl2(image2);
contactListItems.setPicture(userimage);
getter.add(contactListItems);
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}});
}
});

how to set on click listener on recyclerview and open a static page and get content from json url

i have a series of items in recyclerview .i want to set on click listener and open a description page of specific item and set data from json url. i have already made an adapter for description screen and a bean class. i dont know how to set adapter on layout. is it possible to set an adapter on linear layout to show static content from json url?
My code is :
Description activity
private class MakeRequestForGetDescription extends AsyncTask<String, Void, String> {
ProgressDialog Pdialog;
private String response;
private MakeServiceClass makeServiceClass = new MakeServiceClass();
#Override
protected void onPreExecute() {
Pdialog = new ProgressDialog(getActivity());
Pdialog.setMessage("Please Wait..");
Pdialog.show();
}
#Override
protected String doInBackground(String... params) {
try {
HashMap<String, String> parms = new HashMap<String, String>();
response = makeServiceClass.makeServiceConnectionGet(ConstUrl.DESCRP_URLS);
Log.e("response ads", response);
} catch (Exception ex) {
ex.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(response);
if (Pdialog != null) {
Pdialog.dismiss();
}
if (response != null) {
try {
JSONObject mainObject = new JSONObject(response);
if (mainObject.has("status")) {
String Status = mainObject.getString("status");
String img_url = "";
if (Status.equalsIgnoreCase("200")) {
if (mainObject.has("img_url")) {
img_url = mainObject.getString("img_url");
Log.e("img_url", img_url);
}
if (mainObject.has("details")) {
JSONArray datArray = mainObject.getJSONArray("details");
descriptionBeanArrayList = new ArrayList<>();
if (datArray.length() > 0) {
for (int i = 0; i < datArray.length(); i++) {
DescriptionBean descriptionBean = new DescriptionBean();
JSONObject internalDataObject = datArray.getJSONObject(i);
if (internalDataObject.has("id")) {
descriptionBean.setId(internalDataObject.getString("id"));
}
if (internalDataObject.has("title_en")) {
descriptionBean.setTitle_en(internalDataObject.getString("title_en"));
}
if (internalDataObject.has("ad_description_en")) {
descriptionBean.setAd_description_en(internalDataObject.getString("ad_description_en"));
}
if (internalDataObject.has("price")) {
descriptionBean.setPrice(internalDataObject.getString("price"));
}
if (internalDataObject.has("km_driven")) {
descriptionBean.setKm_driven(internalDataObject.getString("km_driven"));
}
if (internalDataObject.has("image_file")) {
descriptionBean.setImage_file("http://" + img_url + internalDataObject.getString("image_file"));
}
descriptionBeanArrayList.add(descriptionBean);
}
setAdapterForDescription();
}
}
} else {
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private void setAdapterForDescription() {
DescriptionAdapter adapter = new DescriptionAdapter(getActivity(), descriptionBeanArrayList);
}
}
Description Adapter
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder; // view lookup cache stored in tag
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(R.layout.fragment_description, parent,false);
viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
viewHolder.tvRate = (TextView) convertView.findViewById(R.id.tvRate);
viewHolder.tvMiles = (TextView) convertView.findViewById(R.id.tvMiles);
viewHolder.et_description = (EditText) convertView.findViewById(R.id.et_description);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
//setdata
viewHolder.tvTitle.setText(descriptionBeanArrayList.get(position).getTitle_en());
viewHolder.tvRate.setText(descriptionBeanArrayList.get(position).getPrice());
viewHolder.tvMiles.setText(descriptionBeanArrayList.get(position).getKm_driven());
viewHolder.et_description.setText(descriptionBeanArrayList.get(position).getAd_description_en());
Log.e("s", descriptionBeanArrayList.get(position).getImage_file());
//Glide.with(mContext).load("www.apnikheti.com/upload/buysell/idea99A4.jpg").into(viewHolder.iv_picofproduct);
Picasso.with(mContext).load(descriptionBeanArrayList.get(position).getImage_file()).into(viewHolder.iv_picofproduct, new Callback() {
#Override
public void onSuccess() {
Log.e("s", "sucess");
}
#Override
public void onError() {
Log.e("s", "failed");
}
});
Picasso.with(mContext).setLoggingEnabled(true);
return convertView;
}
public class ViewHolder {
private TextView tvTitle,tvRate,tvMiles;
private EditText et_description;
public ImageView iv_picofproduct;
}
}
This is my code which is used to retrieve data from url (Json Data) and load it into a recyclerview using adapter and passing the same values to another activity.
MyActivity
public class Video_List extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
//private GridLayoutManager layoutManager;
private List<Video_Details> videodetails;
public static final String VideoID = "v_id";
public static final String ID = "id";
public static final String Title = "title";
public static final String Thumb = "thumb";
public static final String url = "http://115.115.122.10/paul/api/videos.php?start=1&count=10";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video__list);
getdata();
recyclerView = (RecyclerView) findViewById(R.id.card_recycler_view);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
//layoutManager = new GridLayoutManager(this,2);
recyclerView.setLayoutManager(layoutManager);
videodetails = new ArrayList<>();
}
private void getdata(){
final ProgressDialog loading = ProgressDialog.show(this,"Loading Data", "Please wait...",false,false);
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Dismissing progress dialog
loading.dismiss();
Log.d("count",response.toString());
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loading.dismiss();
Log.d("infoz","777"+error.getMessage());
Toast.makeText(getApplicationContext(),"No data Found",Toast.LENGTH_LONG).show();
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
//This method will parse json data
private void parseData(JSONArray array){
try {
for (int i = 0; i < array.length(); i++) {
JSONObject json = array.getJSONObject(i);
Video_Details video = new Video_Details();
if (json.has(VideoID)) {
Log.d("has values", json.getString(VideoID));
}
video.setId(json.getString(ID));
video.setV_id(json.getString(VideoID));
video.setTitle(json.getString(Title));
video.setThumb(json.getString(VideoID));
videodetails.add(video);
if (json.has(VideoID))
{
Log.d("Video",VideoID);
}
}
} catch (Exception e) {
e.printStackTrace();
}
//Finally initializing our adapter
adapter = new DataAdapter(videodetails, this);
//Adding adapter to recyclerview
recyclerView.setAdapter(adapter);
}
}
MyAdapter
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private Context context;
List<Video_Details> video;
public DataAdapter(List<Video_Details> video, Context context) {
super();
this.context = context;
this.video = video;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_row, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final Video_Details videoDetails = video.get(position);
String url;
final String VideoID;
holder.title.setText(video.get(position).getTitle());
VideoID= video.get(position).getV_id();
url = video.get(position).getThumb();
Glide.with(context)
.load(url)
.override(150,70)
.into(holder.thumb);
//viewHolder.thumb.setText(android.get(i).getVer());
// viewHolder.tv_api_level.setText(android.get(i).getApi());
holder.vm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "You Clicked"+video.get(position).getV_id(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(v.getContext(),Play_Video.class);
intent.putExtra("VideoId",(video.get(position).getV_id()));
intent.putExtra("Title",(video.get(position).getTitle()));
v.getContext().startActivity(intent);
}
}
);
}
#Override
public int getItemCount() {
return video.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView title;
public ImageView thumb;
public String videoid;
public View vm;
public ViewHolder(View view) {
super(view);
vm = view;
title = (TextView)view.findViewById(R.id.title);
thumb = (ImageView) view.findViewById(R.id.thumb);
//tv_version = (TextView)view.findViewById(R.id.tv_version);
//tv_api_level = (TextView)view.findViewById(R.id.tv_api_level);
}
}
}

Change items in recyclerview when item click on another

I am creating an app where there are 2 RecyclerView in one layout. I set one for category and second for text based on category. when i am debug my code that give me recyclerview display null value on this line recyclerView.setAdapter(adapter); in adapter see in image
I want to select category item then give the text that contain that category.
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private List<TextJson> listtext;
private List<CategoryJson> horizentallylist;
private RecyclerView recyclerView , horizantalrcview;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
String textUrl = "http:www.extample.com/texturl.php";
String categoryUrl ="http:www.extample.com/categoryurl.php";
private static final String TAG = MainActivity.class.getSimpleName();
private JSONArray result;
ArrayAdapter<String> adapterSpin;
CategoryJson categoryJson;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView_text);
horizantalrcview = (RecyclerView)findViewById(R.id.recyclerView_cate);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
listtext = new ArrayList<>();
horizentallylist = new ArrayList<>();
getData();
verticalData();
}
private void getData() {
final ProgressDialog loading = ProgressDialog.show(this, "Loading Data", "Please wait...", false, false);
loading.setCancelable(true);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(textUrl,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.e("text", "resopnce is =>" + response);
loading.dismiss();
verticalParse(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
private void verticalParse(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
TextJson jsonitem = new TextJson();
JSONObject json = null;
try {
json = array.getJSONObject(i);
String text = json.getString("txt");
String txtcate = json.getString("category");
jsonitem.setText_status(text);
jsonitem.setCategory(txtcate);
Log.e("text", "is==> " + text);
Log.e("cate", "is==> " + txtcate);
} catch (JSONException e) {
e.printStackTrace();
}
listtext.add(jsonitem);
}
//Finally initializing our adapter
adapter = new VerticalAdapter(listtext, this);
adapter.notifyDataSetChanged();
//Adding adapter to recyclerview
recyclerView.setAdapter(adapter);
}
private void verticalData() {
final ProgressDialog loading = ProgressDialog.show(this, "Loading Data", "Please wait...", false, false);
loading.setCancelable(true);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(categoryUrl,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.e("Response is", "first==>" + response);
loading.dismiss();
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NoConnectionError) {
Log.e("NoConnectionError>>", "NoConnectionError....");
} else if (error instanceof AuthFailureError) {
Log.e("AuthFailureError>>>", "AuthFailureError...");
} else if (error instanceof ServerError) {
Log.e("ServerError>>>>>>>>>", "ServerError.......");
} else if (error instanceof NetworkError) {
Log.e("NetworkError>>>>>>>>>", "NetworkError.......");
} else if (error instanceof ParseError) {
Log.e("ParseError>>>>>>>>>", "ParseError.......");
} else if (error instanceof TimeoutError) {
Log.d("TimeoutError>>>>>>>>>", "TimeoutError.......");
}
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
private void parseData(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
CategoryJson model1 = new CategoryJson();
JSONObject json = null;
try {
json = array.getJSONObject(i);
String imgurl = json.getString("cat_img");
String imgname = json.getString("category");
Log.e("value in","link=>"+imgurl);
Log.e("value in","imagename=>"+imgname);
model1.setImageUrl(imgurl);
model1.setName(imgname);
} catch (JSONException e) {
e.printStackTrace();
}
horizentallylist.add(model1);
}
//Finally initializing our adapter
adapter = new HorizantalAdapter(horizentallylist, this);
adapter.notifyDataSetChanged();
//Adding adapter to recyclerview
horizantalrcview.setAdapter(adapter);
}
private void selectData() {
NewModel newModel = new NewModel();
final ProgressDialog loading = ProgressDialog.show(this, "Loading Data", "Please wait...", false, false);
loading.setCancelable(true);
String txtselect =newModel.getItem().toString();
String select_cate ="http:www.extample.com/filter.php"+selectitem;
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(select_cate ,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.e("text", "resopnce is =>" + response);
loading.dismiss();
selectParse(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
private void selectParse(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
TextJson jsonitem = new TextJson();
JSONObject json = null;
try {
json = array.getJSONObject(i);
String text = json.getString("txt");
String txtcate = json.getString("category");
jsonitem.setText_status(text);
jsonitem.setCategory(txtcate);
Log.e("text", "is==> " + text);
Log.e("cate", "is==> " + txtcate);
} catch (JSONException e) {
e.printStackTrace();
}
listtext.add(jsonitem);
}
//Finally initializing our adapter
adapter = new VerticalAdapter(listtext, this);
adapter.notifyDataSetChanged();
//Adding adapter to recyclerview
recyclerView.setAdapter(adapter);
}
}
HorizantalAdapter
public class HorizantalAdapter extends RecyclerView.Adapter<HorizantalAdapter.ViewHolder> {
private ImageLoader imageLoader;
private Context context;
List<CategoryJson> listmodel;
NewModel newModel = new NewModel();
String link;
public HorizantalAdapter(List<CategoryJson> listmodel, Context context) {
super();
this.listmodel = listmodel;
this.context = context;
setHasStableIds(false);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.text_horigentally, parent, false);
HorizantalAdapter.ViewHolder viewHolder = new HorizantalAdapter.ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(final HorizantalAdapter.ViewHolder holder, final int position) {
CategoryJson imgModel = listmodel.get(position);
imageLoader =CustomVolleyRequest.getInstance(context).getImageLoader();
imageLoader.get(imgModel.getImageUrl(),imageLoader.getImageListener(holder.imageView,R.drawable.placeholder,android.R.drawable.ic_dialog_alert));
holder.imageView.setImageUrl(imgModel.getImageUrl(),imageLoader);
holder.textViewName.setText(imgModel.getName());
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
link = listmodel.get(position).getName();
newModel.setItem(link);
Toast.makeText(context, "select item select" +link, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return listmodel.size();
}
public long getItemId(int position) {
return position;
}
class ViewHolder extends RecyclerView.ViewHolder {
public NetworkImageView imageView;
public TextView textViewName;
public ViewHolder(View itemView) {
super(itemView);
imageView = (NetworkImageView) itemView.findViewById(R.id.imageView_img);
imageView.setScaleType(NetworkImageView.ScaleType.FIT_CENTER);
textViewName = (TextView) itemView.findViewById(R.id.text_cate);
}
}
}
VerticalAdapter
public class VerticalAdapter extends RecyclerView.Adapter<VerticalAdapter.ViewHolder> {
private Context context;
String link;
List<TextJson> listmodel;
private Activity parentActivity;
public VerticalAdapter(List<TextJson> listmodel, Context context) {
super();
this.listmodel = listmodel;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.text_virtically, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
TextJson model = listmodel.get(position);
holder.textViewName.setText(model.getText_status());
holder.textViewName.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
link = listmodel.get(position).getText_status();
return true;
}
});
}
#Override
public int getItemCount() {
return listmodel.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public TextView textViewName;
public ViewHolder(View itemView) {
super(itemView);
textViewName = (TextView) itemView.findViewById(R.id.texting_status);
}
}
}
Log
08-01 18:28:14.021 11378-11378/com.vm.recyclervirtical E/text: is==> Stinging Jellyfish Come to Jersey, But Beaches Sti
08-01 18:28:14.021 11378-11378/com.vm.recyclervirtical E/cate: is==> speech
08-01 18:28:14.021 11378-11378/com.vm.recyclervirtical E/text: is==> Koala Facts for Kids | Australian Animals
08-01 18:28:14.021 11378-11378/com.vm.recyclervirtical E/cate: is==> motivational
08-01 18:28:14.021 11378-11378/com.vm.recyclervirtical E/text: is==> Antarctic penguins ielts reading passage
08-01 18:28:14.021 11378-11378/com.vm.recyclervirtical E/cate: is==> dance
08-01 18:28:14.061 11378-11378/com.vm.recyclervirtical E/CacheĀ is: 0_0==>com.android.volley.toolbox.DiskBasedCache#41812ce8
08-01 18:28:24.861 11378-11378/com.vm.recyclervirtical E/text: resopnce is =>http://www.example.com/filtered/evideo/json/jsoncategory.php?category=motivational
08-01 18:28:25.331 11378-11378/com.vm.recyclervirtical E/text: resopnce is =>[{"txt":"Koala Facts for Kids | Australian Animals"}]
08-01 18:28:25.351 11378-11378/com.vm.recyclervirtical E/text: is==> Koala Facts for Kids | Australian Animals
Image
After debug
This is a broad problem, so I can suggest some basic approach, which is to pass the click listener into the constructor of the adapter.
public class HorizantalAdapter extends RecyclerView.Adapter<HorizantalAdapter.ViewHolder>
/*** Store a reference ***/
private View.OnClickListener clickListener;
/*** Add that reference ***/
public HorizantalAdapter(List<CategoryJson> listmodel, Context context, View.OnClickListener clickListener) {
super();
this.listmodel = listmodel;
this.context = context;
setHasStableIds(false);
/*** Set the reference ***/
this.clickListener = clickListener;
}
.......
#Override
public void onBindViewHolder(final HorizantalAdapter.ViewHolder holder, final int position) {
.........
/*** Use the reference ***/
holder.imageView.setOnClickListener(clickListener);
}
Then in the Activity, where you set the horizontal adapter
private void parseData(JSONArray array) {
.........
/*** Define the listener ***/
final View.OnClickListener horizontalClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
link = listmodel.get(position).getName();
newModel.setItem(link);
Toast.makeText(context, "select item select" +link, Toast.LENGTH_SHORT).show();
// TODO: Make Volley request for Categories here...
// Should be able to set other adapter in onResponse there
}
};
/*** Pass in the listener reference ***/
adapter = new HorizantalAdapter(horizentallylist, this, horizontalClickListener);
}
In response to the edit, the messages are coming from these lines
Log.e("text", "is==> " + text);
Log.e("cate", "is==> " + txtcate);

notifyDataSetChanged on RecyclerView android

I have problem with my code in notifyDataSetChanged on Recyclerview. Here is my code, please help me to fix it.
public class FragmentListFilm extends BaseFragment {
private static final String TAG = FragmentListFilm.class.getSimpleName();
private static final String url "http://api.androidhive.info/json/movies.json";
private List<InforFilm> inforFilms = new ArrayList<InforFilm>();
private Fragment_Film_Adapter adapter;
private DialogActivity dialogActivity;
View root;
private ProgressDialog pDialog;
private RecyclerView rv;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root = inflater.inflate(R.layout.fragment_film, container, false);
rv = (RecyclerView) root.findViewById(R.id._recycler_fragment_film);
setUpRecycleView(rv);
return root;
}
private void setUpRecycleView(RecyclerView recycleView) {
recycleView.setLayoutManager(new LinearLayoutManager(recycleView.getContext()));
recycleView.setAdapter(adapter);
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// recycleView.
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
// Log.d(TAG, "try-cat");
JSONObject obj = response.getJSONObject(i);
InforFilm film = new InforFilm();
film.setTitle(obj.getString("title"));
film.setThumbail(obj.getString("image"));
film.setRating(((Number) obj.get("rating"))
.doubleValue());
film.setYear(obj.getInt("releaseYear"));
// Genre is json array
JSONArray genreArry = obj.getJSONArray("genre");
ArrayList<String> genre = new ArrayList<String>();
for (int j = 0; j < genreArry.length(); j++) {
genre.add((String) genreArry.get(j));
}
film.setGender(genre);
// adding movie to movies array
inforFilms.add(film);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
Log.d(TAG, "notifydatasetchanged");
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
////// Adapter
public class Fragment_Film_Adapter extends RecyclerView.Adapter<Fragment_Film_Adapter.ViewHolder> {
private List<InforFilm> inforFilms;
ImageLoader imageLoader = AppController.getInstance().getmImageLoader();
public Fragment_Film_Adapter(List<InforFilm> inforFilms) {
this.inforFilms = inforFilms;
}
public class ViewHolder extends RecyclerView.ViewHolder {
#Bind(R.id.film_thumbnail)
NetworkImageView thumbNail;
#Bind(R.id.film_genre)
TextView gender;
#Bind(R.id.film_rating)
TextView rating;
#Bind(R.id.film_title)
TextView title;
#Bind(R.id.film_releaseYear)
TextView year;
public ViewHolder(View view) {
super(view);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_film_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
InforFilm infor = inforFilms.get(position);
holder.thumbNail.setImageUrl(infor.getThumbail(), imageLoader);
holder.title.setText(infor.getTitle());
holder.rating.setText(String.valueOf(infor.getRating()));
holder.year.setText(infor.getYear());
String genreStr = "";
for (String str : infor.getGender()) {
genreStr += str + ", ";
}
genreStr = genreStr.length() > 0 ? genreStr.substring(0,
genreStr.length() - 2) : genreStr;
holder.gender.setText(genreStr);
}
#Override
public int getItemCount() {
return inforFilms.size();
}
}
It throws the following exception:
Attempt to invoke virtual method 'void com.example.qtv.qtvmaterial.adapter.Fragment_Film_Adapter.notifyDataSetChanged()' on a null object reference
at com.example.qtv.qtvmaterial.fragment.FragmentListFilm$1.onResponse(FragmentListFilm.java:110)
at com.example.qtv.qtvmaterial.fragment.FragmentListFilm$1.onResponse(FragmentListFilm.java:71)
Before setting adapter to RecyclerView initialize it:
recycleView.setLayoutManager(new LinearLayoutManager(recycleView.getContext()));
adapter = new Fragment_Film_Adapter(inforFilms);
recycleView.setAdapter(adapter);

RecyclerView during OnRefresh adds another recyclerView List?

when I conduct onRefresh, my recyclerView adds on another copy to my current recyclerView instead of refreshing it, by looking at my code below does anyone know what the problem is?I have tried everything but nothing seems to work?
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
//send our volley JSON Request
//Initialize VolleySingleton
mVolleySingleton = VolleySingleton.getInstance();
//intitalize Volley Singleton request key
mRequestQueue = mVolleySingleton.getRequestQueue();
//2 types of requests an Array request and an Object Request
JSONArrayRequest();
}
private void JSONArrayRequest() {
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, URL_API, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
listblogs=parseJSONResponse(response);
mAdapterDashBoard.setBloglist(listblogs);
System.out.println("it worked!!!");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
ToastTest.t(getActivity(), error.toString());
}
});
mRequestQueue.add(request);
}
private ArrayList<Blogs> parseJSONResponse(JSONArray response) {
if (!response.equals("")) {
ArrayList<Blogs> blogsArrayList = new ArrayList<>();
try {
StringBuilder data = new StringBuilder();
for (int i = 0; i < response.length(); i++) {
JSONObject currentQuestions = response.getJSONObject(i);
String text = currentQuestions.getString("text");
String points = currentQuestions.getString("points");
String ID=currentQuestions.getString("id");
String courseId = currentQuestions.getString("courseId");
String studentId = currentQuestions.getString("studentId");
data.append(text + "\n" + points + "\n" + courseId + "\n");
System.out.println(data);
Blogs blogs = new Blogs();
blogs.setId(ID);
blogs.setMstudentId(studentId);
blogs.setMtext(text);
blogs.setPoints(points);
listblogs.add(blogs);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return listblogs;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view=inflater.inflate(R.layout.fragment_dashboard,container,false);
mRecyclerView=(RecyclerView)view.findViewById(R.id.fragment_dashboard);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mAdapterDashBoard=new AdapterDashBoard(getActivity());
mRecyclerView.setAdapter(mAdapterDashBoard);
mPullToRefreshView = (PullToRefreshView)view.findViewById(R.id.pull_to_refresh);
mPullToRefreshView.setOnRefreshListener(new PullToRefreshView.OnRefreshListener() {
#Override
public void onRefresh() {
mPullToRefreshView.postDelayed(new Runnable() {
#Override
public void run() {
mPullToRefreshView.setRefreshing(false);
JSONArrayRequest();
}
}, REFRESH_DELAY);
}
});
return view;
}
}
public class AdapterDashBoard extends RecyclerView.Adapter<AdapterDashBoard.ViewDashboard>{
private LayoutInflater mLayoutInflater;
private ArrayList<Blogs> listblogs=new ArrayList<>();
public AdapterDashBoard(Context context){
mLayoutInflater=LayoutInflater.from(context);
}
public void setBloglist(ArrayList<Blogs> listBlogs){
this.listblogs=listBlogs;
notifyItemRangeChanged(0,listBlogs.size());
}
#Override
public ViewDashboard onCreateViewHolder(ViewGroup parent, int viewType) {
View view= mLayoutInflater.inflate(R.layout.customizejson,parent,false);
ViewDashboard viewholder=new ViewDashboard(view);
return viewholder;
}
#Override
public void onBindViewHolder(ViewDashboard holder, int position) {
Blogs currentBlog=listblogs.get(position);
holder.questionText.setText(currentBlog.getMtext().toString());
holder.points.setText(currentBlog.getPoints().toString());
holder.id.setText(currentBlog.getId().toString());
}
#Override
public int getItemCount() {
return listblogs.size();
}
static class ViewDashboard extends RecyclerView.ViewHolder{
private ImageView thumbnail;
private TextView questionText;
private TextView points;
private TextView id;
public ViewDashboard (View itemView){
super(itemView);
//thumbnail=(ImageView)itemView.findViewById(R.id.thumbnail);
questionText=(TextView)itemView.findViewById(R.id.questionText);
points=(TextView)itemView.findViewById(R.id.points);
id=(TextView)itemView.findViewById(R.id.ID);
}
}
}
You need to clear your listblogs list before adding new items. This is why you get duplicated values.
Also you're already adding new items to listblogs in parseJSONResponse() method, so there is no need for listblogs=parseJSONResponse(response); in onResponse() method, while its the same list.
Change your onResponse() method to:
#Override
public void onResponse(JSONArray response) {
listblogs.clear(); // here you clear the old data
parseJSONResponse(response);
mAdapterDashBoard.setBloglist(listblogs);
System.out.println("it worked!!!");
}

Categories

Resources