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()
Related
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.
Recycle view load list and reached at top by mList.add(0,actor) but i want to reverse the list.
also i chnaged my code like this,
mLayoutManager.setReverseLayout(true);
mList.add(0,actor);
Here is my recycleview info, This is my recyclview api code InfoJson() here:
public class GatekeeperInfoActivity extends BaseActivity implements View.OnClickListener , MyComplaintListner {
private RecyclerView mRecyclerView;
private GateInfoAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private List<GateInfoPojo> mList;
Context ctx;
String visitor_id,id,cid;
M_Shared_Pref m_shared_pref;
ImageView back_button, img;
private MyDialog dialog;
TextView complaint,subject,msg,from_name_txt;
ImageView attach;
String from_id,from_name,from_mobile;
String id_rwa,new_id;
public static final int DISMISS_TIMEOUT = 2000;
LinearLayout ll_no_data;
int limit =0;
int limit_refresh;
static int nums;
private appconfig.EndlessRecyclerOnScrollListener scrollListener;
LinearLayoutManager linearLayoutManager;
public int overallXScrol = 0;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rwa_view_info);
ctx = GatekeeperInfoActivity.this;
dialog = new MyDialog(this);
m_shared_pref = new M_Shared_Pref(GatekeeperInfoActivity.this);
visitor_id = m_shared_pref.getPrefranceStringValue(App_Info.Visitor_ID);
id = m_shared_pref.getPrefranceStringValue(App_Info.Flat_User_Id);
cid = m_shared_pref.getPrefranceStringValue(App_Info.Flat_User_Id_cid);
Bundle bundle = this.getIntent().getExtras();
from_id = bundle.getString("id");
from_name = bundle.getString("name");
from_mobile = bundle.getString("mobile");
id_rwa = getIntent().getStringExtra("id_rwa");
if (from_id != null && !from_id.isEmpty() && !from_id.equals("null"))
{ new_id = from_id; }
else{ new_id = id_rwa; }
System.out.println("check:check"+from_id+":"+id_rwa);
///// using this new_id
mList = new ArrayList<GateInfoPojo>();
mRecyclerView = findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new GateInfoAdapter(mList, ctx);
ll_no_data = findViewById(R.id.ll_no_data);
mAdapter.setMyClickListener(this);
/* button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
limit_refresh = nums+limit;
limit = limit_refresh;
if(nums>=20){
// item_progress_bar.setVisibility(View.VISIBLE);
InfoJson();
}
}
});*/
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (!recyclerView.canScrollVertically(-1)) {
// Toast.makeText(GatekeeperInfoActivity.this, "Last", Toast.LENGTH_LONG).show();
limit_refresh = nums+limit;
limit = limit_refresh;
if(nums>=20){
// item_progress_bar.setVisibility(View.VISIBLE);
InfoJson();
}
}
}
});
img = findViewById(R.id.pic);
from_name_txt = findViewById(R.id.from_name_txt);
attach = findViewById(R.id.attach);
msg = findViewById(R.id.msg);
complaint = findViewById(R.id.complaint);
subject = findViewById(R.id.subject);
back_button = findViewById(R.id.back_button);
back_button.setOnClickListener(this);
attach.setOnClickListener(this);
if(NetWorkCheck.checkConnection(GatekeeperInfoActivity.this)){
mList.clear();
InfoJson();
}
else{
TastyToast.makeText(getApplicationContext(), "Internet connection is disable", TastyToast.LENGTH_LONG, TastyToast.WARNING);
}
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.back_button:
finish();
break;
case R.id.attach:
if(msg.getText().toString().length()>0){
submitReply(msg.getText().toString(),new_id);
}
else{
TastyToast.makeText(getApplicationContext(), "Enter Message", TastyToast.LENGTH_LONG, TastyToast.INFO);
}
break;
}
}
public void InfoJson() {
dialog.ShowProgressDialog();
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.Base_Url+"AllChatWithUser.php?", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
dialog.CancelProgressDialog();
JSONObject obj = new JSONObject(response);
String error = obj.getString("error");
nums = obj.getInt("nums");
System.out.println("limit_limit_num"+nums);
if(nums>=1) {
if (error.equals("true")) {
from_name_txt.setText("GateKeeper : " + obj.getString("names"));
JSONArray tower = obj.getJSONArray("Flat");
for (int i = 0; i < tower.length(); i++) {
JSONObject jsonnew = tower.getJSONObject(i);
GateInfoPojo actor = new GateInfoPojo();
String id = jsonnew.getString("id");
String Reply_From = jsonnew.getString("reply_from");
String message = jsonnew.getString("message");
String reply_date = jsonnew.getString("send_time");
String usertype = jsonnew.getString("usertype");
actor.setId(id);
actor.setReply_from(Reply_From);
actor.setMessage(message);
actor.setSend_time(reply_date);
actor.setUsertype(usertype);
if(limit==0){
mList.add(actor);
}
else{
mList.add(0,actor);
}
mAdapter.notifyDataSetChanged();
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.getLayoutManager().scrollToPosition(nums - 1);
}
}
}
else
{
mRecyclerView.setVisibility(View.GONE);
ll_no_data.setVisibility(View.VISIBLE);
// TastyToast.makeText(getApplicationContext(), obj.getString("msg"), TastyToast.LENGTH_LONG, TastyToast.ERROR);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
dialog.CancelProgressDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("empid", new_id);
params.put("fid", id);
params.put("usertype", "FlatUser");
params.put("limit", String.valueOf(limit));
Log.e("params", String.valueOf(params));
return params;
}
};
requestQueue.add(stringRequest);
}
#Override
public void onItemClick(View v, Object bean, String feed, String rating,String comp_spinner) {
String complaint_id = ((GateInfoPojo) bean).getId();
// submitComplaintInfo(complaint_id,feed,rating,comp_spinner);
}
#Override
public void onItemClickActivity(View v, Object bean) {
String complaint_id = ((GateInfoPojo) bean).getId();
}
public void submitReply(final String msg1,final String new_id) {
dialog.ShowProgressDialog();
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.Base_Url+"ChatWithUser.php?", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
dialog.CancelProgressDialog();
JSONObject obj = new JSONObject(response);
String error = obj.getString("error");
if (error.equals("true"))
{
// TastyToast.makeText(getApplicationContext(), obj.getString("msg"), TastyToast.LENGTH_LONG, TastyToast.SUCCESS);
msg.setText("");
InfoJson();
mList.clear();
}
else
{
TastyToast.makeText(getApplicationContext(), obj.getString("msg"), TastyToast.LENGTH_LONG, TastyToast.ERROR);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
dialog.CancelProgressDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("fid", id);
params.put("empid", new_id);
params.put("usertype", "FlatUser");
params.put("message", msg1);
Log.e("params", String.valueOf(params));
return params;
}
};
requestQueue.add(stringRequest);
}
}
But this is not working its add to top but not reverse the api data bottom to top.
Any help would be appreciated.
You can reverse the array list by -
Collections.reverse(mList);
After that setAdapter() or notifyDataSetChanged() according to your requirement.
public void InfoJson() {
dialog.ShowProgressDialog();
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.Base_Url+"AllChatWithUser.php?", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
dialog.CancelProgressDialog();
JSONObject obj = new JSONObject(response);
String error = obj.getString("error");
nums = obj.getInt("nums");
System.out.println("limit_limit_num"+nums);
if(nums>=1) {
if (error.equals("true")) {
from_name_txt.setText("GateKeeper : " + obj.getString("names"));
JSONArray tower = obj.getJSONArray("Flat");
for (int i = 0; i < tower.length(); i++) {
JSONObject jsonnew = tower.getJSONObject(i);
GateInfoPojo actor = new GateInfoPojo();
String id = jsonnew.getString("id");
String Reply_From = jsonnew.getString("reply_from");
String message = jsonnew.getString("message");
String reply_date = jsonnew.getString("send_time");
String usertype = jsonnew.getString("usertype");
actor.setId(id);
actor.setReply_from(Reply_From);
actor.setMessage(message);
actor.setSend_time(reply_date);
actor.setUsertype(usertype);
if(limit==0){
mList.add(actor);
}
else{
mList.add(0,actor);
}
}
Collections.reverse(mList);
mAdapter.notifyDataSetChanged();
mRecyclerView.setAdapter(mAdapter);
// mRecyclerView.getLayoutManager().scrollToPosition(nums - 1);
}
}
else
{
mRecyclerView.setVisibility(View.GONE);
ll_no_data.setVisibility(View.VISIBLE);
// TastyToast.makeText(getApplicationContext(), obj.getString("msg"), TastyToast.LENGTH_LONG, TastyToast.ERROR);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
dialog.CancelProgressDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("empid", new_id);
params.put("fid", id);
params.put("usertype", "FlatUser");
params.put("limit", String.valueOf(limit));
Log.e("params", String.valueOf(params));
return params;
}
};
requestQueue.add(stringRequest);
}
Try adding the following code, both of them need to be true.
mLayoutManager.setStackFromEnd(true);
mLayoutManager.setReverseLayout(true);
From OnCreate() remove your setadapter as your list doesn't have data yet.
and in your onResponse() reverse your listdata before setting it
Collections.reverse(mList);
mAdapter = new GateInfoAdapter(mList, ctx);
mRecyclerView.setAdapter(mAdapter);
I am developing an android app, where I am using Relam as local Database. I have rest api one for all the user information and other is for news information. I have two buttons. one for showing the user information and other is for showing the news information. Now, with my code what is done, after login, I need to click the button at first for user information and news information accordingly and then I can see those images and news. but if I connection off, just after login, the data is not showing in the view. I am explaining my code in detail.Also I am having problem in image loading. How can I Make the funtionality so that user can get all the information just after login.I am reallly sorry for such a long code. It would be really helpful for me if someone tell me how can I modify my code to store all data in background thread, so that user get all information just after login.
The part of the login page where I want to start
private void loginUser(final String mEmail, final String mPassword) {
final GlobalClass globalClass = new GlobalClass();
globalClass.setEmail_info( mEmail );
setFilePath();
RequestQueue queue = Volley.newRequestQueue( LoginPage.this );
StringRequest strReq = new StringRequest( Request.Method.POST,
LOGIN_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d( TAG, "Register Response: " + response.toString() );
//parse your response here
if (response.contains( "overview" )) {
showProgress( true );
globalClass.setImage_urlpath( Constants.HTTP.PHOTO_URL + mEmail);
String str = globalClass.readDatafromStorage();
Log.d("----After Login---",str);
if ( !str.contains("ACTIVATE") ) {
Log.d( "----After Login---", "After Login" );
}
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(KEY_EMAIL, mEmail);
editor.putString(KEY_PASSWORD, mPassword);
editor.commit();
showProgress(false);
Intent loginIntent = new Intent(LoginPage.this, MainOptionPage.class);
loginIntent.putExtra(KEY_EMAIL, mEmail);
startActivity(loginIntent);
} else {
userEmail.setError(getString(R.string.error_incorrect_login));
userEmail.requestFocus();
}
}
}, new Response.ErrorListener() {
#Override
....
Here is my code for User Page
public class MyColleaguesPage extends AppCompatActivity implements ColleagueController.UserCallbackListener {
private List<MyColleagueModel> myColleagueList = new ArrayList<>();
private Realm colleagueRealm;
private RealmResults<MyColleagueModel> colleagueResult;
private List<MyColleagueModel> filteredModelList;
private RealmChangeListener realmListener;
private static final String DIALOG_TAG = "EmployeeDialog";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mycolleagues_layout);
configViews();
}
private void configViews() {
recyclerView = this.findViewById(R.id.colleagues_recycler);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(MyColleaguesPage.this));
recyclerView.setRecycledViewPool(new RecyclerView.RecycledViewPool());
colleagueRealm = Realm.getDefaultInstance();
RealmResults<MyColleagueModel> results = colleagueRealm.where(MyColleagueModel.class).findAll();
for (int i = 0; i < results.size(); i++) {
myColleagueList.add(results.get(i));
}
adapter = new MyColleaguesAdapter(myColleagueList,getApplicationContext());
//adapter = new MyColleaguesAdapter(myColleagueList,getApplicationContext());
Log.d( "adapter value is"+"", String.valueOf( adapter ) );
recyclerView.setAdapter(adapter);
}
//successful
#Override
public void onFetchStart() {
}
#Override
public void onFetchProgress(ColleagueModel colleague) {
//adapter.addColleague(colleague);
}
#Override
public void onFetchProgress(List<ColleagueModel> colleagueList) {
}
#Override
public void onFetchComplete() {
}
#Override
public void onFetchFailed() {
}
}
Here is my controller class for my colleague page
public class ColleagueController {
private static final String TAG = ColleagueController.class.getSimpleName();
private UserCallbackListener mListener;
private ColleagueResApiManager mApiManager;
Realm myColleague_realm;
public ColleagueController() {
mApiManager = new ColleagueResApiManager();
}
public void startFetching(){
myColleague_realm = Realm.getDefaultInstance();
mApiManager.getColleagueApi().getColleague(new Callback<String>() {
#Override
public void success(String s, Response response) {
Log.d(TAG, "JSON :: " + s);
try {
JSONArray array = new JSONArray(s);
for(int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
Log.d("-----Start Fetching---", object.optString( "name" ));
myColleague_realm.beginTransaction();
MyColleagueModel mycolleague = myColleague_realm.createObject( MyColleagueModel.class );
mycolleague.setName( object.optString( "name" ) );
.... data ) );
myColleague_realm.commitTransaction();
}
} catch (JSONException e) {
mListener.onFetchFailed();
}
// mListener.onFetchComplete();
}
#Override
public void failure(RetrofitError error) {
Log.d(TAG, "Error :: " + error.getMessage());
if (mListener != null) {
mListener.onFetchComplete();
}
}
});
}
public interface UserCallbackListener{
void onFetchComplete();
void onFetchFailed();
}
}
In the same way I have other page news option page where I am shoing the news data. Here is my news page.
public class NewsPage extends AppCompatActivity{
private RecyclerView recyclerView;
private NewsAdapter adapter;
private Realm newsRealm;
private List<NewsRealmModel> mNewsList;
private List<NewsRealmModel> filteredModelList;
private NewsController mController;
Constant constant;
SharedPreferences app_preferences;
int appTheme;
int themeColor;
int appColor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView( R.layout.news_page_layout);
configViews();
}
private void configViews() {
recyclerView = this.findViewById(R.id.news_recycler);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(NewsPage.this));
recyclerView.setRecycledViewPool(new RecyclerView.RecycledViewPool());
Realm newsRealm = Realm.getDefaultInstance();
RealmResults<NewsRealmModel> temp = newsRealm.where(NewsRealmModel.class).findAll();
mNewsList = new ArrayList<>();
for (int i = 0; i < temp.size(); i++) {
mNewsList.add(temp.get(i));
}
adapter = new NewsAdapter(mNewsList,getApplicationContext());
Log.d( "adapter value is"+"", String.valueOf( adapter ) );
recyclerView.setAdapter(adapter);
}
}
And the new Controller Class
public class NewsController {
private static final String TAG = NewsController.class.getSimpleName();
private UserCallbackListener mListener;
private NewsRestApiManager mApiManager;
private AppImage appImages;
Realm myNews_realm;
ArrayList<String> title_list = new ArrayList<>();
GlobalClass globalClass = new GlobalClass();
public NewsController(UserCallbackListener listener) {
mListener = listener;
mApiManager = new NewsRestApiManager();
}
public void startFetching() {
myNews_realm = Realm.getDefaultInstance();
mApiManager.getNewsApi().getNews(new Callback<String>() {
#Override
public void success(String s, Response response) {
Log.d(TAG, "JSON :: " + s);
try {
JSONArray array = new JSONArray(s);
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
Log.d("-----Start Fetching---", jsonObject.optString("title"));
if (!myNews_realm.isInTransaction()) {
myNews_realm.beginTransaction();
NewsRealmModel news = new NewsRealmModel();
....... data
}
myNews_realm.copyToRealm(news);
myNews_realm.commitTransaction();
mListener.onFetchProgressNews(news);
} else {
myNews_realm.commitTransaction();
}
}
} catch (JSONException e) {
mListener.onFetchFailed();
}
mListener.onFetchComplete();
}
#Override
public void failure(RetrofitError error) {
Log.d(TAG, "Error :: " + error.getMessage());
mListener.onFetchComplete();
}
});
}
public interface UserCallbackListener {
void onFetchProgressNews(NewsRealmModel news);
void onFetchComplete();
void onFetchFailed();
}
}
To do your database processing on a background thread using Volley, you need to extend Request<T> and do the Realm write in parseNetworkResponse method.
public class RealmGsonObjectRequest<T, M extends RealmModel> extends Response<Void> {
...
#Override
protected Response<Void> parseNetworkResponse(
NetworkResponse response) {
try {
String json = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
T data = gson.fromJson(json, clazz);
// write the downloaded data into the Realm on bg thread
try(Realm r = Realm.getDefaultInstance()) {
M model = mapper.toModel(data);
r.executeTransaction((realm) -> {
realm.insertOrUpdate(model);
});
}
return Response.success(null,
HttpHeaderParser.parseCacheHeaders(response)
);
} // handle errors
}
You might need a RealmGsonListRequest as well.
public class RealmGsonListRequest<T, M extends RealmModel> extends Response<Void> {
...
#Override
protected Response<Void> parseNetworkResponse(
NetworkResponse response) {
try {
String json = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
List<T> data = gson.fromJson(json, new TypeToken<ArrayList<T>>() {}.getType());
// write the downloaded data into the Realm on bg thread
try(Realm r = Realm.getDefaultInstance()) {
M model = mapper.toModel(data);
r.executeTransaction((realm) -> {
realm.insertOrUpdate(model);
});
}
return Response.success(null,
HttpHeaderParser.parseCacheHeaders(response)
);
} // handle errors
}
For more information, refer to the official Volley tutorial on how to create a custom Volley request type.
Here is my code, I have to call method getServerResponse() for first time to get store in arraylist and when I scrolls down I have to call method getServerResponseScroll(). I got result and notify adapter but after scrolling down and up data changes position or may be not visible or get changed. I had created custom adapter for chat. Please help me how to sort out this kind of problem.
public class ChatDetailActivity extends AppCompatActivity {
String macAddress;
RecyclerView recyclerView;
Activity context;
ChatAdapter adapter;
EditText etText;
DatabaseAdapter db;
NetClient nc;
EditText edtSend;
Button btnSend;
DataPref mDataPref;
static int page = 0;
SwipeRefreshLayout mSwipeRefreshLayout;
JSONArray chatDetailListJsonArray;
String toId, channelId, toProfilePic, deviceToken, deviceOsType;
static ArrayList<ChatDetailModel> chatDetailModels = new ArrayList<ChatDetailModel>();
// User mchatUSer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_detail);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
recyclerView = (RecyclerView) findViewById(R.id.card_recycler_view);
mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
edtSend = (EditText) findViewById(R.id.edtSend);
btnSend = (Button) findViewById(R.id.btnSend);
db = new DatabaseAdapter(this);
mDataPref = DataPref.getInstance(this);
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wifiManager.getConnectionInfo();
macAddress = wInfo.getMacAddress();
etText = (EditText) findViewById(R.id.etText);
toId = getIntent().getStringExtra("toId");
channelId = getIntent().getStringExtra("channelId");
toProfilePic = getIntent().getStringExtra("toProfilePic");
deviceToken = getIntent().getStringExtra("deviceToken");
deviceOsType = getIntent().getStringExtra("deviceOsType");
getServerResponse(this);
connectionForSend();
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessage();
}
});
}
void getServerResponse(final Context context){
StringRequest strReqNewsList = new StringRequest(Request.Method.POST, Constants.getChatDetailListUrl, new
Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("GetNewsList Response POST " + response);
/*
if (progressDialog != null) {
if (progressDialog.isShowing())
progressDialog.dismiss();
}*/
String message = "";
try {
JSONObject jsonObjectResponse = new JSONObject(response);
String responseStatus = jsonObjectResponse.getString("status");
message = jsonObjectResponse.getString("message");
if (responseStatus.equals("true")) {
chatDetailListJsonArray = jsonObjectResponse.getJSONArray("data");
if(page==0) {
GetChat.getInstance(context).deleteAllTableData("tbl_chat_detail", channelId);
}
// JSONObject chatListJsonObject= new JSONObject(gson.toJson(chatListJsonArray));
ArrayList<ChatDetailModel> chatlistModels = new Gson()
.fromJson(chatDetailListJsonArray.toString(),
new TypeToken<List<ChatDetailModel>>() {
}.getType());
for (int i = 0; i < chatDetailListJsonArray.length(); i++) {
ChatDetailModel chatlistModel = chatlistModels.get(i);
chatlistModel.setChannel_id(channelId);
GetChat.getInstance(context).addChatDetailList(new JSONObject(new Gson().toJson(chatlistModel)));
}
JSONArray chatListJsonArray = GetChat.getInstance(ChatDetailActivity.this).getChatDetailListJsonArray(channelId);
chatDetailModels = new Gson().fromJson(chatListJsonArray.toString(), new TypeToken<List<ChatDetailModel>>() {
}.getType());
implemantation();
}
} catch (JSONException e) {
e.printStackTrace();
JSONArray chatListJsonArray = GetChat.getInstance(ChatDetailActivity.this).getChatDetailListJsonArray(channelId);
chatDetailModels = new Gson().fromJson(chatListJsonArray.toString(), new TypeToken<List<ChatDetailModel>>() {
}.getType());
implemantation();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
/* if (progressDialog != null) {
if (progressDialog.isShowing())
progressDialog.dismiss();
}*/
error.printStackTrace();
JSONArray chatListJsonArray = GetChat.getInstance(ChatDetailActivity.this).getChatDetailListJsonArray(channelId);
chatDetailModels = new Gson().fromJson(chatListJsonArray.toString(), new TypeToken<List<ChatDetailModel>>() {
}.getType());
implemantation();
// DatabaseAdapter.deleteDatabase(context);
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("to_id", toId);
params.put("from_id", mDataPref.getUserId());
params.put("page",page+"");
params.put("last_sync_date_time", "");
return params;
}
#Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
};
strReqNewsList.setRetryPolicy(new DefaultRetryPolicy(40 * 1000, 1, 1.0f));
AppController.getInstance(context).addToRequestQueue(strReqNewsList);
}
void getServerResponseScroll(final Context context) {
StringRequest strReqNewsList = new StringRequest(Request.Method.POST, Constants.getChatDetailListUrl, new
Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("GetNewsList Response POST " + response);
String message = "";
try {
JSONObject jsonObjectResponse = new JSONObject(response);
String responseStatus = jsonObjectResponse.getString("status");
message = jsonObjectResponse.getString("message");
if (responseStatus.equals("true")) {
chatDetailListJsonArray = jsonObjectResponse.getJSONArray("data");
// JSONObject chatListJsonObject= new JSONObject(gson.toJson(chatListJsonArray));
ArrayList<ChatDetailModel> chatlistModels = new Gson()
.fromJson(chatDetailListJsonArray.toString(),
new TypeToken<List<ChatDetailModel>>() {
}.getType());
for (int i = 0; i < chatDetailListJsonArray.length(); i++) {
ChatDetailModel chatlistModel = chatlistModels.get(i);
chatlistModel.setChannel_id(channelId);
GetChat.getInstance(context).addChatDetailList(new JSONObject(new Gson().toJson(chatlistModel)));
}
JSONArray chatListJsonArray = GetChat.getInstance(ChatDetailActivity.this).getChatDetailListJsonArray(channelId);
// chatDetailModels.clear();
ArrayList<ChatDetailModel> chatDetailModels1 = new ArrayList<ChatDetailModel>();
chatDetailModels1 = new Gson().fromJson(chatListJsonArray.toString(), new TypeToken<List<ChatDetailModel>>() {
}.getType());
chatDetailModels.clear();
chatDetailModels.addAll(chatDetailModels1);
mSwipeRefreshLayout.setRefreshing(false);
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
/* if (progressDialog != null) {
if (progressDialog.isShowing())
progressDialog.dismiss();
}*/
error.printStackTrace();
// DatabaseAdapter.deleteDatabase(context);
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("to_id", toId);
params.put("from_id", mDataPref.getUserId());
params.put("page", page + "");
params.put("last_sync_date_time", "");
return params;
}
#Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
};
strReqNewsList.setRetryPolicy(new DefaultRetryPolicy(40 * 1000, 1, 1.0f));
AppController.getInstance(context).addToRequestQueue(strReqNewsList);
}
void implemantation() {
RecyclerView.LayoutManager manager = new LinearLayoutManager(this.getApplicationContext());
recyclerView.setLayoutManager(manager);
adapter = new ChatAdapter(this.getApplicationContext(), chatDetailModels);
recyclerView.setAdapter(adapter);
recyclerView.scrollToPosition(chatDetailModels.size() - 1);
recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, recyclerView, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Intent i = new Intent(ChatDetailActivity.this, ProfilesDetailActivity.class);
// i.putExtra("profileId",ChatlistModel.get(position).getId());
startActivity(i);
}
#Override
public void onItemLongClick(View view, int position) {
}
}));
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
page++;
getServerResponseScroll(ChatDetailActivity.this);
}
});
}
// Adapter for chat
public class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.ViewHolder> {
private ArrayList<ChatDetailModel> chatDetailModels;
private Context context;
public ChatAdapter(Context context, ArrayList<ChatDetailModel> chatDetailModels) {
this.context = context;
this.chatDetailModels = chatDetailModels;
}
#Override
public ChatAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.chat_lsit_row, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
if (chatDetailModels.get(position).getFrom_username().equalsIgnoreCase(mDataPref.getUsername())) {
viewHolder.messageTextRight.setText(chatDetailModels.get(position).getMessage());
viewHolder.chatLeftLayout.setVisibility(View.GONE);
if (mDataPref.getProfilePicFullUrl().equals("null") || mDataPref.getProfilePicFullUrl().equals("")) {
viewHolder.fromImageView.setImageResource(R.drawable.default_profile_pic);
} else {
Picasso.with(context).load(mDataPref.getProfilePicFullUrl()).placeholder(R.drawable.default_profile_pic).transform(new CircleTransform()).resize(40, 40).into(viewHolder.fromImageView);
}
} else {
viewHolder.messageTextLeft.setText(chatDetailModels.get(position).getMessage());
viewHolder.chatRightLayout.setVisibility(View.GONE);
if (toProfilePic.equals("null") || toProfilePic.equals("")) {
viewHolder.toImageView.setImageResource(R.drawable.default_profile_pic);
} else {
Picasso.with(context).load(toProfilePic).placeholder(R.drawable.default_profile_pic).transform(new CircleTransform()).resize(40, 40).into(viewHolder.toImageView);
}
}
}
#Override
public int getItemCount() {
return chatDetailModels.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private LinearLayout chatLeftLayout;
private ImageView toImageView;
private TextView messageTextLeft;
private LinearLayout chatRightLayout;
private TextView messageTextRight;
private ImageView fromImageView;
public ViewHolder(View view) {
super(view);
chatLeftLayout = (LinearLayout) view.findViewById(R.id.chatLeftLayout);
toImageView = (ImageView) view.findViewById(R.id.toImageView);
messageTextLeft = (TextView) view.findViewById(R.id.message_text_left);
chatRightLayout = (LinearLayout) view.findViewById(R.id.chatRightLayout);
messageTextRight = (TextView) view.findViewById(R.id.message_text_right);
fromImageView = (ImageView) view.findViewById(R.id.fromImageView);
}
}
}
}
From onSaveInstanceState documentation:
Called when the LayoutManager should save its state. This is a good time to save your
* scroll position, configuration and anything else that may be required to restore the same
* layout state if the LayoutManager is recreated.
* RecyclerView does NOT verify if the LayoutManager has changed between state save and
* restore. This will let you share information between your LayoutManagers but it is also
* your responsibility to make sure they use the same parcelable class.
To get current state of recyclerview:
private Parcelable recyclerViewState = recyclerView.getLayoutManager().onSaveInstanceState();
to restore saved instance:
recyclerView.getLayoutManager().onRestoreInstanceState(recyclerViewState);
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);