i have two activty A and B in my app. i am loading data from api in my listview using json and store that data in listview using getter setter method
in activity A.
now i want to maintain data in listview after start B activity and when i back from B to A activity i dont wont to download data again from json.
i am right now doing it by sotirng api responce in string and after back from B to A i pass json string to adapter but it still take time to load listview
any idea how to prevent loading time and getting data instantly when i back from B to A.
here is code of my activty A
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_list);
pref =getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
editor = pref.edit();
itemCount_database = new ItemCount_database(this);
item_adding_cart = new Item_adding_cart(this);
String fromhome =pref.getString("from_product_view_back_Btn","");
if(fromhome.equals("yes"))
{
editor.putString("from_product_view_back_Btn","no");
editor.commit();
overridePendingTransition(R.anim.right_in, R.anim.right_out);
stored_json();
recycler_adapter = new Product_list_Recycler_Adapter(this,datalist);
recyclerView.setAdapter(recycler_adapter);
recycler_adapter.setListener(ProductList_Activity.this);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
}
else
{
overridePendingTransition(R.anim.left_in, R.anim.left_out);
pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
jsoncall();
}
initialised_actionbar();
checkout = (TextView)findViewById(R.id.txt_checkout_product_list);
txt_total_amount =(TextView)findViewById(R.id.total_amount_in_checkout_label);
checkout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myint = new Intent(ProductList_Activity.this,Cart.class);
startActivity(myint);
}
});
footer =(LinearLayout) findViewById(R.id.footer);
footer.setVisibility(View.GONE);
cart_item_count =item_adding_cart.total_product_count(1);
if(cart_item_count==0 )
{
footer.setVisibility(View.GONE);
cart_count_background.setVisibility(View.GONE);
}
else
{
footer.setVisibility(View.VISIBLE);
cart_count_background.setVisibility(View.VISIBLE);
}
wishlist_item_count = item_adding_cart.getrowcount_wishlist();
if(wishlist_item_count==0)
{
// wishlist_count_backround.setVisibility(View.GONE);
}
else
{
// wishlist_count_backround.setVisibility(View.VISIBLE);
}
recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
initialization();
hidePDialog();
}
}, 3000);
boolean popup_once=pref.getBoolean("total_item_cart_insert_qery",true);
if(popup_once)
{
editor.putBoolean("total_item_cart_insert_qery",false);
editor.commit();
item_adding_cart.insert_total_item_in_cart(0);
}
}
public void jsoncall() {
final HashMap<String, String> params = new HashMap<String, String>();
params.put("sub_cate_id","24");
params.put("city_id","3");
CustomRequest_JsonObject servicelistrequest = new CustomRequest_JsonObject
(/*Request.Method.POST,*/
url,
params,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
stored_json_string = response.toString();
editor.putString("stored_json_prodcutlist",stored_json_string);
editor.commit();
try {
JSONArray data = response.getJSONArray("data");
for (int ie = 0; ie < data.length(); ie++) {
JSONObject dataobje = data.getJSONObject(ie);
ModelData_Product_list_act Model = new ModelData_Product_list_act();
Model.setProduct_id(dataobje.getString("product_id"));
Model.setTitle(dataobje.getString("title"));
Model.setImage(dataobje.getString("product_image"));
Model.setWieght(dataobje.getString("weight"));
Model.setLatest_price(dataobje.getString("mrp"));
Model.setDiscount(dataobje.getString("discount"));
Model.setPre_price(dataobje.getString("retail_price"));
Model.setUnit(dataobje.getString("unit"));
datalist.add(Model);
loadlistview();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hidePDialog();
Toast.makeText(getApplicationContext(), "error : " + error.getMessage(), Toast.LENGTH_LONG).show();
}
}
);
AppController.getInstance().addToRequestQueue(servicelistrequest);
}
public void stored_json() {
pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
String mystored_json = pref.getString("stored_json_prodcutlist","");
try {
JSONObject myjsonojb = new JSONObject(mystored_json);
JSONArray data = myjsonojb.getJSONArray("data");
for (int ie = 0; ie < data.length(); ie++) {
JSONObject dataobje = data.getJSONObject(ie);
ModelData_Product_list_act Model = new ModelData_Product_list_act();
Model.setProduct_id(dataobje.getString("product_id"));
Model.setTitle(dataobje.getString("title"));
Model.setImage(dataobje.getString("product_image"));
Model.setWieght(dataobje.getString("weight"));
Model.setLatest_price(dataobje.getString("mrp"));
Model.setDiscount(dataobje.getString("discount"));
Model.setPre_price(dataobje.getString("retail_price"));
Model.setUnit(dataobje.getString("unit"));
datalist.add(Model);
// loadlistview();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();
}
}
Instead of using startActivity use startActivityForResult(yourIntent,REQ_CODE)
Intent startActivity = new Intent(context,ClassName.class);
startActivityForResult(startActivity,REQ_CODE);
after your come back from Activity B ,so can send your list from activity and can get in Activity A.
Then onActivityResult callback method get your intent data
I Have another idea use background task is on create and store it to local db and display the data from local db in on resume .you always call list view from local db so when you come back b to a on resume will call so it will not call on create so it will not call background data
Related
I am currently using recycler view to load courses using JSON, the first course has its id in JSON that is one, and then the second, each course has its id that is stored in the db. I want that if I click the first button it should save its ID that is one to my session manager and pass it to the next activity to load its corresponding data, and when I click on the 2nd button it should load data by passing its respective ID. I have attached the onclick of my recycler view, it should get the ID of the button clicked and store it into a string that I will then store into the session manager.
private RecyclerView mRecyclerView;
private CourseAdapter mExampleAdapter;
private ArrayList<CourseItem> mExampleList;
private RequestQueue mRequestQueue;
private static final String URL_PRODUCTS = "https://www.sniptx.com/ws/findTeacher/allCourses.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mRecyclerView = (RecyclerView) findViewById(R.id.course_recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, mRecyclerView, new RecyclerItemClickListener
.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Toast.makeText(HomeActivity.this, "Item Clicked" + position , Toast.LENGTH_LONG).show();
}
#Override
public void onItemLongClick(View view, int position) {
//handle longClick if any
}
}));
mExampleList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJSON();
}
private void parseJSON() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_PRODUCTS,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
JSONArray courseArray = obj.getJSONArray("courses");
for (int i = 0; i < courseArray.length(); i++) {
JSONObject courseObject = courseArray.getJSONObject(i);
String courseName = courseObject.getString("c_name");
String id = courseObject.getString("c_id").trim();
l.add(new CourseItem(courseName, id));
}
try {
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
JSONObject product = array.getJSONObject(i);
String courseName = product.getString("c_name");
String id = product.getString("id").trim();
mExampleList.add(new CourseItem(courseName, id));
Toast.makeText(HomeActivity.this,"ID is" +id, Toast.LENGTH_SHORT).show();
}
mExampleAdapter = new CourseAdapter(HomeActivity.this, mExampleList);
mRecyclerView.setAdapter(mExampleAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
Volley.newRequestQueue(this).add(stringRequest); }
}
Use Intent to set the data(i.e id of clicked button)as extra params of intent in first activity and get the intent extras in second activity.
// first activity
Intent i = new Intent(getApplicationContext(), SecondActivity.class);
i.putExtra("id", value);
startActivity(i);
// second activity
Bundle extras = getIntent().getExtras();
int id = extras.getInt("id");
Here in my UI, i have used two buttons to load different data to a RecyclerView. First time the data is displaying properly on click of each button. But if i click the button for the second time the data is adding to the adapter twice. I mean the the adapter is not cleared. it is keep on adding the data on click of button. I Think i have to do something with the adapter on click of a button. Can anyone pls let me know how to clear the adapter or where i am going wrong..
Here is the code.
public class GstVendorLocRetrieve extends AppCompatActivity {
private String vault;
private TextView txt;
public static final String DATA_URL = "http://oursite.com/getgstvendorlocation.php?vault_no=";
public static final String DATA_URL1 = "http://oursite.com/getgstcustomerlocation.php?vault_no=";
//Tags for my JSONRes
public static final String TAG_VendorID = "VendorID";
public static final String TAG_CustomerID = "Customer_ID";
public static final String TAG_ADDRESS = "Address";
private Button vendor;
private Button customer;
//Creating a List of superheroes
private List<GstVendLoc> listSuperHeroes;
private List<GstCustLoc> listSuperHeroes1;
//Creating Views
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.locationretrieve);
SharedPreferences sharedPreferences = getSharedPreferences(GstLogin.SHARED_PREF_NAME, MODE_PRIVATE);
vault = sharedPreferences.getString(GstLogin.EMAIL_SHARED_PREF,"Not Available");
vendor = (Button) findViewById(R.id.login);
customer = (Button) findViewById(R.id.login1);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
//Initializing our superheroes list
listSuperHeroes = new ArrayList<>();
listSuperHeroes1 = new ArrayList<>();
vendor.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
recyclerView.setAdapter(null);
getData();
}
});
customer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
recyclerView.setAdapter(null);
getData1();
}
});
}
//This method will get data from the web api
private void getData(){
//Showing a progress dialog
final ProgressDialog loading = ProgressDialog.show(this,"Loading Data", "Please wait...",false,false);
//Creating a json array request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(DATA_URL+vault,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Dismissing progress dialog
loading.dismiss();
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
//This method will parse json data
private void parseData(JSONArray array){
for(int i = 0; i<array.length(); i++) {
GstVendLoc gst1 = new GstVendLoc();
JSONObject json = null;
try {
json = array.getJSONObject(i);
gst1.setVendorID(json.getString(TAG_VendorID));
gst1.setAddress(json.getString(TAG_ADDRESS));
} catch (JSONException e) {
e.printStackTrace();
}
listSuperHeroes.add(gst1);
}
//Finally initializing our adapter
adapter = new CardAdapter17(listSuperHeroes, this);
//Adding adapter to recyclerview
recyclerView.setAdapter(adapter);
}
private void getData1(){
//Showing a progress dialog
final ProgressDialog loading = ProgressDialog.show(this,"Loading Data", "Please wait...",false,false);
//Creating a json array request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(DATA_URL1+vault,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Dismissing progress dialog
loading.dismiss();
//calling method to parse json array
parseData1(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
//This method will parse json data
private void parseData1(JSONArray array){
for(int i = 0; i<array.length(); i++) {
GstCustLoc gst1 = new GstCustLoc();
JSONObject json = null;
try {
json = array.getJSONObject(i);
gst1.setCustomer_ID(json.getString(TAG_CustomerID));
gst1.setAddress(json.getString(TAG_ADDRESS));
} catch (JSONException e) {
e.printStackTrace();
}
listSuperHeroes1.add(gst1);
}
//Finally initializing our adapter
adapter = new CardAdapter18(listSuperHeroes1, this);
//Adding adapter to recyclerview
recyclerView.setAdapter(adapter);
}
}
Use this code for clear RecycleView items
public void clear() {
int size = listSuperHeroes.size();
listSuperHeroes.clear();
notifyItemRangeRemoved(0, size);
}
You need to clear your Array List before you get data second time.
Do this inside parseData1 method before for loop.
listSuperHeroes.clear();
listSuperHeroes1.clear();
What you have to do is Update RecyclerView on button Click , Put below method in your adapter
public void updateData(ArrayList<ViewModel> viewModels) {
items.clear();
items.addAll(viewModels);
notifyDataSetChanged();
}
Than call this method with new data
ArrayList<ViewModel> viewModelsWithNewData = new ArrayList<ViewModel>();
adapter.updateData(viewModelsWithNewData );
you dont need to set adapter after geting data from the online
//Finally initializing our adapter
adapter = new CardAdapter18(listSuperHeroes1, this);
//Adding adapter to recyclerview
recyclerView.setAdapter(adapter);
you can initialize of set the adapter in the on create and add data in the 'listSuperHeroes1' and after parse data you can do adapter.notifyDataSetChanged();
this will change the list data.
and the solution for the getting the previous data you have to remove the all data from the listsuperHeroes1 this will help you if you getting any problem please comment .
I am just improving #Rony's answer.
If you should always check if the ArrayList is not null before attempting to call .size(), otherwise, you might end up with a null pointer exception
if (listSuperHeroes != null && !listSuperHeroes.isEmpty()) {
int size = listSuperHeroes.size();
listSuperHeroes.clear();
notifyItemRangeRemoved(0, size);
}
I have a website which publishes news on daily basis.
Now, I'm sending a JsonArrayRequest to retrieve and parse the title and summary of each news published on the website. The parsed items are then used to populate RecyclerView.
The problem I'm having is the way volley implements caching .
Let's take this scenario: the app is installed, launched and the RecyclerView is populated. The user reads the news and forgets about the app
Later, the user launches the app and the items are fetched and RecyclerView is populated.
Between the first and the second launch, new news are published on the website. But in the second launch, these new items are not displayed. However, if the user manually go to app settings and clear cache of the app, and relaunch, the new items are displayed.
You get my point?
While I don't want to disable Volley caching, how do I make it to always fetch new items?
EDIT
MainActivity
public class MainActivity extends AppCompatActivity {
private final String TAG = "MainActivity";
//Creating a list of newss
private List<NewsItems> mNewsItemsList;
//Creating Views
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate called");
//Initializing Views
recyclerView = (RecyclerView) findViewById(R.id.news_recycler);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
//Initializing the newslist
mNewsItemsList = new ArrayList<>();
adapter = new NewsAdapter(mNewsItemsList, this);
recyclerView.setAdapter(adapter);
if (NetworkCheck.isAvailableAndConnected(this)) {
//Calling method to get data
getData();
} else {
//Codes for building Alert Dialog
alertDialogBuilder.setPositiveButton(R.string.alert_retry, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (!NetworkCheck.isAvailableAndConnected(mContext)) {
alertDialogBuilder.show();
} else {
getData();
}
}
});
alertDialogBuilder.setNegativeButton(R.string.alert_cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialogBuilder.show();
}
}
//This method will get data from the web api
private void getData(){
Log.d(TAG, "getData called");
//Codes for Showing progress dialog
//Creating a json request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(ConfigNews.GET_URL + getNumber(),
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, "onResponse called");
//Dismissing the progress dialog
if (mProgressDialog != null) {
mProgressDialog.hide();
}
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
//This method will parse json data
private void parseData(JSONArray array){
Log.d(TAG, "Parsing array");
for(int i = 0; i<array.length(); i++) {
NewsItems newsItem = new NewsItems();
JSONObject jsonObject = null;
try {
jsonObject = array.getJSONObject(i);
newsItem.setNews_title(jsonObject.getString(ConfigNews.TAG_VIDEO_TITLE));
newsItem.setNews_body(jsonObject.getString(ConfigNews.TAG_VIDEO_BODY));
} catch (JSONException w) {
w.printStackTrace();
}
mNewsItemsList.add(newsItem);
}
adapter.notifyItemRangeChanged(0, adapter.getItemCount());
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy called");
if (mProgressDialog != null){
mProgressDialog.dismiss();
Log.d(TAG, "mProgress dialog dismissed");
}
}
}
Option 1) Delete Cache
before you make a call you can delete the whole cache by myDiskBasedCache.clear() or specific entries by myDiskBasedCache.remove(entryUrl)
Option 2) Custom CacheParser (in the Request)
#Override
protected Response<Bitmap> parseNetworkResponse(NetworkResponse response) {
Response<Bitmap> resp = super.parseNetworkResponse(response);
if(!resp.isSuccess()) {
return resp;
}
long now = System.currentTimeMillis();
Cache.Entry entry = resp.cacheEntry;
if(entry == null) {
entry = new Cache.Entry();
entry.data = response.data;
entry.responseHeaders = response.headers;
entry.ttl = now + 60 * 60 * 1000; //keeps cache for 1 hr
}
entry.softTtl = 0; // will always refresh
return Response.success(resp.result, entry);
}
Option 3) send requests that does not cache
myRequest.setShouldCache(false);
Option 4) use custom Cache implementation
UPDATE:
Example with your code:
//Creating a json request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(ConfigNews.GET_URL + getNumber(),
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, "onResponse called");
//Dismissing the progress dialog
if (mProgressDialog != null) {
mProgressDialog.hide();
}
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
Response<JSONArray> resp = super.parseNetworkResponse(response);
if(!resp.isSuccess()) {
return resp;
}
long now = System.currentTimeMillis();
Cache.Entry entry = resp.cacheEntry;
if(entry == null) {
entry = new Cache.Entry();
entry.data = response.data;
entry.responseHeaders = response.headers;
entry.ttl = now + 60 * 60 * 1000; //keeps cache for 1 hr
}
entry.softTtl = 0; // will always refresh
return Response.success(resp.result, entry);
}
};
UPDATE 2
Http protocol caching supports many ways to define how the client can cache responses and when to update them. Volley simplifies those rules to:
entry.ttl (time to live in ms) if greater than the current time then cache can be used otherwise fresh request needs to be made
and
entry.softTtl (soft time to live in ms :) if greater than the current time
cache is absolutely valid and no request to the server needs to be made, otherwise new request is still made (even if the ttl is good) and if there is a change new response will be delivered.
note that if ttl is valid and softTtl is not you can receive 2 onResponse calls
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);
i want to pass the correct json object on the list item click in the first activity to the second activity. If i click any list item, the json object from JSONArray response should be passed to intent and my next activity must get it.
Here is my code
JsonArrayRequest postReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Consumer user = new Consumer();
user.setTitle(obj.getString("name"));
user.setUserid(obj.getString("user"));
user.setThumbnailUrl(obj.getString("image"));
user.setAmountreq(obj.getString("price"));
user.setTime(obj.getString("date"));
user.setCounty(obj.getString("county"));
// adding request to consumer class
userList.add(user);
} catch (JSONException e) {
e.printStackTrace();
}
}
/*notifying list adapter about data changes
so that it renders the list view with updated data*/
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(postReq);
// listening to single list item on click
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(!obj.isNull(position)){
//start new activity
Intent myIntent = new Intent(RequestFeedActivity.this,RequestFeed.class);
myIntent.putExtra("name", obj.getJSONObject(position).toString());
startActivity(myIntent);
}
// ListView Clicked
}
});
}
On the other activity here is my sample code of the variables i want to be passed
TextView rname, rtitle,rprice, rdate, rdesc, rcounty;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.requestfeed);
rtitle = (TextView)findViewById(R.id.IDRproduct);
rprice = (TextView)findViewById(R.id.IDRquote);
rdate = (TextView)findViewById(R.id.IDRdate);
rdesc = (TextView)findViewById(R.id.IDRdesc);
rname = (TextView)findViewById(R.id.IDRname);
Intent myIntent = getIntent();
//Assign values
rname.setText(myIntent.getExtras().getString("name"));
rtitle.setText(myIntent.getExtras().getString("title"));
rprice.setText(myIntent.getExtras().getString("pricetag"));
rdate.setText(myIntent.getExtras().getString("timereq"));
rdesc.setText(myIntent.getExtras().getString("description"));
rcounty.setText(myIntent.getExtras().getString("county"));
}
I tried this answer but didnt work .Any much help is much appreciated
Try to replace this peace of code:
myIntent.getExtras().getString("name")
With this code:
myIntent.getStringExtra("name");
Just try this
Intent i =new Intent(this,ActivityA.class);
Bundle b =new Bundle();
i.putExtra("KEY","VALUE");
i.putExtras(b);
startActivity(i)
At the receiver side
Bundle b=getIntent().getExtras();
b.getInt("KEY") //useaccording to ur need
If it doesn't work check this answer