Problem while adding ArrayList in adapter - android

I am populating RecyclerView's adapter with ArrayList. List contain model object class which holds data from server. And it needs to be loaded into Tab Fragment.
I have tried everything I know about life cycle of a list and it seems that this list is deleted from memory at some point in that cycle.
Here is relevant part of code:
public class TrueFragment extends Fragment {
public static List<AllPositiveModel> newsList = new ArrayList<>();
private RecyclerView recyclerView;
private NewsAdapterTrue adapter;
private OnFragmentInteractionListener mListener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_true, container, false);
recyclerView = rootView.findViewById(R.id.recycler_view_true);
newsList = getResult();
adapter = new NewsAdapterTrue(newsList, getActivity());
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
return rootView;
}
public List<AllPositiveModel> getResult(){
final List<AllPositiveModel> items = new ArrayList<>();
GETAll getApiService;
getApiService = ApiUtils.getAPIServiceFetchAll();
getApiService.getAllNews().enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
if (response.isSuccessful()) {
if (response.body() != null) {
Log.i("onSuccess", response.body());
String jsonresponse = response.body();
try {
//getting the whole json object from the response
JSONObject obj = new JSONObject(response.body());
JSONArray dataArray = obj.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
String title, desc, link, date, img, paper;
final Integer id, positive, negative;
JSONObject dataobj = dataArray.getJSONObject(i);
AllPositiveModel item = new AllPositiveModel(dataobj.getInt("id"), dataobj.getString("title"),
dataobj.getString("description"), dataobj.getString("link"),
dataobj.getString("date"), dataobj.getString("image"),
dataobj.getInt("positive_votes"), dataobj.getInt("negative_votes"),
dataobj.getString("paper"));
id = dataobj.getInt("id");
title = dataobj.getString("title");
desc = dataobj.getString("description");
link = dataobj.getString("link");
date = dataobj.getString("date");
img = dataobj.getString("image");
positive = dataobj.getInt("positive_votes");
negative = dataobj.getInt("negative_votes");
paper = dataobj.getString("paper");
items.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.i("onEmptyResponse", "Returned empty response");
}
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
}
});
return items;
}
}
When I print in Log values of list inside of getResult() method, it works fine. But after it gets out from the method, list is empty.

You have already a list on Global level, no need to create a new list. i have updated your code try to run it and test hopefully it will work.
public class TrueFragment extends Fragment {
public static List<AllPositiveModel> newsList = new ArrayList<>();
private RecyclerView recyclerView;
private NewsAdapterTrue adapter;
private OnFragmentInteractionListener mListener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_true, container, false);
recyclerView = rootView.findViewById(R.id.recycler_view_true);
getResult();// Call this method
adapter = new NewsAdapterTrue(newsList, getActivity());
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
return rootView;
}
public void getResult(){
// final List<AllPositiveModel> items = new ArrayList<>(); no need for this as you have a list on global level
GETAll getApiService;
getApiService = ApiUtils.getAPIServiceFetchAll();
getApiService.getAllNews().enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
if (response.isSuccessful()) {
if (response.body() != null) {
Log.i("onSuccess", response.body());
String jsonresponse = response.body();
try {
//getting the whole json object from the response
JSONObject obj = new JSONObject(response.body());
JSONArray dataArray = obj.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
String title, desc, link, date, img, paper;
final Integer id, positive, negative;
JSONObject dataobj = dataArray.getJSONObject(i);
AllPositiveModel item = new AllPositiveModel(dataobj.getInt("id"), dataobj.getString("title"),
dataobj.getString("description"), dataobj.getString("link"),
dataobj.getString("date"), dataobj.getString("image"),
dataobj.getInt("positive_votes"), dataobj.getInt("negative_votes"),
dataobj.getString("paper"));
id = dataobj.getInt("id");
title = dataobj.getString("title");
desc = dataobj.getString("description");
link = dataobj.getString("link");
date = dataobj.getString("date");
img = dataobj.getString("image");
positive = dataobj.getInt("positive_votes");
negative = dataobj.getInt("negative_votes");
paper = dataobj.getString("paper");
newsList.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.i("onEmptyResponse", "Returned empty response");
}
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
}
});
// return items;
}
}

