How to fetch link from json and connect it to button? - android

I am working with a project and I am trying to fetch some link from a json data and I want to connect the link with a button in my recycleview so that whenever the button is clicked, it'll automatically connet to the respective websites. I gave user permission to interner in Manifest. So, How to connect it?
package com.example.covidcuretemplate1;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RequestQueue requestQueue;
private ExampleAdapter exampleAdapter;
private ArrayList<ExampleItem> exampleList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL,false));
exampleList = new ArrayList<>();
requestQueue = Volley.newRequestQueue(this);
parseJSON();
}
private void parseJSON() {
String url = "https://newsapi.org/v2/top-headlines?country=in&category=health&apiKey=*************************";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("articles");
for(int i = 0; i < jsonArray.length(); i++)
{
JSONObject article = jsonArray.getJSONObject(i);
if(article.isNull("description") || article.isNull("urlToImage")) {
continue;
}
if(article.getString("description").isEmpty() || article.getString("urlToImage").isEmpty())
continue;
String title = article.getString("title");
String description = article.getString("description");
String date = article.getString("publishedAt");
String imageurl = article.getString("urlToImage");
//How to connect this??????
String newsurl = article.getString("url");
exampleList.add(new ExampleItem(imageurl,title,description,date));
}
exampleAdapter = new ExampleAdapter(MainActivity.this,exampleList);
recyclerView.setAdapter(exampleAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
requestQueue.add(request);
}
}
My Adapter class, Here can anybody suggest anything in the place of toast? The Toast is working fine !!!
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
public Context mcontext;
public ArrayList<ExampleItem> marrayList;
public ExampleAdapter(Context mcontext, ArrayList<ExampleItem> marrayList) {
this.mcontext = mcontext;
this.marrayList = marrayList;
}
#NonNull
#Override
public ExampleViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mcontext).inflate(R.layout.card_item,parent,false);
ExampleViewHolder exampleViewHolder = new ExampleViewHolder(view);
return exampleViewHolder;
}
#Override
public void onBindViewHolder(#NonNull ExampleViewHolder holder, int position) {
ExampleItem examplItem = marrayList.get(position);
String imageurl = examplItem.getMimgurl();
String title = examplItem.getMtitle();
String description = examplItem.getMdescription();
String date = examplItem.getMdate();
/////////////
final String newsurl = examplItem.getMurl();
////////////
holder.textview_title.setText(title);
holder.textview_description.setText(description);
holder.textview_date.setText(date);
Glide.with(mcontext).load(imageurl).into(holder.imageview_news);
///////////////////////////
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//////////////////////////////////NEED HELP!!!!!!!!!!!!!!!!!!/////////
Toast.makeText(mcontext,newsurl,Toast.LENGTH_LONG).show();
}
});
//////////////////////////
}
#Override
public int getItemCount() {
return marrayList.size();
}
public static class ExampleViewHolder extends RecyclerView.ViewHolder{
public ImageView imageview_news;
public TextView textview_title;
public TextView textview_description;
public TextView textview_date;
///////////////////////////
public Button button;
///////////////////////////
public ExampleViewHolder(#NonNull View itemView) {
super(itemView);
imageview_news = itemView.findViewById(R.id.imageview_news);
textview_title = itemView.findViewById(R.id.textview_title);
textview_description = itemView.findViewById(R.id.textview_description);
textview_date = itemView.findViewById(R.id.textview_date);
/////////////////////////
button = itemView.findViewById(R.id.button);
////////////////////////
}
}
}

Try to set intent for the website inside the onClickListener. Something like this:
Button button= findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String url = "http://www.YourWebsite.com"; //insert the link you prase
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
}
});

You can use this code inside onClickListener to open it in the browser.
Uri uri = Uri.parse(newsurl);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);

Related

Recycler view doesn't show first item until refresh

