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);
Related
here getItemCount() not null, but here getlayoutmanager is null. plz help me to solved this. i'm trying to loadmore data when user scroll down recyclerview at end of scrolling load another data so on. This Error occurred in adapter.
here getLayoutManager() is get null:
final GridLayoutManager gridLayoutManager = (GridLayoutManager) recyclerView.getLayoutManager();
My Adapter code:
public class ImageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context mCtx;
private ImageView link;
private boolean isLoading;
private List<Image> imageList;
private int visibleThreshold = 5;
private final int VIEW_TYPE_ITEM = 0;
private final int VIEW_TYPE_LOADING = 1;
private int lastVisibleItem, totalItemCount;
private OnLoadMoreListener onLoadMoreListener;
public ImageAdapter(RecyclerView recyclerView, List<Image> imageList, Context mCtx) {
this.imageList = imageList;
this.mCtx = mCtx;
final GridLayoutManager gridLayoutManager = (GridLayoutManager) recyclerView.getLayoutManager();
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
Log.d(TAG, "Tj_getItemCount" + getItemCount());
Log.d(TAG, "Tj_linearLayoutManager" + gridLayoutManager);
totalItemCount = gridLayoutManager.getItemCount();
lastVisibleItem = gridLayoutManager.findLastVisibleItemPosition();
if (!isLoading && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
if (onLoadMoreListener != null) {
onLoadMoreListener.onLoadMore();
}
isLoading = true;
}
}
});
}
public void setOnLoadMoreListener(OnLoadMoreListener mOnLoadMoreListener) {
this.onLoadMoreListener = mOnLoadMoreListener;
}
#Override
public int getItemViewType(int position) {
return imageList.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == VIEW_TYPE_ITEM) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View v = inflater.inflate(R.layout.list_items, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
} else if (viewType == VIEW_TYPE_LOADING) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_loading, parent, false);
LoadingViewHolder vh1 = new LoadingViewHolder(view);
return vh1;
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof ViewHolder) {
final Image image = imageList.get(position);
final String imgUrl = image.getThumb();
link.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), ViewImage.class);
intent.putExtra("URL", imgUrl);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
v.getContext().startActivity(intent);
}
});
Glide.with(mCtx).load(imgUrl).into(link);
} else if (holder instanceof LoadingViewHolder) {
LoadingViewHolder loadingViewHolder = (LoadingViewHolder) holder;
loadingViewHolder.progressBar.setIndeterminate(true);
}
}
#Override
public int getItemCount() {
return imageList == null ? 0 : imageList.size();
}
public void setLoaded() {
isLoading = false;
}
private class LoadingViewHolder extends RecyclerView.ViewHolder {
public ProgressBar progressBar;
LoadingViewHolder(View view) {
super(view);
progressBar = view.findViewById(R.id.progressBar1);
}
}
class ViewHolder extends RecyclerView.ViewHolder {
ViewHolder(View v) {
super(v);
link = v.findViewById(R.id.link);
}
}
}
My Activity code:
public class MainActivity extends AppCompatActivity {
//the URL having the json data https://api.unsplash.com/search/photos?query=canada&client_id=8b0a3f8ddb23f80f16303601c12664119e27c2d26a6fc7b43bcba68d5c35f73c
// private static final String JSON_URL = "https://api.unsplash.com/photos/random?count=25&client_id=8b0a3f8ddb23f80f16303601c12664119e27c2d26a6fc7b43bcba68d5c35f73c";
// private static final String JSON_URL = "https://api.unsplash.com/photos/?client_id=8b0a3f8ddb23f80f16303601c12664119e27c2d26a6fc7b43bcba68d5c35f73c";
int i = 2;
Image hero;
String query;
List<Image> imageList;
RecyclerView listView;
private static String JSON_URL;
private static final String TAG = "Tj";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//initializing listview and hero list
listView = findViewById(R.id.listView);
imageList = new ArrayList<>();
Intent intent = getIntent();
query = intent.getStringExtra("category");
JSON_URL = "https://api.unsplash.com/search/photos?query=" + query + "&client_id=8b0a3f8ddb23f80f16303601c12664119e27c2d26a6fc7b43bcba68d5c35f73c&page=1";
Log.d(TAG, "Query" + JSON_URL);
loadHeroList();
}
private void loadHeroList() {
//getting the progressbar
final ProgressBar progressBar = findViewById(R.id.progressBar);
//making the progressbar visible
progressBar.setVisibility(View.VISIBLE);
//creating a string request to send request to the url
StringRequest jsonArrayRequest = new StringRequest(Request.Method.GET, JSON_URL,
new Response.Listener<String>() {
// JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
// Request.Method.GET,
// JSON_URL,
// null,
// new Response.Listener<JSONArray>() {
#Override
public void onResponse(String response) {
//hiding the progressbar after completion
progressBar.setVisibility(View.INVISIBLE);
try {
//getting the whole json object from the response
JSONObject obj = new JSONObject(response);
//we have the array named hero inside the object
//so here we are getting that json array
JSONArray heroArray = obj.getJSONArray("results");
//now looping through all the elements of the json array
for (int i = 0; i < heroArray.length(); i++) {
//getting the json object of the particular index inside the array
JSONObject jsonObject = heroArray.getJSONObject(i);
JSONObject jsonObject1 = jsonObject.getJSONObject("urls");
//creating a hero object and giving them the values from json object
hero = new Image(jsonObject.getString("id"),
jsonObject.getString("color"),
jsonObject1.getString("full"));
//adding the hero to herolist
imageList.add(hero);
}
//creating custom adapter object
final ImageAdapter adapter = new ImageAdapter(listView, imageList, getApplicationContext());
listView.setHasFixedSize(true);
// use a grid layout manager
listView.setLayoutManager(new GridLayoutManager(MainActivity.this, 2));
//adding the adapter to listview
listView.setAdapter(adapter);
adapter.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
if (imageList.size() <= 20) {
imageList.add(null);
adapter.notifyItemInserted(imageList.size() - 1);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
imageList.remove(imageList.size() - 1);
adapter.notifyItemRemoved(imageList.size());
JSON_URL = "https://api.unsplash.com/search/photos?query=" + query + "&client_id=8b0a3f8ddb23f80f16303601c12664119e27c2d26a6fc7b43bcba68d5c35f73c&page=" + i;
Log.d(TAG, "QueryLoadMore" + JSON_URL);
i++;
StringRequest jsonArrayRequest = new StringRequest(Request.Method.GET, JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//hiding the progressbar after completion
progressBar.setVisibility(View.INVISIBLE);
try {
//getting the whole json object from the response
JSONObject obj = new JSONObject(response);
//we have the array named hero inside the object
//so here we are getting that json array
JSONArray heroArray = obj.getJSONArray("results");
//now looping through all the elements of the json array
for (int i = 0; i < heroArray.length(); i++) {
//getting the json object of the particular index inside the array
JSONObject jsonObject = heroArray.getJSONObject(i);
JSONObject jsonObject1 = jsonObject.getJSONObject("urls");
//creating a hero object and giving them the values from json object
hero = new Image(jsonObject.getString("id"),
jsonObject.getString("color"),
jsonObject1.getString("full"));
//adding the hero to herolist
imageList.add(hero);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
//creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
//adding the string request to request queue
requestQueue.add(jsonArrayRequest);
// imageList.add(hero);
// }
adapter.notifyDataSetChanged();
adapter.setLoaded();
}
}, 5000);
} else {
Toast.makeText(MainActivity.this, "Loading data completed", Toast.LENGTH_SHORT).show();
}
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
//creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//adding the string request to request queue
requestQueue.add(jsonArrayRequest);
}
}
You never set any kind of LayoutManager to your listView.
You must set the layout manager before creating your custom adapter object.
You can set it by calling: recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns)); Then you are able to get it later in your ImageAdapter class.
Image before scroll - Image After Scroll
I'm trying to develop application like wallpaper app when i select any category then open it and when i scroll this RecyclerView that time load page 2 images from api and so on but when i scroll RecyclerView image change it's position and load duplicate of it. plz help me to solved this.
My Adapter :
public class ImageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context mCtx;
private ImageView link;
private boolean isLoading;
private List<Image> imageList;
private int visibleThreshold = 4;
private final int VIEW_TYPE_ITEM = 0;
private final int VIEW_TYPE_LOADING = 1;
private int lastVisibleItem, totalItemCount;
private OnLoadMoreListener onLoadMoreListener;
public ImageAdapter(RecyclerView recyclerView, List<Image> imageList, Context mCtx) {
this.mCtx = mCtx;
this.imageList = imageList;
if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {
final LinearLayoutManager gridLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
totalItemCount = gridLayoutManager.getItemCount();
lastVisibleItem = gridLayoutManager.findLastVisibleItemPosition();
if (!isLoading && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
if (onLoadMoreListener != null) {
onLoadMoreListener.onLoadMore();
}
isLoading = true;
}
}
// }
});
}
}
public void setOnLoadMoreListener(OnLoadMoreListener mOnLoadMoreListener) {
this.onLoadMoreListener = mOnLoadMoreListener;
}
#Override
public int getItemViewType(int position) {
return imageList.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == VIEW_TYPE_ITEM) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View v = inflater.inflate(R.layout.list_items, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
} else if (viewType == VIEW_TYPE_LOADING) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_loading, parent, false);
LoadingViewHolder vh1 = new LoadingViewHolder(view);
return vh1;
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof ViewHolder) {
final Image image = imageList.get(position);
final String imgUrl = image.getThumb();
link.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), ViewImage.class);
intent.putExtra("URL", imgUrl);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
v.getContext().startActivity(intent);
}
});
Glide.with(mCtx).load(imgUrl).into(link);
} else if (holder instanceof LoadingViewHolder) {
LoadingViewHolder loadingViewHolder = (LoadingViewHolder) holder;
loadingViewHolder.progressBar.setIndeterminate(true);
}
}
#Override
public int getItemCount() {
return imageList.size();
}
public void setLoaded() {
isLoading = false;
}
private class LoadingViewHolder extends RecyclerView.ViewHolder {
public ProgressBar progressBar;
LoadingViewHolder(View view) {
super(view);
progressBar = view.findViewById(R.id.progressBar1);
}
}
class ViewHolder extends RecyclerView.ViewHolder {
ViewHolder(View v) {
super(v);
link = v.findViewById(R.id.link);
}
}
}
My Activity :
public class MainActivity extends AppCompatActivity {
int i = 1;
String query;
List<Image> imageList;
RecyclerView listView;
ImageAdapter adapter;
private static String JSON_URL;
private static final String TAG = "Tj";
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//initializing listview and hero list
listView = findViewById(R.id.listView);
imageList = new ArrayList<>();
Intent intent = getIntent();
query = intent.getStringExtra("category");
JSON_URL = "https://api.unsplash.com/search/photos?query=" + query +
"&client_id=xxxxx&page=" + i;
Log.d(TAG, "Query " + JSON_URL);
loadHeroList();
}
private void loadHeroList() {
//getting the progressbar
progressBar = findViewById(R.id.progressBar);
//making the progressbar visible
progressBar.setVisibility(View.VISIBLE);
//creating a string request to send request to the url
StringRequest jsonArrayRequest = new StringRequest(Request.Method.GET, JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//hiding the progressbar after completion
progressBar.setVisibility(View.INVISIBLE);
try {
//getting the whole json object from the response
JSONObject obj = new JSONObject(response);
//we have the array named hero inside the object
//so here we are getting that json array
JSONArray heroArray = obj.getJSONArray("results");
//now looping through all the elements of the json array
for (int i = 0; i < heroArray.length(); i++) {
//getting the json object of the particular index inside the array
JSONObject jsonObject = heroArray.getJSONObject(i);
JSONObject jsonObject1 = jsonObject.getJSONObject("urls");
//creating a hero object and giving them the values from json object
Image hero = new Image(jsonObject.getString("id"),
jsonObject.getString("color"),
jsonObject1.getString("full"));
//adding the hero to herolist
imageList.add(hero);
listView.setHasFixedSize(true);
// use a grid layout manager
listView.setLayoutManager(new GridLayoutManager(MainActivity.this, 2));
}
//creating custom adapter object
adapter = new ImageAdapter(listView, imageList, getApplicationContext());
//adding the adapter to listview
listView.setAdapter(adapter);
//Load More Pages Start Here
adapter.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
loadMoreData();
}
});
//Complete for Load More Pages
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
//creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//adding the string request to request queue
requestQueue.add(jsonArrayRequest);
}
private void loadMoreData() {
imageList.add(null);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
adapter.notifyItemInserted(imageList.size() - 1);
imageList.remove(imageList.size() - 1);
adapter.notifyItemRemoved(imageList.size());
i++;
Log.d(TAG, "ILoadMore " + i);
String JSON_URL_LoadMore = "https://api.unsplash.com/search/photos?query=" + query + "&client_id=xxxxx&page=" + i;
Log.d(TAG, "QueryLoadMore " + JSON_URL_LoadMore);
StringRequest jsonArrayRequestLoadMore = new StringRequest(Request.Method.GET, JSON_URL_LoadMore,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//hiding the progressbar after completion
progressBar.setVisibility(View.INVISIBLE);
try {
//getting the whole json object from the response
JSONObject obj = new JSONObject(response);
//we have the array named hero inside the object
//so here we are getting that json array
JSONArray heroArray = obj.getJSONArray("results");
//now looping through all the elements of the json array
for (int i = 0; i < heroArray.length(); i++) {
//getting the json object of the particular index inside the array
JSONObject jsonObject = heroArray.getJSONObject(i);
JSONObject jsonObject1 = jsonObject.getJSONObject("urls");
//creating a hero object and giving them the values from json object
Image hero = new Image(jsonObject.getString("id"),
jsonObject.getString("color"),
jsonObject1.getString("full"));
//adding the hero to herolist
imageList.add(hero);
adapter.notifyItemInserted(imageList.size());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
//creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
//adding the string request to request queue
requestQueue.add(jsonArrayRequestLoadMore);
adapter.notifyDataSetChanged();
adapter.setLoaded();
}
}, 5000);
}
}
Override
#Override
public long getItemId(int position) {
return position;
}
And use
Picasso.with(context)
.load(getImgUrl)
.placeholder(R.drawable.user_placeholder)
.fit()
.into(imageView);
Or else
To retain and restore recyclerview position on scrolling, please try below link.
https://panavtec.me/retain-restore-recycler-view-scroll-position
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);
}
}
}
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());
From a JSON array that I am parsing, I want to send a particular object value (using intent putExtra) to another activity. I have read this this question
and the accepted answer but I don't want to send all the values, in my case I only want to send the news_id as an integer to NewsDetails.class.
And I tried using the accepted answer to do it but I got stuck.
MainActivity
public class MainActivity extends AppCompatActivity{
private final String TAG = "MainActivity";
//Creating a list of newss
private List<NewsItems> mNewsItemsList;
//Creating Views
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "Device rotated and onCreate called");
//Initializing Views
recyclerView = (RecyclerView) findViewById(R.id.news_recycler);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
//Initializing the newslist
mNewsItemsList = new ArrayList<>();
adapter = new NewsAdapter(mNewsItemsList, this);
recyclerView.setAdapter(adapter);
//Caling method to get data
getData();
}
//This method will get data from the web api
private void getData(){
Log.d(TAG, "getData called");
//Showing progress dialog
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setCancelable(false);
mProgressDialog.setMessage(this.getResources().getString(R.string.load_news));
mProgressDialog.show();
//Creating a json request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(ConfigNews.GET_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, "onResponse called");
//Dismissing the progress dialog
if (mProgressDialog != null) {
mProgressDialog.hide();
}
/*progressDialog.dismiss();*/
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//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){
Log.d(TAG, "Parsing array");
for(int i = 0; i<array.length(); i++) {
NewsItems newsItem = new NewsItems();
JSONObject jsonObject = null;
try {
jsonObject = array.getJSONObject(i);
newsItem.setNews_title(jsonObject.getString(ConfigNews.TAG_NEWS_TITLE));
newsItem.setNews_excerpt(jsonObject.getString(ConfigNews.TAG_NEWS_EXCERPT));
newsItem.setNewsId(jsonObject.getInt(ConfigNews.TAG_NEWS_ID));
} catch (JSONException w) {
w.printStackTrace();
}
mNewsItemsList.add(newsItem);
}
adapter.notifyItemRangeChanged(0, adapter.getItemCount());
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy called");
if (mProgressDialog != null){
mProgressDialog.dismiss();
Log.d(TAG, "mProgress dialog dismissed");
}
}
}
NewsItems class
public class NewsItems {
private String news_title;
private String news_excerpt;
private int news_id;
public String getNews_title() {
return news_title;
}
public void setNews_title(String news_title) {
this.news_title = news_title;
}
public String getNews_excerpt() {
return news_excerpt;
}
public void setNews_excerpt(String news_excerpt) {
this.news_excerpt = news_excerpt;
}
public int getNews_id() {
return news_id;
}
public void setNews_id(int news_id) {
this.news_id = news_id;
}
}
NewsAdapter
public class NewsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private ImageLoader imageLoader;
private Context mContext;
//List of newss
private List<NewsItems> mNewsItems;
private final int VIEW_ITEM = 0;
private final int VIEW_PROG = 1;
private int lastPosition = -1;
public NewsAdapter(List<NewsItems> newsItems, Context context) {
super();
//Getting all newss
this.mNewsItems = newsItems;
this.mContext = context;
}
#Override
public int getItemViewType(int position) {
if (isPositionItem(position))
return VIEW_ITEM;
return VIEW_PROG;
}
private boolean isPositionItem(int position) {
return position != getItemCount()-1;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder (ViewGroup parent, int viewType) {
if (viewType == VIEW_ITEM) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.news_summ, parent, false);
return new TextViewHolder(v, mContext);
} else if (viewType == VIEW_PROG){
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recyclerfooter, parent, false);
return new ProgressViewHolder(v);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof TextViewHolder) {
NewsItems newsList = mNewsItems.get(position);
((TextViewHolder) holder).newsTitle.setText(newsList.getNews_title());
((TextViewHolder) holder).newsExcerpt.setText(newsList.getNews_excerpt());
((TextViewHolder) holder).newsId.setText(String.valueOf(newsList.getNewsId()));
} else {
((ProgressViewHolder) holder).progressBar.setIndeterminate(true);
((ProgressViewHolder) holder).loadButton.setText(R.string.reload);
}
}
#Override
public int getItemCount(){
//Return the number of items in the data set
return mNewsItems.size();
}
public static class TextViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView newsTitle,newsExcerpt, newsId;
public ImageButton imageButton;
public NewsItems dNewsItems;
private Context context;
public TextViewHolder (final View newsView, final Context context) {
super(newsView);
this.context = context;
newsTitle = (TextView) newsView.findViewById(R.id.news_title);
newsExcerpt = (TextView) newsView.findViewById(R.id.news_excerpt);
newsId = (TextView) newsView.findViewById(R.id.news_id);
newsExcerpt.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == newsExcerpt.getId()) {
Intent intent = new Intent(context, NewsDetails.class);
Bundle bundle = new Bundle();
bundle.putSerializable("PostId", //This is where I got confused);
}
}
}
}
public static class ProgressViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
Button loadButton;
ProgressBar progressBar;
public ProgressViewHolder(View footerView){
super(footerView);
loadButton = (Button) footerView.findViewById(R.id.reload_button);
progressBar = (ProgressBar) footerView.findViewById(R.id.progress_load);
loadButton.setOnClickListener(this);
if(NetworkCheck.isAvailableAndConnected(footerView.getContext())) {
progressBar.setVisibility(View.VISIBLE);
} else if (!NetworkCheck.isAvailableAndConnected(footerView.getContext())) {
loadButton.setVisibility(View.VISIBLE);
}
}
#Override
public void onClick(View v) {
if (v.getId() == loadButton.getId()) {
//
}
}
}
}
You can send single value also instead of complete object like this -
#Override
public void onClick(View v) {
if (v.getId() == newsExcerpt.getId()) {
Intent intent = new Intent(context, NewsDetails.class);
intent.putExtra("PostId",<your_news_id_here>);
startActivity(intent);
}
}
}
In your case, remove onClick(View v) and change your onBindViewHolder() to setOnClickListener() on newsExcerpt like this -
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof TextViewHolder) {
NewsItems newsList = mNewsItems.get(position);
((TextViewHolder) holder).newsTitle.setText(newsList.getNews_title());
((TextViewHolder) holder).newsExcerpt.setText(newsList.getNews_excerpt());
((TextViewHolder) holder).newsId.setText(String.valueOf(newsList.getNewsId()));
((TextViewHolder) holder).newsExcerpt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, NewsDetails.class);
intent.putExtra("PostId",newsList.getNewsId()); //Any getter of your class you want
startActivity(intent);
});
} else {
((ProgressViewHolder) holder).progressBar.setIndeterminate(true);
((ProgressViewHolder) holder).loadButton.setText(R.string.reload);
}
}
I don't want to send all the values
You dont' have to send all, It's up to you and your needs.
Intent i = new Intent(context, DestActivity.class);
i.putExtra(KEY_NEWS_ID, news_id );
On the other end:
int news_id = getIntent().getIntExtra(KEY_NEWS_ID, defaultValue);