Try this.I modified the code.
public class TrueFragment extends Fragment {
public static List<AllPositiveModel> newsList; //changed here
private RecyclerView recyclerView;
private NewsAdapterTrue adapter;
private OnFragmentInteractionListener mListener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_true, container, false);
recyclerView = rootView.findViewById(R.id.recycler_view_true);
newsList = getResult(); //no changes here
adapter = new NewsAdapterTrue(newsList, getActivity());
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
return rootView;
}
public List<AllPositiveModel> getResult(){
final List<AllPositiveModel> items = new ArrayList<>();
GETAll getApiService;
getApiService = ApiUtils.getAPIServiceFetchAll();
getApiService.getAllNews().enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
if (response.isSuccessful()) {
if (response.body() != null) {
Log.i("onSuccess", response.body());
String jsonresponse = response.body();
try {
//getting the whole json object from the response
JSONObject obj = new JSONObject(response.body());
JSONArray dataArray = obj.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
String title, desc, link, date, img, paper;
final Integer id, positive, negative;
JSONObject dataobj = dataArray.getJSONObject(i);
AllPositiveModel item = new AllPositiveModel(dataobj.getInt("id"), dataobj.getString("title"),
dataobj.getString("description"), dataobj.getString("link"),
dataobj.getString("date"), dataobj.getString("image"),
dataobj.getInt("positive_votes"), dataobj.getInt("negative_votes"),
dataobj.getString("paper"));
id = dataobj.getInt("id");
title = dataobj.getString("title");
desc = dataobj.getString("description");
link = dataobj.getString("link");
date = dataobj.getString("date");
img = dataobj.getString("image");
positive = dataobj.getInt("positive_votes");
negative = dataobj.getInt("negative_votes");
paper = dataobj.getString("paper");
items.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.i("onEmptyResponse", "Returned empty response");
}
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
}
});
return items;
}
}

I have managed to solve the problem:
I have initialized adapter and recyclerview inside method getResult()
adapter = new NewsAdapterTrue(TrueNewsList, getActivity());
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
But I am still confused why my list is getting deleted from memory after it's being populated. I have almost same fragment and there is working just fine. I hope someone will answer me.

Related

populating recyclerview from API response