I've got an app which saves a number and the date it was recorded in a recycler View, however when the array is empty and then I try to save my number, the RecyclerView does not show the item. The item did save, but it isn't displayed in the view. I know it save because when I go back to the view the item is there. I have looked ages for answer online and have seen nobody with the same issue. Thank you in advance for your help!
Activity 2:
package com.pinet.count;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.format.DateFormat;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
public class Activity2 extends AppCompatActivity {
private ExampleAdapter mAdapter;
private static final Date currentTime = Calendar.getInstance().getTime();
private ArrayList<ExampleItem> mexampleList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
Intent intent = getIntent();
String dateString= DateFormat.format("dd/MM/yyyy",currentTime).toString();
int count = intent.getIntExtra(MainActivity.EXTRA_NUMBER,0);
loadData();
buildRecyclerView();
if (count!=0){
if (mexampleList == null){
mexampleList = new ArrayList<ExampleItem>();
}
mexampleList.add(0, new ExampleItem(String.valueOf(count), dateString));
mAdapter.notifyItemInserted(0);
mAdapter.notifyItemRangeChanged(0,mexampleList.size());
}
saveList();
}
private void buildRecyclerView(){
RecyclerView mRecyclerView = findViewById(R.id.recyclerview);
mRecyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
mAdapter= new ExampleAdapter(mexampleList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(new ExampleAdapter.OnItemClickListener() {
#Override
public void onDeleteClick(int position) {
removeItem(position);
}
});
}
private void removeItem(int position){
mexampleList.remove(position);
mAdapter.notifyItemRemoved(position);
mAdapter.notifyItemRangeChanged(position, mexampleList.size());
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences",0);
sharedPreferences.edit().remove("count list").apply();
}package com.pinet.count;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.format.DateFormat;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
public class Activity2 extends AppCompatActivity {
private ExampleAdapter mAdapter;
private static final Date currentTime = Calendar.getInstance().getTime();
private ArrayList<ExampleItem> mexampleList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
Intent intent = getIntent();
String dateString= DateFormat.format("dd/MM/yyyy",currentTime).toString();
int count = intent.getIntExtra(MainActivity.EXTRA_NUMBER,0);
loadData();
buildRecyclerView();
if (count!=0){
if (mexampleList == null){
mexampleList = new ArrayList<ExampleItem>();
}
mexampleList.add(0, new ExampleItem(String.valueOf(count), dateString));
mAdapter.notifyItemInserted(0);
mAdapter.notifyItemRangeChanged(0,mexampleList.size());
}
saveList();
}
private void buildRecyclerView(){
RecyclerView mRecyclerView = findViewById(R.id.recyclerview);
mRecyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
mAdapter= new ExampleAdapter(mexampleList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(new ExampleAdapter.OnItemClickListener() {
#Override
public void onDeleteClick(int position) {
removeItem(position);
}
});
}
private void removeItem(int position){
mexampleList.remove(position);
mAdapter.notifyItemRemoved(position);
mAdapter.notifyItemRangeChanged(position, mexampleList.size());
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences",0);
sharedPreferences.edit().remove("count list").apply();
}
private void saveList(){
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(mexampleList);
editor.putString("count list", json);
editor.apply();
}
private void loadData(){
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("count list", null);
Type type = new TypeToken<ArrayList<ExampleItem>>() {}.getType();
mexampleList = gson.fromJson(json, type);
}
}
`
private void saveList(){
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(mexampleList);
editor.putString("count list", json);
editor.apply();
}
private void loadData(){
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("count list", null);
Type type = new TypeToken<ArrayList<ExampleItem>>() {}.getType();
mexampleList = gson.fromJson(json, type);
}
}
Main Activity:
package com.pinet.count;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private int count = 0;
public static final String EXTRA_NUMBER ="com.pinet.count.EXTRA_NUMBER";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textView= findViewById(R.id.textView);
Button buttonPos = findViewById(R.id.button);
Button buttonNeg = findViewById(R.id.button2);
Button buttonReset = findViewById(R.id.button3);
Button buttonSave = findViewById(R.id.button4);
Button butonHistory = findViewById(R.id.button5);
buttonPos.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
count +=1;
textView.setText(String.valueOf(count));
}
});
buttonNeg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
count-=1;
textView.setText(String.valueOf(count));
}
});
buttonReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
count = 0;
textView.setText(String.valueOf(count));
}
});
butonHistory.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
OpenActivity2();
}
});
buttonSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openActivity2();
}
});
}
private void openActivity2(){
Intent intent = new Intent(this, Activity2.class);
intent.putExtra(EXTRA_NUMBER, count);
startActivity(intent);
}
private void OpenActivity2(){
Intent intent = new Intent(this, Activity2.class);
startActivity(intent);
}
}
ExampleAdapter:
package com.pinet.count;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
private final ArrayList<ExampleItem> mExampleList;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onDeleteClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
public static class ExampleViewHolder extends RecyclerView.ViewHolder {
final TextView mTextView1;
final TextView mTextView2;
final ImageView mDeleteImage;
ExampleViewHolder(#NonNull View itemView, final OnItemClickListener listener) {
super(itemView);
mTextView1=itemView.findViewById(R.id.textView);
mTextView2=itemView.findViewById(R.id.textView2);
mDeleteImage=itemView.findViewById(R.id.image_delete);
mDeleteImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener !=null){
int position = getAdapterPosition();
if (position!=RecyclerView.NO_POSITION){
listener.onDeleteClick(position);
}
}
}
});
}
}
public ExampleAdapter(ArrayList<ExampleItem> exampleList){
mExampleList = exampleList;
}
#NonNull
#Override
public ExampleViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.example_item, parent, false);
return new ExampleViewHolder(v, mListener);
}
#Override
public void onBindViewHolder(#NonNull ExampleViewHolder holder, int position) {
ExampleItem currentItem = mExampleList.get(position);
holder.mTextView1.setText(currentItem.getmText1());
holder.mTextView2.setText(currentItem.getmText2());
}
#Override
public int getItemCount() {
if (mExampleList !=null) {
return mExampleList.size();
}
else {
return 0;
}
}
}
ExampleItem :
package com.pinet.count;
class ExampleItem {
private final String mText1;
private final String mText2;
public ExampleItem(String text1, String text2){
mText1= text1;
mText2= text2;
}
public String getmText1(){
return mText1;
}
public String getmText2(){
return mText2;
}
}
If you could also help me figure out animating the recycler view that would be appreciated !
PiNet
Change your onCreate() method inside the "Activity2" Activity to look like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
String dateString = DateFormat.format("dd/MM/yyyy",currentTime).toString();
Intent intent = getIntent();
int count = intent.getIntExtra(MainActivity.EXTRA_NUMBER,0);
loadData();
if (count!=0){
if (mexampleList == null){
mexampleList = new ArrayList<ExampleItem>();
}
String value = String.valueOf(count);
ExampleItem exampleItem = new ExampleItem(value, dateString);
mexampleList.add(0, exampleItem);
}
buildRecyclerView();
saveList();
}
I've changed the order of adding the new data to the ArrayList. This way the "new item" will be added to the list before you set the adapter. I have also extrapolated some if the code into distinct code lines. I recommend this because it will be easier to debug.
A few additional comments:
The method removeItem(int position) appears to remove the entire list from your SharedPreferences instead of what I assume you only want to remove the one item.
Also in your "MainActivity" you have two methods:
openActivity2()
and
OpenActivity2()
Firstly, Java naming convention dictates that method names begin with lower case. Secondly, this is very poor programing style to give methods indistinguishable method names.

How to Show JSON Data in Fragment Android Recyclerview Volley?

Please help with the following problems, the problem is that the data does not want to appear in the fragment home, even though the internet condition is on
My HomeFragment code:
package untag.adproj.lestari.lestari.Home;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import untag.adproj.lestari.lestari.R;
public class HomeFragment extends Fragment {
private String URL="http://pembuatanprogram.000webhostapp.com";
private RecyclerAdapter recyclerAdapter;
private RecyclerView recyclerView;
private ArrayList<Data> listdata;
private GridLayoutManager gridLayoutManager;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
recyclerView = view.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
gridLayoutManager = new GridLayoutManager(getActivity(), 2);
gridLayoutManager.setOrientation(GridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(gridLayoutManager);
listdata = new ArrayList<Data>();
AmbilData();
recyclerAdapter = new RecyclerAdapter(getActivity(),listdata);
recyclerView.setAdapter(recyclerAdapter);
recyclerAdapter.notifyDataSetChanged();
return view;
}
private void AmbilData() {
JsonArrayRequest aarRequest = new JsonArrayRequest(URL + "/produk.php" ,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response.length()>0){
for (int i =0 ; i<response.length();i++){
try {
JSONObject data = response.getJSONObject(i);
Data item = new Data();
item.setId(data.getString("id"));
item.setJudul(data.getString("judul"));
item.setHarga(data.getString("harga"));
item.setThubnail(data.getString(URL+"/img/"+data.getString("gambar")));
listdata.add(item);
recyclerAdapter.notifyDataSetChanged();
} catch (JSONException e) {
}
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
};
Volley.newRequestQueue(getActivity()).add(aarRequest);
}
}
My RecyclerAdapter code:
package untag.adproj.lestari.lestari.Home;
import android.app.Activity;
import android.content.Context;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import untag.adproj.lestari.lestari.R;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private ArrayList<Data> listdata;
private Activity activity;
private Context context;
public RecyclerAdapter(Activity activity, ArrayList<Data> listdata) {
this.listdata = listdata;
this.activity = activity;
}
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_home_list, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
//holder.mImage.setImageResource(listdata.get(position).getThubnail());
holder.id.setText(listdata.get(position).getId());
holder.judul.setText(listdata.get(position).getJudul());
holder.harga.setText(listdata.get(position).getHarga());
final ViewHolder x=holder;
Glide.with(activity)
.load(listdata.get(position).getThubnail())
.into(holder.thumbnail);
holder.id.setVisibility(View.GONE);
}
#Override
public int getItemCount() {
return listdata.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private CardView cv;
private TextView id,judul,harga;
private ImageView thumbnail;
public ViewHolder(View v) {
super(v);
cv=(CardView)v.findViewById(R.id.card_view);
id=(TextView)v.findViewById(R.id.id);
judul=(TextView)v.findViewById(R.id.judul);
harga=(TextView)v.findViewById(R.id.harga);
thumbnail=(ImageView)v.findViewById(R.id.thumbnail);
}
}
}
My Data code:
package untag.adproj.lestari.lestari.Home;
public class Data {
private String id;
private String judul;
private String harga;
private String thubnail;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getJudul() {
return judul;
}
public void setJudul(String judul) {
this.judul = judul;
}
public String getHarga() {
return harga;
}
public void setHarga(String harga) {
this.harga = harga;
}
public String getThubnail() {
return thubnail;
}
public void setThubnail(String thubnail) {
this.thubnail = thubnail;
}
}
My code refresh comes from Youtube
but in the tutorial it does not use fragment, please anyone help me
You have a wrong point, that is not update the list of recycler view, the list you add value in code listdata.add(item); belong to your fragment
Please add below method in your adapter
public void addData(List<Data> data) {
listdata.addAll(data);
notifyDataSetChanged();
}
And edit AmbilData function as below
private void AmbilData() {
JsonArrayRequest aarRequest = new JsonArrayRequest(URL + "/produk.php" ,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response.length()>0){
for (int i =0 ; i<response.length();i++){
try {
JSONObject data = response.getJSONObject(i);
Data item = new Data();
item.setId(data.getString("id"));
item.setJudul(data.getString("judul"));
item.setHarga(data.getString("harga"));
item.setThubnail(data.getString(URL+"/img/"+data.getString("gambar")));
listdata.add(item);
} catch (JSONException e) {
}
}
recyclerAdapter.addData(listdata);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
};
Volley.newRequestQueue(getActivity()).add(aarRequest);
}
package untag.adproj.lestari.lestari.Home;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import untag.adproj.lestari.lestari.R;
public class HomeFragment extends Fragment {
private String URL="http://pembuatanprogram.000webhostapp.com";
private RecyclerAdapter recyclerAdapter;
private RecyclerView recyclerView;
private ArrayList<Data> listdata;
private ArrayList<Data> tempList;
private GridLayoutManager gridLayoutManager;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
recyclerView = view.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
gridLayoutManager = new GridLayoutManager(getActivity(), 2);
gridLayoutManager.setOrientation(GridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(gridLayoutManager);
tempList = new ArrayList<Data>();
listdata = new ArrayList<Data>();
AmbilData();
recyclerAdapter = new RecyclerAdapter(getActivity(),listdata);
recyclerView.setAdapter(recyclerAdapter);
recyclerAdapter.notifyDataSetChanged();
return view;
}
private void AmbilData() {
JsonArrayRequest aarRequest = new JsonArrayRequest(URL + "/produk.php" ,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response.length()>0){
for (int i =0 ; i<response.length();i++){
try {
JSONObject data = response.getJSONObject(i);
Data item = new Data();
item.setId(data.getString("id"));
item.setJudul(data.getString("judul"));
item.setHarga(data.getString("harga"));
item.setThubnail(data.getString(URL+"/img/"+data.getString("gambar")));
tempList.add(item);
recyclerAdapter.notifyDataSetChanged();
} catch (JSONException e) {
}
}
listdata.clear();
listdata.addAll(tempList);
recyclerAdapter.notifyDataSetChanged();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
};
Volley.newRequestQueue(getActivity()).add(aarRequest);
}
}
Use temp list then addAll() method then call notifyDataSetChanged() method.
If you want to notify your adapter from a loop then you should go for notifyItemInserted() otherwise keep the notifyDataSetChanged() outside of the loop.
Like this;
for (int i =0 ; i<response.length();i++){
try {
JSONObject data = response.getJSONObject(i);
Data item = new Data();
item.setId(data.getString("id"));
item.setJudul(data.getString("judul"));
item.setHarga(data.getString("harga"));
item.setThubnail(data.getString(URL+"/img/"+data.getString("gambar")));
listdata.add(item);
recyclerAdapter.notifyItemInserted(listdata.size()-1); //To update the recyclerview one by one from a loop.
} catch (JSONException e) {
}
}
// OR
for (int i =0 ; i<response.length();i++){
try {
JSONObject data = response.getJSONObject(i);
Data item = new Data();
item.setId(data.getString("id"));
item.setJudul(data.getString("judul"));
item.setHarga(data.getString("harga"));
item.setThubnail(data.getString(URL+"/img/"+data.getString("gambar")));
listdata.add(item);
} catch (JSONException e) {
}
}
recyclerAdapter.notifyDataSetChanged(); //To update the whole recyclerview in one shot

Unable to use intent in adapter

While firing Intent finish activity i am getting this error
03-20 11:05:16.991 8566-8566/com.example.jenya1.ebilling E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.jenya1.ebilling, PID: 8566
java.lang.ClassCastException: droidninja.filepicker.FilePickerDelegate cannot be cast to android.app.Activity
at com.example.jenya1.ebilling.adapter.MaterialAdapter$1$1.onClick(MaterialAdapter.java:142)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
This line causing error
((Activity)mContext).finish(); //error
calling apapter class
private void loadMaterialRequest() {
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
//getting the progressbar
//making the progressbar visible
progressBar.setVisibility(View.VISIBLE);
albumList.clear();
//creating a string request to send request to the url
StringRequest stringRequest = new StringRequest(Request.Method.GET, HttpUrl+token+"&type="+type,
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);
JSONArray heroArray = obj.getJSONArray("response");
//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 heroObject = heroArray.getJSONObject(i);
//creating a hero object and giving them the values from json object
Material hero = new Material(
heroObject.getInt("Request_id"),
heroObject.getString("Site_name"),
heroObject.getString("User_id"),
heroObject.getString("Item_name"),
heroObject.getString("Quantity"),
heroObject.getString("Country"),
heroObject.getString("Request_date"),
heroObject.getString("Request_status"));
//adding the hero to herolist
albumList.add(hero);
}
//Log.e("list", String.valueOf(albumList));
//creating custom adapter object
adapter = new MaterialAdapter(getApplicationContext(),albumList);
//adding the adapter to listview
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("error", String.valueOf(error));
}
});
//creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//adding the string request to request queue
requestQueue.add(stringRequest);
}
I am trying to Intent when user click on alert dialog yes button
This is my adapter class:
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.example.jenya1.ebilling.MaterialHistoryActivity;
import com.example.jenya1.ebilling.R;
import com.example.jenya1.ebilling.model.HistoryQuotation;
import com.example.jenya1.ebilling.model.Material;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Mitesh Makwana on 18/03/18.
*/
public class MaterialAdapter extends RecyclerView.Adapter<MaterialAdapter.MyViewHolder> {
private Context mContext;
private List<Material> albumList;
private List lstfavquoteid;
String quote_id;
ArrayList<Integer> arryfavquoteid;
Typeface tf;
ArrayList<String> imageserver,imageList;
int count;
int status=0;
private int mExpandedPosition=-1;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title,quantity,site,date,note,req_id,status;
ImageView delete;
LinearLayout lndetail,lnapprove,lnreject,lnoperation;
CardView cdview;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.txttitle);
req_id = (TextView) view.findViewById(R.id.txtreqid);
quantity = (TextView) view.findViewById(R.id.txtquantity);
date = (TextView) view.findViewById(R.id.txtdate);
site = (TextView) view.findViewById(R.id.txtsite);
note = (TextView) view.findViewById(R.id.txtnotes);
status = (TextView) view.findViewById(R.id.txtstatus);
delete=(ImageView)view.findViewById(R.id.imgmdelete);
lndetail = (LinearLayout) view.findViewById(R.id.lndetails);
lnapprove = (LinearLayout) view.findViewById(R.id.lnapprove);
lnreject = (LinearLayout) view.findViewById(R.id.lnreject);
lnoperation = (LinearLayout) view.findViewById(R.id.lnstatusoperation);
cdview = (CardView) view.findViewById(R.id.card_view);
}
}
public MaterialAdapter(Context mContext, List<Material> albumList) {
this.mContext = mContext;
this.albumList = albumList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.raw_material_history, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
arryfavquoteid = new ArrayList<Integer>();
imageserver = new ArrayList<String>();
tf = Typeface.createFromAsset(mContext.getAssets(), "fonts/HKNova-Medium.ttf");
holder.title.setTypeface(tf);
holder.req_id.setTypeface(tf);
holder.quantity.setTypeface(tf);
holder.date.setTypeface(tf);
holder.site.setTypeface(tf);
holder.note.setTypeface(tf);
final Material album = albumList.get(position);
holder.title.setText(album.getItem_name());
holder.req_id.setText("#"+album.getId());
holder.quantity.setText(album.getQuantity());
holder.site.setText(album.getSite_id());
String input = album.getRequest_date();
input = input.replace(" ", "\n");
holder.date.setText(input);
holder.note.setText("Notes : "+album.getCountry());
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Toast.makeText(mContext, "Delete...", Toast.LENGTH_SHORT).show();
AlertDialog.Builder alert = new AlertDialog.Builder(
view.getContext());
alert.setTitle("Alert!!");
alert.setMessage("Are you sure to delete record");
alert.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
MaterialHistoryActivity.deleterequest(mContext,album.getId());
notifyDataSetChanged();
Intent i=new Intent(mContext,MaterialHistoryActivity.class);
mContext.startActivity(i);
((Activity)mContext).finish(); //error
dialog.dismiss();
}
});
alert.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.show();
}
});
if (mExpandedPosition == position) {
if(album.getRequest_status().equals("1"))
{
holder.status.setText("Approved");
holder.status.setVisibility(View.VISIBLE);
holder.status.setTextColor(Color.GREEN);
holder.lnoperation.setVisibility(View.GONE);
}else if(album.getRequest_status().equals("2"))
{
holder.status.setText("Rejected");
holder.status.setVisibility(View.VISIBLE);
holder.status.setTextColor(Color.RED);
holder.lnoperation.setVisibility(View.GONE);
}
else
{
holder.status.setVisibility(View.GONE);
holder.lnoperation.setVisibility(View.VISIBLE);
}
//creating an animation
Animation slideDown = AnimationUtils.loadAnimation(mContext, R.anim.slide_down);
//toggling visibility
holder.lndetail.setVisibility(View.VISIBLE);
//adding sliding effect
holder.lndetail.startAnimation(slideDown);
}
else
{
holder.lndetail.setVisibility(View.GONE);
}
holder.cdview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//getting the position of the item to expand it
mExpandedPosition = position;
//reloding the list
notifyDataSetChanged();
}
});
holder.lnapprove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Toast.makeText(mContext, "Approve...", Toast.LENGTH_SHORT).show();
MaterialHistoryActivity.materialpermission(mContext,album.getId(),1);
}
});
holder.lnreject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Toast.makeText(mContext, "Reject...", Toast.LENGTH_SHORT).show();
MaterialHistoryActivity.materialpermission(mContext,album.getId(),2);
}
});
}
#Override
public int getItemCount() {
return albumList.size();
}
}
Any help would be highly appreciated.
let see:
((Activity)mContext).finish();
The log say mContext is kind of FilePickerDelegate. So check your Adapter init function. I think you pass context as "this", but "this" reference to FilePickerDelegate. So change it to YourActivity.this ( with activity) or getActivity( in fragment)
You are passing the Application Context not the Activity Context in your adapter.
getApplicationContext();
Wherever you are passing it pass this or ActivityName.this instead.
Since you are trying to cast the Context you pass (Application not Activity as you thought) to an Activity with
(Activity)
you get this exception because you can't cast the Application to Activity since Application is not a sub-class of Activity.
Instead of Context use Activity in your adapter. As Activity can be cast to context but context can not be cast to activity.
Activity avtivity;
public MaterialAdapter(Activity activity, List<Material> albumList) {
this.activity = activity;
this.albumList = albumList;
}
In your calling activity when you initialize your adapter Call this adapter like below.
new MaterialAdapter(<your calling activity>.this, yourList);
view.getContext().startActivity(new Intent(mContext, MaterialHistoryActivity.class));

ReyclerView. Police Data Json - No adapter attached, skipping layout

Good afternoon guys, I am trying to fetch some data from the police data website.
Unfortunately, the application doesn't show any data saying "E/RecyclerView: No adapter attached; skipping layout".
I have attached the LatestCrimesActivity, adapter and the ListItem class.
Thank you for your help.
This is LatestCrimesActivity:
package com.example.cosmin.crimerate.Latest_crimes_api;
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.cosmin.crimerate.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class LatestCrimesActivity extends AppCompatActivity {
private static final String URL_DATA = "https://data.police.uk/api/crimes-street/all-crime?poly=52.268,0.543:52.794,0.238:52.130,0.478&date=2017-01";
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<ListItem> listItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_latest_crimes);
recyclerView = (RecyclerView) findViewById(R.id.recyclerViewlatest);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems=new ArrayList<>();
loadRecyclerViewData();
}
private void loadRecyclerViewData() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading data...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET,
URL_DATA,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray array = jsonObject.getJSONArray("");
for (int i=0; i<array.length();i++){
JSONObject o = array.getJSONObject(i);
ListItem item = new ListItem(
o.getString("category"),
o.getString("location_type"),
o.getString("street"),
o.getString("status")
);
listItems.add(item);
}
adapter = new MyAdapter(listItems, getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
Adapter:
package com.example.cosmin.crimerate.Latest_crimes_api;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.TextView;
import com.example.cosmin.crimerate.R;
import java.util.List;
/**
* Created by Cosmin on 25/11/2017.
*/
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<ListItem> listItems;
private Context context;
public MyAdapter(List<ListItem> listItems, LatestCrimesActivity latestCrimesActivity) {
this.listItems = listItems;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
ListItem listItem = listItems.get(position);
holder.textViewCat.setText(listItem.getCategory());
holder.textViewLoc.setText(listItem.getLocation());
holder.textViewStreet.setText(listItem.getStreet());
holder.textViewStatus.setText(listItem.getStatus());
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView textViewCat;
public TextView textViewLoc;
public TextView textViewStreet;
public TextView textViewStatus;
public ViewHolder(View itemView) {
super(itemView);
textViewCat = (TextView) itemView.findViewById(R.id.textViewCat);
textViewLoc = (TextView) itemView.findViewById(R.id.textViewLoc);
textViewStreet = (TextView) itemView.findViewById(R.id.textViewStreet);
textViewStatus = (TextView) itemView.findViewById(R.id.textViewStatus);
}
}
}
This is ListItem class:
package com.example.cosmin.crimerate.Latest_crimes_api;
/**
* Created by Cosmin on 25/11/2017.
*/
public class ListItem {
private String category;
private String location;
private String street;
private String status;
public ListItem (String category, String location, String street, String status){
this.category=category;
this.location=location;
this.street=street;
this.status=status;
}
public String getCategory (){
return category;
}
public String getLocation (){
return location;
}
public String getStreet (){
return street;
}
public String getStatus (){
return status;
}
}
Just try to change some lines. First set adapter before your api call.
recyclerView = (RecyclerView) findViewById(R.id.recyclerViewlatest);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems=new ArrayList<>();
adapter = new MyAdapter(listItems, getApplicationContext());
recyclerView.setAdapter(adapter);
Then when you received the answer, fill listItems, then call notifyDataSetChange() method of your adapter object.

Android Recycler View caching

I'm using volley to load data using JSON Parsing in to a recycler view. I've used recylcer view before, but somehow, the downloaded data is persistent this time, meaning its still there after the app is closed, maybe stays in cache. I'm not sure, what I'm doing wrong here. Any help is appreciated, thanks.
Edit: The application is storing downloaded data after the app is closed, which doesn't happen when using recycler view.
This is my Activity Class:
package com.example.recyclerview;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class PostActivity extends AppCompatActivity implements
OnItemClick{
private ArrayList<PostData> posts = new ArrayList<>();
private PostRecycleViewAdapter viewAdapter;
private String listingJsonUrl = "https://jsonplaceholder.typicode.com/posts/";
Toolbar toolbar;
private ProgressDialog progressDialog;
private RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
progressDialog = new ProgressDialog(this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(true);
final RecyclerView.LayoutManager viewLayoutManager = new LinearLayoutManager(getApplicationContext());
viewAdapter = new PostRecycleViewAdapter(posts);
final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(viewLayoutManager);
recyclerView.setAdapter(viewAdapter);
viewAdapter.setClickListener(this);
new DownloadData().execute(listingJsonUrl);
}
#Override
public void onClick(View view, int position) {
final PostData data = posts.get(position);
String title;
int id;
Intent commentIntent = new Intent(this, CommentsActivity.class);
id = data.getId();
title = data.getTitle();
if(title.length() > 25){
title = title.substring(0,25);
title = title.concat("..");
}
commentIntent.putExtra("title",title) ;
commentIntent.putExtra("id", id);
startActivity(commentIntent);
}
class DownloadData extends AsyncTask<String, String, String>{
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
#Override
protected String doInBackground(String... url) {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url[0], new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
JSONArray jsonArray = new JSONArray(response.toString());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
PostData postData = new PostData(jsonObject.getInt("id"),jsonObject.getString("title"), jsonObject.getString("body"));
posts.add(postData);
viewAdapter.notifyDataSetChanged();
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("JsonError", error.getMessage());
}
});
getRequestQueue().add(jsonArrayRequest);
return null;
}
}
public RequestQueue getRequestQueue()
{
if (requestQueue == null)
{
requestQueue = com.android.volley.toolbox.Volley.newRequestQueue(getApplicationContext());
}
return requestQueue;
}
}
This is my RecyclerView Adapter Class:
package com.example.recyclerview;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
public class PostRecycleViewAdapter extends RecyclerView.Adapter<PostRecycleViewAdapter.ViewHolder>
{
private List<PostData> postData;
private OnItemClick itemClick;
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView title, body;
public ViewHolder(View view){
super(view);
title = (TextView) view.findViewById(R.id.title);
body = (TextView) view.findViewById(R.id.body);
view.setTag(view);
view.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if(itemClick != null) itemClick.onClick(view, getAdapterPosition());
}
}
public PostRecycleViewAdapter(List<PostData> postData)
{
this.postData = postData;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemLayout = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_recycler_view,parent,false);
return new ViewHolder(itemLayout);
}
#Override
public void onBindViewHolder(PostRecycleViewAdapter.ViewHolder holder, int position) {
PostData data = postData.get(position);
holder.title.setText(data.getTitle());
holder.body.setText(data.getBody());
}
#Override
public int getItemCount() {
return postData.size();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);}
public void setClickListener(OnItemClick itemClick) {
this.itemClick = itemClick;
}
}
And this is the data item class:
package com.example.recyclerview;
public class PostData {
private String title, body;
private int id;
public PostData(int id, String title, String body)
{
this.id = id;
this.title = title;
this.body = body;
}
public String getTitle() {
return title;
}
public String getBody() {
return body;
}
public int getId() {
return id;
}
}

Categories

Resources