I want to connect my RecyclerView to my API response.. as too many depreciated code I had to make the two separately but I still can't figure out how to put them together I am putting the code if anyone would like to see it or having a problem with RecyclerView.. what I really want is giving me info or a thread or even a tutorial or how to combine both with the latest method as most of the codes online have problems, depreciated not detailed enough to show you the exact way to learn from it
code to connect to the database using httpUrlConnect
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle saveInstanceState) {
super.onCreate(saveInstanceState);
setContentView(R.layout.activity_main);
new GetMethodDemo().execute("http://YourIPAddress/android/search.php");
}
public class GetMethodDemo extends AsyncTask<String, Void, String> {
String server_response;
#Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
server_response = readStream(urlConnection.getInputStream());
Log.v("CatalogClient", server_response);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.e("Response", "" + server_response);
}
}
// Converting InputStream to String
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}
code for RecyclerView
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
List<ModelClass> modelClassList = new ArrayList<>();
modelClassList.add(new ModelClass(R.drawable.ic_launcher_background,"1","day use","cairo","ain shokhna","take a day use from cairo to ain sokhna asdoibasidoasbd asodasidou asidua sdiuas dgpasidu agspiudasdiuasidgasiodgasiudgasoidugasdoiuasgdoiusagdasoiudgsaiudgasiodgasidgasiudgasiudgasoiudgasoidgasoiudasgdoiausdgaouisgduiasg uisag aisoug asiug aosiugdasiudgsauio gasuio gsaiodgasiud gasiug aosi","11/4/2019","20/4/2019","1000EGP"));
modelClassList.add(new ModelClass(R.drawable.ic_launcher_background,"2","day use","cairo","ain shokhna","take a day use from cairo to ain sokhna","11/4/2019","20/4/2019","1000EGP"));
modelClassList.add(new ModelClass(R.drawable.ic_launcher_background,"3","day use","cairo","ain shokhna","take a day use from cairo to ain sokhna","11/4/2019","20/4/2019","1000EGP"));
modelClassList.add(new ModelClass(R.drawable.ic_launcher_background,"4","day use","cairo","ain shokhna","take a day use from cairo to ain sokhna","11/4/2019","20/4/2019","1000EGP"));
modelClassList.add(new ModelClass(R.drawable.ic_launcher_background,"5","day use","cairo","ain shokhna","take a day use from cairo to ain sokhna","11/4/2019","20/4/2019","1000EGP"));
modelClassList.add(new ModelClass(R.drawable.ic_launcher_background,"6","day use","cairo","ain shokhna","take a day use from cairo to ain sokhna","11/4/2019","20/4/2019","1000EGP"));
modelClassList.add(new ModelClass(R.drawable.ic_launcher_background,"7","day use","cairo","ain shokhna","take a day use from cairo to ain sokhna","11/4/2019","20/4/2019","1000EGP"));
modelClassList.add(new ModelClass(R.drawable.ic_launcher_background,"8","day use","cairo","ain shokhna","take a day use from cairo to ain sokhna","11/4/2019","20/4/2019","1000EGP"));
modelClassList.add(new ModelClass(R.drawable.ic_launcher_background,"9","day use","cairo","ain shokhna","take a day use from cairo to ain sokhna","11/4/2019","20/4/2019","1000EGP"));
modelClassList.add(new ModelClass(R.drawable.ic_launcher_background,"10","day use","cairo","ain shokhna","take a day use from cairo to ain sokhna","11/4/2019","20/4/2019","1000EGP"));
modelClassList.add(new ModelClass(R.drawable.ic_launcher_background,"11","day use","cairo","ain shokhna","take a day use from cairo to ain sokhna","11/4/2019","20/4/2019","1000EGP"));
Adapter adapter = new Adapter(modelClassList);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
code for adapter
public class Adapter extends RecyclerView.Adapter<Adapter.Viewholder> {
private List<ModelClass> modelClassList;
public Adapter(List<ModelClass> modelClassList) {
this.modelClassList = modelClassList;
}
#NonNull
#Override
public Viewholder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_layout,viewGroup,false);
return new Viewholder(view);
}
#Override
public void onBindViewHolder(#NonNull Viewholder viewholder, int position) {
int resource = modelClassList.get(position).getImageResource();
String search_id = modelClassList.get(position).getSearch_id();
String activity = modelClassList.get(position).getActivity();
String origin = modelClassList.get(position).getOrigin();
String destination = modelClassList.get(position).getDestination();
String description = modelClassList.get(position).getDescription();
String date_from = modelClassList.get(position).getDate_from();
String date_to = modelClassList.get(position).getDate_to();
String price = modelClassList.get(position).getPrice();
viewholder.setData( resource, search_id,activity,origin,destination,description,date_from,date_to,price);
}
#Override
public int getItemCount() {
return modelClassList.size();
}
public class Viewholder extends RecyclerView.ViewHolder{
private ImageView imageView;
private TextView search;
private TextView mactivity;
private TextView morigin;
private TextView mdestination;
private TextView mdescription;
private TextView mdate_from;
private TextView mdate_to;
private TextView mprice;
public Viewholder(#NonNull View itemView) {
super(itemView);
imageView =itemView.findViewById(R.id.image_view);
search= itemView.findViewById(R.id.search_id);
mactivity= itemView.findViewById(R.id.activity);
morigin= itemView.findViewById(R.id.origin);
mdestination= itemView.findViewById(R.id.destination);
mdescription= itemView.findViewById(R.id.description);
mdate_from= itemView.findViewById(R.id.date_from);
mdate_to= itemView.findViewById(R.id.date_to);
mprice =itemView.findViewById(R.id.price);
}
private void setData(int resource, String search_id,String activity,String origin,String destination,String description,String date_from,String date_to,String price){
imageView.setImageResource(resource);
search.setText(search_id);
mactivity.setText(activity);
morigin.setText(origin);
mdestination.setText(destination);
mdescription.setText(description);
mdate_from.setText(date_from);
mdate_to.setText(date_to);
mprice.setText(price);
}
}
}
volley code doesn't work
public class redirectFragment extends Fragment {
private static final String URL_PRODUCTS = "http://ipAddress/android/search.php";
private RecyclerView recyclerView;
private List<ModelClass> modelClassList;
public redirectFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_redirect, container, false);
recyclerView = v.findViewById(R.id.recyclerView);
LinearLayoutManager layoutManager = new LinearLayoutManager(this.getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
List<ModelClass> modelClassList = new ArrayList<>();
loadModelClass();
Adapter adapter = new Adapter(modelClassList);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
return v ;
}
private void loadModelClass() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_PRODUCTS,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONArray array = new JSONArray(response);
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
//getting product object from json array
JSONObject product = array.getJSONObject(i);
//adding the product to product list
modelClassList.add(new ModelClass(
product.getInt("activity_img"),
product.getString("search_id"),
product.getString("activity"),
product.getString("description"),
product.getString("origin"),
product.getString("destination"),
product.getString("date_from"),
product.getString("date_to"),
product.getString("price")
));
}
//creating adapter object and setting it to RecyclerView
Adapter adapter = new Adapter(modelClassList);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this.getActivity()).add(stringRequest);
}
}
code for retrofit and still doesnt work
private Adapter adapter;
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*Create handle for the RetrofitInstance interface*/
RetrofitInstance.GetEmployeeDataService service = RetrofitInstance.getRetrofitInstance().create(RetrofitInstance.GetEmployeeDataService.class);
/*Call the method with parameter in the interface to get the employee data*/
Call<SearchList> call = service.getSearchData(100);
/*Log the URL called*/
Log.wtf("URL Called", call.request().url() + "");
call.enqueue(new Callback<SearchList>() {
#Override
public void onResponse(Call<SearchList> call, Response<SearchList> response) {
generateEmployeeList(response.body().getSearchArrayList());
}
#Override
public void onFailure(Call<SearchList> call, Throwable t) {
Toast.makeText(MainActivity.this, "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();
}
});
}
/*Method to generate List of employees using RecyclerView with custom adapter*/
private void generateEmployeeList(ArrayList<search> modelClassList) {
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
adapter = new Adapter(modelClassList);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
I tried both codes and they work perfectly for the RecyclerView and for HTTPURLCONNECTION .. I hope someone helps me with the issue of combining the two of them
I tried volley but results in the comeback as null so someone suggested that I have to work with HTTPURLCONNECTION and since then I don't know how to combine the two together. I will add the volley I used to work with
Try this #diaa,
public class redirectFragment extends Fragment {
private static final String URL_PRODUCTS =
"http://IPADDRESS/android/search.php";
private RecyclerView recyclerView;
List<ModelClass> modelClassList;
private RecyclerView.Adapter adapter; //new line
public redirectFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_redirect, container, false);
//getting the recyclerview from xml
recyclerView = v.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getContext()));
//initializing the productlist
List<ModelClass> modelClassList = new ArrayList<>();
adapter = new Adapter(modelClassList); //new line
recyclerView.setAdapter(adapter); //new line
//this method will fetch and parse json
//to display it in recyclerview
loadModelClass();
return v;
}
private void loadModelClass() {
StringRequest stringRequest = new StringRequest(Request.Method.GET,
URL_PRODUCTS,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONArray array = new JSONArray(response);
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
//getting product object from json array
JSONObject product = array.getJSONObject(i);
int search_id = product.getInt("search_id");
String activity = product.getString("activity");
String descp = product.getString("description");
String image = product.getString("activity_img");
String origin = product.getString("origin");
String destination =
product.getString("destination");
String date_from = product.getString("date_from");
String date_to = product.getString("date_to");
String price = product.getString("price");
ModelClass list = new ModelClass(search_id,
activity,
descp,image,
origin, destination, date_from, date_to,
price);
modelClassList.add(list);
}
adapter = new Adapter(list); //new line
recyclerView.setAdapter(adapter); //new line
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this.getActivity()).add(stringRequest);
}

Unable to get the JSON response on RecyclerView

I want to get the JSON response onto a RecyclerView. Though I am getting the correct response through the REST API I have used , but the response is not coming on the RecyclerView after parsing. Below is the code. Please help !!
RepoActivity.java
public class RepoActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private List<RepoList> repoList = new ArrayList<>();
String data = "";
private RecyclerView recyclerView;
private static String url;
private RepoAdapter adapter;
RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_repo);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Bundle bundle = getIntent().getExtras();
String message = bundle.getString("message");
adapter = new RepoAdapter(repoList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
url = "https://api.github.com/users/" + message + "/repos";
parsingMethod();
}
private void parsingMethod() {
Log.d("hello1", url);
pDialog = new ProgressDialog(this);
// Showing progress dialog
pDialog.setMessage("Loading...");
pDialog.show();
// Creating volley request obj
JsonArrayRequest cityReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
hidePDialog();
// Parsing json
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = null;
try {
obj = jsonArray.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
RepoList repoList = new RepoList();
try {
repoList.setRepoName(obj.getString("name"));
Log.d("zxcv",obj.getString("name") );
repoList.setRepoDesc(obj.getString("description"));
Log.d("zxcv",obj.getString("description") );
} catch (JSONException e) {
e.printStackTrace();
}
}
recyclerView.setAdapter(adapter);
}
},new Response.ErrorListener()
{
#Override
public void onErrorResponse (VolleyError error){
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(cityReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
RepoAdapter.java
public class RepoAdapter extends RecyclerView.Adapter<RepoAdapter.MyViewHolder> {
private List<RepoList> repoLists;
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.repo_list_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
RepoList repoList = repoLists.get(position);
holder.repoName.setText(repoList.getRepoName());
holder.repoDesc.setText(repoList.getRepoDesc());
}
#Override
public int getItemCount() {
return repoLists.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView repoName, repoDesc;
public MyViewHolder(View view) {
super(view);
repoName = (TextView) view.findViewById(R.id.repoName);
repoDesc = (TextView) view.findViewById(R.id.repoDesc);
}
}
public RepoAdapter( List<RepoList> repoList) {
this.repoLists = repoList;
}
}
RepoList.java
package com.example.lenovo.boxme;
/**
* Created by lenovo on 16-12-2016.
*/
public class RepoList {
private String repoName,repoDesc;
public RepoList(String repoDesc, String repoName) {
this.repoDesc = repoDesc;
this.repoName = repoName;
}
public RepoList(){};
public String getRepoDesc() {
return repoDesc;
}
public void setRepoDesc(String repoDesc) {
this.repoDesc = repoDesc;
}
public String getRepoName() {
return repoName;
}
public void setRepoName(String repoName) {
this.repoName = repoName;
}
}
adapter = new RepoAdapter(repoList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
//notify data set after list item changed
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = null;
try {
obj = jsonArray.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
RepoList repo= new RepoList();
try {
repo.setRepoName(obj.getString("name"));
Log.d("zxcv",obj.getString("name") );
repo.setRepoDesc(obj.getString("description"));
Log.d("zxcv",obj.getString("description") );
repoList.add(repo);//you missed
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChange();
you're passing in repoList when creating adapter
adapter = new RepoAdapter(repoList);
but are then creating/populating new list before calling setAdapter
RepoList repoList = new RepoList();
...
recyclerView.setAdapter(adapter);
Remove this line :
RepoList repoList = new RepoList();
Put this line in onCreate
recyclerView.setAdapter(adapter);
And after fetching the data call :
adapter.notifyDataSetChange()

Recycler view not rendering the data list

I'm trying to implement a recycler view in fragment using Volley library.
Data is loaded and logged successfully from the server but not displayed at all in the recycler fragment.
The request fetches the data and logs it but nothing renders in the fragment. There are no XML errors.
HitVideoFragment.java
public class HitVideoFragment extends Fragment {
private RecyclerView recyclerView;
private HitVideoAdapter adapter;
private List<HitVideo> hitVideoList = new ArrayList<HitVideo>();
public HitVideoFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_hit_video, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
//Initializing Views
recyclerView = (RecyclerView) this.getActivity().findViewById(R.id.hitvideo_recycler_view);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this.getActivity());
recyclerView.setHasFixedSize(false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
adapter = new HitVideoAdapter(hitVideoList);
recyclerView.setAdapter(adapter);
//Calling method to get data
//Showing a progress dialog
final ProgressDialog loading = ProgressDialog.show(this.getActivity(),"Loading Data", "Please wait...",false,false);
//Creating a json array request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(AppConfig.URL_HIT_VIDEOS,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Dismissing progress dialog
loading.dismiss();
Log.d("Some tag", "onResponse: "+response.toString());
hitVideoList = new ArrayList<HitVideo>();
for(int i = 0; i<response.length(); i++) {
HitVideo hitVideo = new HitVideo();
JSONObject json = null;
try {
json = response.getJSONObject(i);
hitVideo.setTitle(json.getString("name"));
hitVideo.setUrl(json.getString("url"));
hitVideo.setUsername(json.getString("user_id"));
hitVideo.setHits(json.getInt("hits"));
} catch (JSONException e) {
e.printStackTrace();
}
hitVideoList.add(hitVideo);
}
adapter.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Hit Video", "Error: " + error.getMessage());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
Context _context = getActivity().getApplicationContext();
SharedPreferences pref;
String token;
if (_context != null) {
pref = _context.getSharedPreferences(Config.PREF_NAME, Config.PRIVATE_MODE);
if (pref != null) {
token = pref.getString(Config.USER_TOKEN, null);
headers.put("Authorization", "Bearer " + token);
}
}
return headers;
}
};
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this.getActivity());
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
This is not throwing any exceptions. And the model and adapters are doing their job fine. Thanks in advance.
I am probably too late to this,
But I had the same issue and I fixed it by returning the list.size() on the getItemCout() method in the Adapter class.

Set notifyDataSetChanged() on Recyclerview adapter

I'm implementing an endless data loading for a RecyclerView. When software detects that last item is going to be shown, it downloads new items and call to the loadMoreData() function but new dataset is not showing.
When I called notifyDataSetChanged() so nothing to be happened.
I have only one solution that is refresh the view is to set again the adapter but problem is that the recyclerview returns to the first position then again recyclerview scrolled up from the first position to last position.
RecyclerViewActivity.java
RecyclerView rv;
DatabaseHelpr databaseHelpr;
RVAdapter adapter;
LocationFinder locationfinder;
Location currentLocation;
ArrayList<ServiceModel> childList, list;
private int MainService_ID, city_id;
String url2;
ActionBar actionBar;
JSONArray items = null;
Utility utility;
Double lat, longi;
LinearLayoutManager llm;
int counter=0;
ProgressBar progressBar;
private static final String TAG_ITEMS = "items";
private static final String TAG_LOCALITY = "Locality";
private static final String TAG_BUSINESS_ID = "Business_Id";
private static final String TAG_LONGITUDE = "Longitude";
private static final String TAG_BUSINESS_NAME = "Business_Name";
private static final String TAG_LATITUDE = "Latitude";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recyclerview_activity);
list = new ArrayList<>();
utility = new Utility(this);
llm = new LinearLayoutManager(this);
Bundle bundle=getIntent().getExtras();
MainService_ID=bundle.getInt("service_id");
String mainService_Name = bundle.getString("service_name");
city_id = bundle.getInt("city_id");
lat= bundle.getDouble("lat");
longi=bundle.getDouble("longi");
rv=(RecyclerView)findViewById(R.id.rv);
rv.setLayoutManager(llm);
actionBar = getSupportActionBar();
assert actionBar != null;
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle(mainService_Name);
//Here city_id = 8, lat = 18.552954, longi = 73.897200, counter=0, MainService_ID = 5
String url="https://servicedata2-dot-indiacomapi.appspot.com/_ah/api/servicedata/v1/ServiceData?city_id=";
url2 =url+city_id+"&lat="+lat+"&lng="+longi+"&roll="+counter+"&service_id="+MainService_ID;
AsyncHttpClient client = new AsyncHttpClient();
progressBar=(ProgressBar) findViewById(R.id.progressBar1);
progressBar.setVisibility(View.VISIBLE);
client.get(url2, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// called when response HTTP status is "200 OK"
String s = new String(response);
try {
JSONObject jsonObj = new JSONObject(s);
// Getting JSON Array node
items = jsonObj.getJSONArray(TAG_ITEMS);
// looping through All Contacts
for (int i = 0; i < items.length(); i++) {
JSONObject c = items.getJSONObject(i);
String locality = c.getString(TAG_LOCALITY);
String business_Id = c.getString(TAG_BUSINESS_ID);
String longitude = c.getString(TAG_LONGITUDE);
String latitude = c.getString(TAG_LATITUDE);
String business_Name = c.getString(TAG_BUSINESS_NAME);
locationfinder = new LocationFinder(RecyclerViewActivity.this);
// check if GPS enabled
if (locationfinder.canGetLocation()) {
double lat = locationfinder.getLatitude();
double longi = locationfinder.getLongitude();
currentLocation = new Location("");
currentLocation.setLatitude(lat);
currentLocation.setLongitude(longi);
} else {
locationfinder.showSettingsAlert();
}
Location savedLocation = new Location("databaseLocation");
savedLocation.setLatitude(Double.parseDouble(latitude));
savedLocation.setLongitude(Double.parseDouble(longitude));
Double difference = currentLocation.distanceTo(savedLocation) * (0.001);
difference = Double.parseDouble(new DecimalFormat("##.##").format(difference));
String newDifference = String.valueOf(difference) + " km";
ServiceModel serviceModel = new ServiceModel(business_Id, business_Name, newDifference, locality);
list.add(serviceModel);
}
} catch (JSONException e) {
e.printStackTrace();
}
progressBar.setVisibility(View.GONE);
adapter = new RVAdapter(RecyclerViewActivity.this, list);
rv.setAdapter(adapter);
rv.addOnScrollListener(new EndlessRecyclerOnScrollListener(llm) {
#Override
public void onLoadMore(int current_page) {
// counter= counter+1;
loadMoreData();
}
});
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
//Toast.makeText(getApplicationContext(),""+statusCode,Toast.LENGTH_LONG).show();
}
});
}
private void loadMoreData() {
counter= counter+1;
//Here city_id = 8, lat = 18.552954, longi = 73.897200, counter=1, MainService_ID = 5
String url="https://servicedata2-dot-indiacomapi.appspot.com/_ah/api/servicedata/v1/ServiceData?city_id=";
url2 =url+city_id+"&lat="+lat+"&lng="+longi+"&roll="+counter+"&service_id="+MainService_ID;
AsyncHttpClient client = new AsyncHttpClient();
progressBar=(ProgressBar) findViewById(R.id.progressBar1);
progressBar.setVisibility(View.VISIBLE);
client.get(url2, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// called when response HTTP status is "200 OK"
String s = new String(response);
try {
JSONObject jsonObj = new JSONObject(s);
// Getting JSON Array node
items = jsonObj.getJSONArray(TAG_ITEMS);
// looping through All Contacts
for (int i = 0; i < items.length(); i++) {
JSONObject c = items.getJSONObject(i);
String locality = c.getString(TAG_LOCALITY);
String business_Id = c.getString(TAG_BUSINESS_ID);
String longitude = c.getString(TAG_LONGITUDE);
String latitude = c.getString(TAG_LATITUDE);
String business_Name = c.getString(TAG_BUSINESS_NAME);
locationfinder = new LocationFinder(RecyclerViewActivity.this);
// check if GPS enabled
if (locationfinder.canGetLocation()) {
double lat = locationfinder.getLatitude();
double longi = locationfinder.getLongitude();
currentLocation = new Location("");
currentLocation.setLatitude(lat);
currentLocation.setLongitude(longi);
} else {
locationfinder.showSettingsAlert();
}
Location savedLocation = new Location("databaseLocation");
savedLocation.setLatitude(Double.parseDouble(latitude));
savedLocation.setLongitude(Double.parseDouble(longitude));
Double difference = currentLocation.distanceTo(savedLocation) * (0.001);
difference = Double.parseDouble(new DecimalFormat("##.##").format(difference));
String newDifference = String.valueOf(difference) + " km";
ServiceModel serviceModel = new ServiceModel(business_Id, business_Name, newDifference, locality);
list.add(serviceModel);
}
} catch (JSONException e) {
e.printStackTrace();
}
progressBar.setVisibility(View.GONE);
//adapter = new RVAdapter(RecyclerViewActivity.this, list);
//rv.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
}
});
Toast.makeText(this, "Net is present", Toast.LENGTH_SHORT).show();
}
}
RVAdapter.java
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.PersonViewHolder>{
private final LayoutInflater mInflater;
List<ServiceModel> persons ;
private Context mContext;
public RVAdapter(Context context,List<ServiceModel> persons){
this.mInflater = LayoutInflater.from(context);
this.persons = new ArrayList<>(persons);
this.mContext = context;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public PersonViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item, viewGroup, false);
PersonViewHolder pvh = new PersonViewHolder(v);
return pvh;
}
#Override
public void onBindViewHolder(PersonViewHolder personViewHolder, int i) {
ServiceModel person = persons.get(i);
personViewHolder.businessName.setOnClickListener(clickListener);
personViewHolder.image_url.setOnClickListener(clickListenerImage);
personViewHolder.businessName.setTag(personViewHolder);
personViewHolder.difference.setTag(personViewHolder);
personViewHolder.business_id.setTag(personViewHolder);
personViewHolder.image_url.setTag(personViewHolder);
personViewHolder.locality.setTag(personViewHolder);
personViewHolder.businessName.setText(Html.fromHtml(person.getBusinessname()));
String firstLetter = String.valueOf(person.getBusinessname().charAt(0));
ColorGenerators generator = ColorGenerators.MATERIAL; // or use DEFAULT
int color = generator.getColor(person.getBusinessname());
TextDrawable drawable = TextDrawable.builder().buildRound(firstLetter, color); // radius in px
personViewHolder.image_url.setImageDrawable(drawable);
personViewHolder.difference.setText(Html.fromHtml(person.getNewDiffer()));
personViewHolder.locality.setText(Html.fromHtml(person.getLocality()));
personViewHolder.bind(person);
}
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
PersonViewHolder holder = (PersonViewHolder) view.getTag();
int position = holder.getPosition();
ServiceModel person = persons.get(position);
String businessids = person.getBusinessid();
Intent intent = new Intent(mContext, BusinessInfoActivity.class);
intent.putExtra("businessids", businessids);
mContext.startActivity(intent);
}
};
View.OnClickListener clickListenerImage = new View.OnClickListener() {
#Override
public void onClick(View view) {
PersonViewHolder holder = (PersonViewHolder) view.getTag();
int position = holder.getPosition();
ServiceModel person = persons.get(position);
String businessids = person.getBusinessid();
Intent intent = new Intent(mContext, BusinessInfoActivity.class);
intent.putExtra("businessids", businessids);
mContext.startActivity(intent);
}
};
#Override
public int getItemCount() {
return persons.size();
}
public void animateTo(List<ServiceModel> models) {
applyAndAnimateRemovals(models);
applyAndAnimateAdditions(models);
applyAndAnimateMovedItems(models);
}
private void applyAndAnimateRemovals(List<ServiceModel> newModels) {
for (int i = persons.size() - 1; i >= 0; i--) {
final ServiceModel model = persons.get(i);
if (!newModels.contains(model)) {
removeItem(i);
}
}
}
private void applyAndAnimateAdditions(List<ServiceModel> newModels) {
for (int i = 0, count = newModels.size(); i < count; i++) {
final ServiceModel model = newModels.get(i);
if (!persons.contains(model)) {
addItem(i, model);
}
}
}
private void applyAndAnimateMovedItems(List<ServiceModel> newModels) {
for (int toPosition = newModels.size() - 1; toPosition >= 0; toPosition--) {
final ServiceModel model = newModels.get(toPosition);
final int fromPosition = persons.indexOf(model);
if (fromPosition >= 0 && fromPosition != toPosition) {
moveItem(fromPosition, toPosition);
}
}
}
public ServiceModel removeItem(int position) {
final ServiceModel model = persons.remove(position);
notifyItemRemoved(position);
return model;
}
public void addItem(int position, ServiceModel model) {
persons.add(position, model);
notifyItemInserted(position);
}
public void moveItem(int fromPosition, int toPosition) {
final ServiceModel model = persons.remove(fromPosition);
persons.add(toPosition, model);
notifyItemMoved(fromPosition, toPosition);
}
public static class PersonViewHolder extends RecyclerView.ViewHolder {
protected CardView cv;
protected TextView businessName, difference, business_id, locality;
protected ImageView image_url;
public PersonViewHolder(View itemView) {
super(itemView);
cv = (CardView)itemView.findViewById(R.id.cv);
businessName = (TextView)itemView.findViewById(R.id.business_name);
difference = (TextView)itemView.findViewById(R.id.txtDifferenece);
business_id = (TextView)itemView.findViewById(R.id.business_id);
image_url = (ImageView)itemView.findViewById(R.id.thumbnail);
locality= (TextView)itemView.findViewById(R.id.txtLocality);
}
public void bind(ServiceModel model) {
businessName.setText(model.getBusinessname());
}
}
}
Please help me, How to set notifyDataSetChanged() to the adapter. it is not working in my code. I already checked all answers which is posted on the stackoverflow.
you are setting the new list to the RecyclerView Adapter , set the list in the Adapter:
make a method setItems(list) in adapter and call it before notifyDataSetChanged() and in adapter do
this.persons = new ArrayList<>(persons);
in setItems
add this method in adapter:
public void setItems(List<ServiceModel> persons) {
this.persons = persons;
}
and call it before notifyDataSetChanged() like this:
adapter.setItems(list);
adapter.notifyDataSetChanged();
Issue is in these lines..
adapter = new RVAdapter(RecyclerViewActivity.this, list);
rv.setAdapter(adapter);
adapter.notifyDataSetChanged();
You are initialising your adapter every time. No need to reinitialize it.
Just update your arraylist and invoking to adapter.notifyDataSetChanged(); will make it work.
Like #Beena mentioned, you are creating and setting new adapter ever time, in your success response.
One approach would be to create an adapter and set it to the recycler view only for the first time, and then onSuceess() of your api callback, call a method of your adapter.
In, them adapter method, just add that new data in your main arraylist and do notifyItemInserted() instead of notifyDataSetChanged, in this way you will also see the default adding animation of recyclerView.
Every time you fill your list call the method below:
if (adapter != null) // it works second time and later
adapter.notifyDataSetChanged();
else { // it works first time
adapter = new AdapterClass(context,list);
listView.setAdapter(adapter);
}
I solved this with added method in RVAdapter that call notifyDataSetChanged().
Simply in RVAdapter:
public void refreshList(){
notifyDataSetChanged();
}
and call this method in MainActivity when need:
rVAdapter.refreshList();

Pass position of the item of recycler view to open up a new acitivity

How can i pass the position of item using intent to start a new activity?
I want to start a new activity called single which displays the rating of the movie correspondingly..pls help
I have been trying this for the past two days.
Here is the code:
public class NowPlaying extends Fragment {
private static final String TAG = NowPlaying.class.getSimpleName();
// Movies json url
private static final String url = "http://private-8149-themoviedb.apiary-mock.com/3/movie/now_playing?api_key=";
private ProgressDialog pDialog;
private List<NowPlayingInfo> bottom = new ArrayList<NowPlayingInfo>() ;
NowPlayingAdapter adapter;
RecyclerView recyclerView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_main, container, false);
ActionBar toolbar = ((AppCompatActivity) getActivity()).getSupportActionBar();
toolbar.setTitle("Now playing");
recyclerView = (RecyclerView) v.findViewById(R.id.cardList);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(linearLayoutManager);
adapter = new NowPlayingAdapter(getActivity(), bottom);
recyclerView.setAdapter(adapter);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.show();
adapter.SetOnItemClickListener(new NowPlayingAdapter.OnItemClickListener() {
#Override
public void onItemClick(View v, int position) {
// do something with position
Intent i = new Intent(v.getContext(), Single.class);
//pass the position of the item to single class
v.getContext().startActivity(i);
}
});
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
hidePDialog();
try {
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
NowPlayingInfo trailer = new NowPlayingInfo();
trailer.setTitle(jsonObject.getString("original_title"));
String iss = "http://image.tmdb.org/t/p/w500" + jsonObject.getString("poster_path") ;
trailer.setImage(iss);
bottom.add(trailer);
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
return v;
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
adapter.SetOnItemClickListener(new NowPlayingAdapter.OnItemClickListener() {
#Override
public void onItemClick(View v, int position) {
NowPlayingInfo _nowPlaying = bottom.get(position);
// do something with position
Intent i = new Intent(v.getContext(), Single.class);
//pass the position of the item to single class
i.putExtra("ISS", _nowPlaying.getImage()); //you can put your current playing info.
i.putExtra("POSITION", position); //you can put your position to next activity.
v.getContext().startActivity(i);
}
});
Add this in your SingleInfo Class.
String _rating = "";
public String get_rating() {
return _rating;
}
public void set_rating(String _rating) {
this._rating = _rating;
}
Add this in your Single class -
int _currentPos = 0 ; //Global variable .
_currentPos = getIntent().getIntExtra("position", 0);// paste this in onCreate()
Add this code in onResponse of Single Class -
try {
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
SingleInfo s = new SingleInfo();
s.set_rating(jsonObject.getString("rating"));
single.add(s);
}
//changed by Shoeb
SingleInfo _singleInfo = single.get(_currentPos); //position from previous activity
textView.setText(_singleInfo.get_rating());
//end changes
} catch (JSONException e) {
e.printStackTrace();
}
Add an extra to your intent
i.putExtra("position",position);
And on the other activity:
getIntent().getIntExtra("position", 0);

Categories

Resources