How to use shared preferences in RecyclerView.Adapter? - android

How to use shared preferences in RecyclerView.Adapter..? i have used shared preference value in RecyclerView.Adapter..but nothing is saving in shared preference..where exactly i have to use shared preference ..?in RecyclerView.Adapter or activity..?
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
private ImageLoader imageLoader;
private Context context;
private String gd;
public static final String SHARED_PREF_NAME = "myloginapp";
//We will use this to store the boolean in sharedpreference to track user is loggedin or not
public static final String LOGGEDIN_SHARED_PREF = "loggedin";
public static final String GROUPSNAME_SHARED_PREF = "groupname";
public CardAdapter(Context context) {
this.context = context;
}
//List of superHeroes
List<Group> groups;
public CardAdapter(List < Group > groups, Context context) {
super();
//Getting all the superheroes
this.groups = groups;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder (ViewGroup parent,int viewType){
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.groups_list, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder (ViewHolder holder,int position){
Group group1 = groups.get(position);
imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
imageLoader.get(group1.getPic(), ImageLoader.getImageListener(holder.imageView, R.drawable.ic_launcher, android.R.drawable.ic_dialog_alert));
holder.imageView.setImageUrl(group1.getPic(), imageLoader);
holder.groupname.setText(group1.getGname());//i want to store this value in shared preference..
holder.groupinfo.setText(group1.getGinfo());
gd = holder.groupname.getText().toString();//variable gd is storing any value.
holder.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, Viewgroup1.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount () {
return groups.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public NetworkImageView imageView;
public TextView groupname;
public TextView groupinfo;
public Button add;
public ViewHolder(View itemView) {
super(itemView);
imageView = (NetworkImageView) itemView.findViewById(R.id.imageViewHero);
groupname = (TextView) itemView.findViewById(R.id.textViewName);
groupinfo = (TextView) itemView.findViewById(R.id.textViewRank);
add = (Button) itemView.findViewById(R.id.button7);
//String gd = holder.groupname.getText().toString();
SharedPreferences sharedPreferences1 = context.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
//Creating editor to store values to shared preferences
SharedPreferences.Editor editor = sharedPreferences1.edit();
//Adding values to editor
editor.putBoolean(LOGGEDIN_SHARED_PREF, true);
editor.putString(GROUPSNAME_SHARED_PREF, gd);
}
}
}
Viewgroup.java
public class Viewgroup extends AppCompatActivity {
//Creating a List of superheroes
private List<Group> listSuperHeroes;
private String vault;
//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.recycle);
//Initializing Views
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
//Initializing our superheroes list
listSuperHeroes = new ArrayList<>();
SharedPreferences sharedPreferences = getSharedPreferences(ProfileLogin.SHARED_PREF_NAME, MODE_PRIVATE);
vault = sharedPreferences.getString(ProfileLogin.EMAIL_SHARED_PREF,"Not Available");
//Calling method to get data
getData();
}
//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(Config.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++) {
Group group1 = new Group();
JSONObject json = null;
try {
json = array.getJSONObject(i);
group1.setPic(json.getString(Config.TAG_IMAGE_URL));
group1.setGname(json.getString(Config.TAG_NAME));
group1.setGinfo(json.getString(Config.TAG_INFO));
} catch (JSONException e) {
e.printStackTrace();
}
listSuperHeroes.add(group1);
}
//Finally initializing our adapter
adapter = new CardAdapter(listSuperHeroes, this);
//Adding adapter to recyclerview
recyclerView.setAdapter(adapter);
/* recyclerView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
final Button add = (Button) v.findViewById(R.id.button7);
final TextView txtStatusChange = (TextView) v.findViewById(R.id.textViewName);
//final TextView txtStatusChange1 = (TextView) v.findViewById(R.id.textView33);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Viewgroup.this, Viewgroup1.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
// Log.e(TAG_IMAGE_URL, "hello text " + txtStatusChange.getText().toString() + " TAG " + txtStatusChange.getTag().toString());
Toast.makeText(Viewgroup.this, txtStatusChange.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
return false;
}
});*/
}
}

You should add editor.commit() or editor.apply() in order to save your data to Sharedpreferences . Add this below your code
//Adding values to editor
editor.putBoolean(LOGGEDIN_SHARED_PREF, true);
editor.putString(GROUPSNAME_SHARED_PREF, gd);
editor.apply();

why the shared preference is not updating..?
Use onClick method of Button before starting Activity to save value in Sharedpreferences like:
...
gd = holder.groupname.getText().toString();
holder.add.setTag(gd);
...
#Override
public void onClick(View view) {
String strValue=view.getTag().toString();
... save strValue in Sharedpreferences
...
editor.putString(GROUPSNAME_SHARED_PREF, strValue);
editor.apply();
// start new Activity..
}
...

This is what I did. (If you cant access class "context" inside SharedPreferences)
Create a context of the adapter class by Context mConext; or private WeakReference<Context> mContext;
Instead giving mContext use this.mContext.get() wherever you need to use context inside the SharedPrefernce. like
SharedPreferences preferences = this.mContext.get().getSharedPreferences(MY_PREFERENCE_NAME, Context.MODE_PRIVATE);
I tried so many other solutions, but couldn't find the thing.

it works just add this.mcontext.getContext instead of this.mContext.get().

just use itemView.getContext() if you using this in side onCreateViewHolder view holder
GET DATA
just use itemView.getContext() before use getSharedPreferences
save is allso the same
Sharedpreferences prefs =
holder.itemView.getContext().getSharedPreferences("SHARED_PREFS", holder.itemView.getContext().MODE_PRIVATE);
String Variable= holder.prefs.getString("yourkey", null);

Related

how can update date from adapter to recyclerView?

when I send new data or update the info, how can to change my recycle view?
I have used a dapter.notifyDataSetChanged(); , but it's not working...
I tried more method, but it all cannot change my recycler view
in my code
recyclerView = view.findViewById(R.id.recyclerCoin);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
listCoinDiamondModel = new ArrayList<>();
requestQueue = Volley.newRequestQueue(getActivity());
getData();
adapter = new CoinAdapter(listCoinDiamondModel, getActivity());
recyclerView.setAdapter(adapter);
private void sendGift(String postUserID) {
final String postUserIDD = postUserID;
final String GiftAmount = this.GiftAmount.getText().toString().trim();
final String flag = "1";
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_GIFTCOIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
if (success.equals("1")){
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Error" + error.toString(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
//Log.d("FID", fid);
params.put("fid", fid);
params.put("GiftAmount", GiftAmount);
params.put("flag", flag);
params.put("postUserID", postUserIDD);
params.put("uid", getID);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
private JsonArrayRequest getDataFromServer(int requestCount) {
//Initializing ProgressBar
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Load...");
progressDialog.dismiss();
final String GROUP_LIST = "https://example.com/aaa.php?flag=1&fid="+ getActivity().getIntent().getStringExtra("fid") +"&page="+requestCount;
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(GROUP_LIST,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
parseData(response);
progressDialog.dismiss();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(getActivity(), "No More gift Available", Toast.LENGTH_SHORT).show();
}
});
//Returning the request
return jsonArrayRequest;
}
//This method will get data from the web api
private void getData() {
requestQueue.add(getDataFromServer(requestCount));
requestCount++;
}
//This method will parse json data
private void parseData(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
//Creating the newFeedModel object
final CoinDiamondModel coinDiamondModel = new CoinDiamondModel();
JSONObject json = null;
try {
//Getting json
json = array.getJSONObject(i);
String TAG_Coin = "Coin";
String TAG_Diamond = "Diamond";
String TAG_UserName = "UserName";
String TAG_UserPhoto = "UserPhoto";
String TAG_UserID = "UserID";
//Log.d("NAME111", json.getString(json.getString(TAG_UserName)));
coinDiamondModel.setCoin(json.getString(TAG_Coin));
coinDiamondModel.setDiamond(json.getString(TAG_Diamond));
coinDiamondModel.setGiftFromUserName(json.getString(TAG_UserName));
coinDiamondModel.setGiftFromUserPhoto(json.getString(TAG_UserPhoto));
coinDiamondModel.setGiftFromUserID(json.getString(TAG_UserID));
} catch (JSONException e) {
e.printStackTrace();
}
//Adding the newFeedModel object to the list
listCoinDiamondModel.add(coinDiamondModel);
//adapter.addTheCoinData(coinDiamondModel);
}
//Notifying the adapter that data has been added or changed
adapter.notifyDataSetChanged();
}
who knows what's happen and how can solve this?
could you told me how can I do, please?
adapter all code
public class CoinAdapter extends RecyclerView.Adapter<CoinAdapter.ViewHolder> {
private ImageLoader imageLoader;
private List<CoinDiamondModel> newcoinDiamondLists;
private RequestManager glide;
private Context context;
SessionManager sessionManager;
private String getID,memail;
public CoinAdapter(List<CoinDiamondModel> newcoinDiamondLists, Context context) {
this.newcoinDiamondLists = newcoinDiamondLists;
this.glide = Glide.with(context);
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.coinlist, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
sessionManager = new SessionManager(getApplicationContext());
sessionManager.checkLogin();
HashMap<String, String> user = sessionManager.getUserDetail();
getID = user.get(sessionManager.USERID);
memail = user.get(sessionManager.EMAIL);
//String gid = getIntent.getStringExtra("xxx");
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
CoinDiamondModel newCoinDiamondModel = newcoinDiamondLists.get(position);
imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
holder.userName.setText(newCoinDiamondModel.getGiftFromUserName());
holder.userID.setText(newCoinDiamondModel.getGiftFromUserID());
holder.coinCount.setText(" x "+newCoinDiamondModel.getCoin());
glide.load(newCoinDiamondModel.getGiftFromUserPhoto()).into(holder.userPhoto);
}
#Override
public int getItemCount() {
return newcoinDiamondLists.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
CircleImageView userPhoto;
TextView userName,userID,coinCount;
ImageView coinImg;
public ViewHolder(#NonNull View itemView) {
super(itemView);
userPhoto = (CircleImageView) itemView.findViewById(R.id.userPhoto);
userName = (TextView) itemView.findViewById(R.id.userName);
coinCount = (TextView) itemView.findViewById(R.id.coinCount);
userID = (TextView) itemView.findViewById(R.id.userID);
coinImg = (ImageView) itemView.findViewById(R.id.coinImg);
}
}
public void addTheCoinData(CoinDiamondModel coinDiamondModel){
if(coinDiamondModel!=null){
newcoinDiamondLists.add(coinDiamondModel);
notifyDataSetChanged();
}else {
throw new IllegalArgumentException("無資料!");
}
}
}
you can again set the adapter to recycler view after the response of the server
public void onResponse(JSONArray response) {
parseData(response);
progressDialog.dismiss();
adapter = new CoinAdapter(listCoinDiamondModel, getActivity());
recyclerView.setAdapter(adapter);
}
solution 2:
in your adapter write a function to update you list
and call function in activity
add this function to the adapter
public void updateList(List<CoinDiamondModel> list){
newcoinDiamondLists = list;
notifyDataSetChanged();
}
and call a function updateList of when you need an update recyclerview
The RecyclerView initialization and notifyDataSetChanged() is used properly. As your question is not clear enough about the Adapter implementation of the RecyclerView, I can give you several suggestions to check.
In RecyclerView.Adapter check if getItemCount() method is properly overriden with returning the list length (not 0) like below:
#Override
public int getItemCount() {
return listdata.length;
}
In RecyclerView.Adapter check if onCreateViewHolder method is properly overriden with proper xml layout like below:
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View listItem= layoutInflater.inflate(R.layout.coin_xml_layout, parent, false);
ViewHolder viewHolder = new ViewHolder(listItem);
return viewHolder;
}
In RecyclerView.Adapter check if RecyclerView.ViewHolder class is properly extended
and linked the UI elements from the xml with the adapter like below:
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView coinTextView;
public ViewHolder(View itemView) {
super(itemView);
this.coinTextView = (TextView) itemView.findViewById(R.id.coinTextView);
}
}
In RecyclerView.Adapter check if onBindViewHolder method is properly overridden and updated the list component UI properly like below:
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final MyListData myListData = listdata[position];
holder.cointTextView.setText(listdata[position].getCoin());
}
Debug with a breakpoint and check if the listCoinDiamondModel.add(coinDiamondModel) is calling or not and coinDiamondModel object is not empty.
The RecyclerView is placed properly in the activity xml, like the RecyclerView is Visible, has a decent size to show list elements. As an example:
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
you can update your adapter list manually like this:(write this function in your adapter)
public void updateCoinAdapterList(ArrayList<listCoinDiamondModel> recyclerItemsList) {
this.recyclerItemsList = recyclerItemsList;
this.notifyDataSetChanged();
}
you must set your adapter global variable and initialize it in OnCreate or OnResume, and call
adapter.updateCoinAdapterList(listCoinDiamondModel);
when your list changed

Issue in RecyclerView NullPointerException

I want to implement one code where data will come from server and show on RecyclerView item, below is my mainActivity class where I am fetching the data from server but this code is not running just because of NullPointerException.
I am using Volley to fetch the data
public class MainActivity_Plan extends AppCompatActivity {
private List<Plan> planList = new ArrayList<>();
private RecyclerView recyclerView;
private PlanAdapter pAdapter;
private RequestQueue requestQueue;
String url;
// Session Manager Class
SessionManager session;
String matri_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.plan_activity);
session = new SessionManager(this);
HashMap<String, String> user = session.getUserDetails();
matri_id = user.get(SessionManager.KEY_EMAIL);
Log.e("matri_id+++++++++++++",matri_id);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
pAdapter = new PlanAdapter(planList);
RecyclerView.LayoutManager mLayoutManager = new
LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(pAdapter);
getInfo();
Log.e("url____________",url);
}
private void getInfo() {
url = ConfigPlan.DATA_URL+matri_id;
JsonArrayRequest of volley
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Calling method parseData to parse the json response
Log.e("response---------",response.toString());
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//If an error occurs that means end of the list has reached
Toast.makeText(MainActivity_Plan.this, "No More Items Available", Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(jsonArrayRequest);
}
This method will parse json data
private void parseData(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
Plan p = new Plan();
JSONObject json = null;
try {
json = array.getJSONObject(i);
//Adding data to the superhero object
p.setName(json.getString(ConfigPlan.KEY_PLAN_NAME));
p.setAmount(json.getString(ConfigPlan.KEY_PLAN_AMOUNT));
p.setDuration(json.getString(ConfigPlan.KEY_PLAN_DURATION));
p.setContacts(json.getString(ConfigPlan.KEY_PLAN_CONTACTS));
} catch (JSONException e) {
e.printStackTrace();
}
//Adding the superhero object to the list
planList.add(p);
}
}
}
Below is Adapter Class
public class PlanAdapter extends RecyclerView.Adapter<PlanAdapter.MyViewHolder> {
private List<Plan> planList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView plan_name, plan_duration, plan_contact, plan_amount;
public Button subscribeButton;
public MyViewHolder(View view) {
super(view);
plan_name = (TextView) view.findViewById(R.id.planName);
plan_duration = (TextView)view.findViewById(R.id.planDuration);
plan_contact = (TextView) view.findViewById(R.id.planContacts);
plan_amount = (TextView) view.findViewById(R.id.planAmount);
subscribeButton = (Button) view.findViewById(R.id.subscribeButton);
}
}
public PlanAdapter(List<Plan> planList) {
this.planList = planList;
}
#Override
public PlanAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.plan_activity_item, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(PlanAdapter.MyViewHolder holder, int position) {
Plan plan = planList.get(position);
holder.plan_name.setText(plan.getName());
holder.plan_amount.setText(plan.getAmount());
holder.plan_contact.setText(plan.getContacts());
holder.plan_duration.setText(plan.getDuration());
}
#Override
public int getItemCount() {
return 0;
}
}
I think you might not have initialized requestQueue object of a class RequestQueue (as per your shared error image).
Please update adapter on list, after you done with parsing of code. You have to put "Adapter" Code in "OnResponse()" method. After parsing code.
not have initialized requestQueue object of a class RequestQueue
you forgot to pAdapter.notifyDataSetChanged(); after adding data in your planList Arraylist
change this in your adapter class
Change in getItemCount() method
#Override
public int getItemCount() {
return planList.size;
}

sharedpreference return whole list not the one seleected in card

I have two activities one is "products" and the other is "cart", I used sharedpreferences to save the selected product and display it in the cart activity, the problem is when I press on add to cart the whole list of products is displayed not just the selected product
my products Adapter
public class productsAdapter extends RecyclerView.Adapter<productsAdapter.MyViewHolder> {
private Context mContext;
private List<products> productList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title, count;
public ImageView thumbnail, cart;
private Context context;
public MyViewHolder(View view) {
super(view);
context = itemView.getContext();
title = (TextView) view.findViewById(R.id.title);
count = (TextView) view.findViewById(R.id.count);
thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
cart = (ImageView) view.findViewById(R.id.cart);
}
}
public productsAdapter(Context mContext, List<products> productList) {
this.mContext = mContext;
this.productList = productList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.products_card, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final products p = productList.get(position);
holder.title.setText(p.getName());
holder.count.setText(p.getPrice() + "L.E");
Glide.with(mContext).load(p.getThumbnail()).into(holder.thumbnail);
holder.thumbnail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), product_details.class);
Bundle bundle = new Bundle();
bundle.putString("img", p.getThumbnail());
bundle.putString("name", p.getName());
bundle.putInt("price", p.getPrice());
intent.putExtras(bundle);
v.getContext().startActivity(intent);
}
});
holder.cart.setImageResource(R.drawable.ic_shopping_cart_black_24dp);
holder.cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.cart.setImageResource(R.drawable.ic_add_cart);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mContext);
SharedPreferences.Editor editor = preferences.edit();
Gson gson = new Gson();
String jsonFavorites = gson.toJson(productList);
editor.putString(FAVORITES, jsonFavorites);
editor.commit();
}
});
}
public int getItemCount() {
return productList.size();
}
}
my cart activity
public class CartActivity extends AppCompatActivity {
Button l;
ImageView imv;
Toolbar t;
RecyclerView rv;
RecyclerView.LayoutManager layoutmanager;
RecyclerView.Adapter adapter;
List<products> cartitems;
ArrayList<products> selected_items_list = new ArrayList<>();
SharedPreference sharedPreference;
public static final String MyPREFERENCES = "MyPrefs";
int countt = 0;
boolean edit_mode = false;
TextView counterr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
rv = (RecyclerView) findViewById(R.id.mycartrecycler);
layoutmanager = new LinearLayoutManager(this);
rv.setLayoutManager(layoutmanager);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String jsonFavorites = preferences.getString(FAVORITES, null);
Gson gson = new Gson();
products[] favoriteItems = gson.fromJson(jsonFavorites,
products[].class);
cartitems = Arrays.asList(favoriteItems);
cartitems = new ArrayList<products>(cartitems);
adapter = new CartAdapter(cartitems, CartActivity.this);
rv.setAdapter(adapter);
}
}
Because you add the whole list in sharedpreferences.. look at below
you did this...
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mContext);
SharedPreferences.Editor editor = preferences.edit();
Gson gson = new Gson();
String jsonFavorites = gson.toJson(productList);
1) if you want the specific selected result then you have to make a pojo class of product with the contain details like
public TextView title, count;
public ImageView thumbnail, cart;
private Context context;
and make getter and setter method of all fields.
in onclick method of cart,you have to pass that pojo class and get that class in your cart activity. that's how you can get your desire output.
2) the second way to add all details as a field of sharedpreferences like
editor.putString("title",title.getText().toString());
and set all count and thumbnail as an value.
I hope it will help you...
You are saving productList in SharedPreference.
Try like this
final Product product = productList.get(position);
// Some other code
holder.cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.cart.setImageResource(R.drawable.ic_add_cart);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mContext);
SharedPreferences.Editor editor = preferences.edit();
Gson gson = new Gson();
String jsonFavorites = gson.toJson(product);
editor.putString(FAVORITES, jsonFavorites);
editor.commit();
}
});
In CartActivity
Gson gson = new Gson();
Product product = gson.fromJson(jsonFavorites,
Product.class);

How to fetch data from json in android and display in RecyclerView?

I am making an android app to fetch JSON data from URL and then showing it in a RecyclerView.
My JSON data
[{"email":"abc#gmail.com","photo":"http:\/\/www.example.com\/x.jpg","bookname":"one","price":"30","num":"3","avg":"3.9","author":"none"}]
but only bookname and photo keys values are fetching. Other parameters are empty but my code is correct because if it is wrong than even bookname shouldn't fetch.
My code is:
public class dashBoard extends AppCompatActivity {
private List<myDash> dash;
private Toolbar mToolbar;
Button read;
//Creating Views
int temp=0;
float starts=0;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
public String ratenumS,numberS;
public String bookName,price,rating;
private RequestQueue requestQueue;
String mail_one;
private int requestCount = 1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dash_bord);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
//Initializing our superheroes list
dash = new ArrayList<>();
requestQueue = Volley.newRequestQueue(this);
getDash();
//Adding an scroll change listener to recyclerview
recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
getDash();
}
});
//initializing our adapter
adapter = new dashCard(dash, this);
//Adding adapter to recyclerview
recyclerView.setAdapter(adapter);
}
private JsonArrayRequest getDataFromDash(int requestCount) {
//Initializing ProgressBar
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar3);
//Displaying Progressbar
progressBar.setVisibility(View.VISIBLE);
setProgressBarIndeterminateVisibility(true);
SharedPreferences pre = PreferenceManager.getDefaultSharedPreferences(dashBoard.this);
mail_one = pre.getString("mail2", "DEFAULT VALUE");
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest("http://www.example.com/getDash.php?page="+ String.valueOf(requestCount )+"&email="+mail_one,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Calling method parseData to parse the json response
parseData(response);
//Hiding the progressbar
progressBar.setVisibility(View.GONE);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressBar.setVisibility(View.GONE);
if(temp==0) {
Toast.makeText(dashBoard.this, "No More Items Available "+bookName+"book "+price+" "+ratenumS+" "+numberS+" "+mail_one, Toast.LENGTH_SHORT).show();
temp++;
}
}
}
//Returning the request
return jsonArrayRequest;
}
private void getDash() {
//Adding the method to the queue by calling the method getDataFromServer
requestQueue.add(getDataFromDash(requestCount));
//Incrementing the request counter
requestCount++;
}
//This method will parse json data
private void parseData(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
myDash dash1 = new myDash();
JSONObject json = null;
try {
//Getting json
json = array.getJSONObject(i);
dash1.setImageUrl(json.getString("photo"));
dash1.setBook_name(json.getString("bookname"));
dash1.setNo_down(json.getString("download"));
dash1.setBook_price(json.getString("price"));
dash1.setStar_num(json.getString("num"));
dash1.setAvg_rate(Float.parseFloat(json.getString("avg")));
} catch (JSONException e) {
e.printStackTrace();
}
//Adding the superhero object to the list
dash.add(dash1);
}
//Notifying the adapter that data has been added or changed
adapter.notifyDataSetChanged();
}
Does anybody have any idea why this code is not working?
My dashCard Activity.
public class dashCard extends RecyclerView.Adapter<dashCard.ViewHolder> {
private ImageLoader imageLoader;
private Context context;
//List to store all superheroes
List<myDash> secDash1;
//Constructor of this class
public dashCard(List<myDash> secDash1, Context context){
super();
//Getting all superheroes
this.secDash1 = secDash1;
this.context = context;
}
//In
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.dash_bord, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final myDash secDash = secDash1.get(position);
imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
imageLoader.get(secDash.getImageUrl(),ImageLoader.getImageListener(holder.imageView, R.drawable.image, android.R.drawable.ic_dialog_alert));
holder.imageView.setImageUrl(secDash.getImageUrl(), imageLoader);
holder.bookName.setText(secDash.getBook_name());
holder.price.setText(secDash.getBook_price());
holder.numberD.setText(secDash.getStar_num());
//holder.rate.setText(Float.toString(secDash.getAvg_rate()));
holder.download.setText(secDash.getNo_down());
// holder.star.setRating(secDash.getAvg_rate());
}
public int getItemCount() {
return secDash1.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
//Views
public NetworkImageView imageView;
public TextView bookName;
public TextView price;
public TextView numberD;
public TextView rate;
RatingBar star;
public TextView download;
//Initializing Views
public ViewHolder(View itemView) {
super(itemView);
imageView = (NetworkImageView) itemView.findViewById(R.id.dashImage);
bookName = (TextView) itemView.findViewById(R.id.bookName4);
price = (TextView) itemView.findViewById(R.id.priceDash);
numberD = (TextView) itemView.findViewById(R.id.numberDash);
rate = (TextView) itemView.findViewById(R.id.ratenumDash);
star = (RatingBar) itemView.findViewById(R.id.rateDash);
download = (TextView) itemView.findViewById(R.id.download);
}
}
}
I think problem at:
dash1.setNo_down(json.getString("download"));
Your json has not download key for get value. When code run over this line, an exception has occurred and program go to catch block, other properties will never be assigned data.
I recommend that check json key are exist before get its value.
You dont have "download" as key in json because of that an exception is thrown which causes other keys to not assigned

How to get id of sqlite when recyclerview item clicked?

Here is my doubt when i click recyclerview item need to get task id which i saved in sqlite how can i do this for example when i click recycler view need to pass that value to next page and need update that value how can i do this so far what i have tried is:
public class Task extends Fragment {
private static final String MY_PREFERENCE_KEY = "yogan";
private List<Model_Task_List> model_task_lists;
private RecyclerView recyclerView;
Task_List_Adapter taskadapter;
private RecyclerView.LayoutManager layoutManager;
SharedPreferences sharedPreferences;
private RecyclerView.Adapter adapter;
RequestQueue yog;
String user_id;
AppController app;
RequestQueue queue;
String Url;
Task_DB task_db = null;
Database_SF_APP database_sf_app;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_task, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setLayoutManager(layoutManager);
if (model_task_lists == null) {
model_task_lists = new ArrayList<Model_Task_List>();
}
Calendar c = Calendar.getInstance();
System.out.println("Current time => " + c.getTime());
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = df.format(c.getTime());
int hour=c.get(Calendar.HOUR_OF_DAY);
String hours=Integer.toString(hour);
database_sf_app = new Database_SF_APP(getActivity().getBaseContext());
int count=database_sf_app.getTaskCount();
sharedPreferences = getActivity().getSharedPreferences(LoginActivity.login, 0);
user_id = sharedPreferences.getString("user_id", null);
model_task_lists=database_sf_app.getTaskListById(user_id);
taskadapter=new Task_List_Adapter(model_task_lists,getActivity());
recyclerView.setAdapter(taskadapter);
if(taskadapter!=null){
taskadapter.setOnItemClickListener(new Task_List_Adapter.data() {
#Override
public void yog(View v, int position) {
}
});
}
queue = Volley.newRequestQueue(getContext());
Url = "http://xxx.xx.x.xx/xxx/GetActivitiesByUserID.svc/getlist/Task/" + user_id +"/" +null+"/"+hours;
ConnectivityManager cn = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nf = cn.getActiveNetworkInfo();
if (nf != null && nf.isConnected()) {
Toast.makeText(getActivity(), "Network Available", Toast.LENGTH_LONG).show();
JsonObjectRequest jsonObjRequest = new JsonObjectRequest(Request.Method.POST, Url, new JSONObject(),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
String server_response = response.toString();
try {
JSONObject json_object = new JSONObject(server_response);
JSONArray json_array = new JSONArray(json_object.getString("TaskResult"));
for (int i = 0; i < json_array.length(); i++) {
Model_Task_List modelobj = new Model_Task_List();
JSONObject json_arrayJSONObject = json_array.getJSONObject(i);
modelobj.setSubject(json_arrayJSONObject.getString("Subject"));
modelobj.setTaskID(json_arrayJSONObject.getInt("TaskID"));
modelobj.setUserName(json_arrayJSONObject.getString("DueDate"));
modelobj.setTaskStatus(json_arrayJSONObject.getString("TaskStatus"));
modelobj.setUserid(json_arrayJSONObject.getString("Owner"));
database_sf_app.insertorUpdate(modelobj);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), error.toString(), Toast.LENGTH_SHORT).show();
}
});
//Creating request queue
queue.add(jsonObjRequest);
}
//sync operation
//a union b
//a server
//b local storage
//a only - insert local
//b only - send to server
//a = b do nothing
//result
//bind
return view;
}
#Override
public void onResume()
{
super.onResume();
}
#Override
public void onStop() {
super.onStop();
}
}
Here is my TaskAdapter:
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class Task_List_Adapter extends RecyclerView.Adapter<Task_List_Adapter.MyViewHolder> {
private List<Model_Task_List> dataSet;
private Context context;
private static data yog;
Model_Task_List modelTaskList=new Model_Task_List();
public void remove(int position)
{
dataSet.remove(position);
notifyItemRemoved(position);
}
public void edit(int position){
dataSet.set(position, modelTaskList);
notifyItemChanged(position);
}
public void setOnItemClickListener(data listener) {
this.yog = listener;
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
// Model_Task_List Model_Task_List=new Model_Task_List();
TextView textname;
TextView textaddress;
TextView textphnum;
TextView textdegree;
TextView textemail;
ImageView call;
data datas;
public MyViewHolder(final View itemView) {
super(itemView);
this.textname = (TextView) itemView.findViewById(R.id.subject);
this.textaddress = (TextView) itemView.findViewById(R.id.username);
this.textphnum = (TextView) itemView.findViewById(R.id.status);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(yog!=null){
yog.yog(itemView,getLayoutPosition());
}
}
});
// this.imageViewIcon = (ImageView) itemView.findViewById(R.id.imageView);
}
}
public interface data
{
void yog(View v,int position);
}
public Task_List_Adapter(List<Model_Task_List> data,Context context) {
this.dataSet = data;
this.context=context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.task_list_view, parent, false);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
TextView textViewName = holder.textname;
TextView textViewaddress = holder.textaddress;
TextView textViewphnum = holder.textphnum;
TextView textdegree = holder.textdegree;
TextView textemail=holder.textemail;
textViewName.setText("Subject:"+dataSet.get(position).getSubject());
textViewaddress.setText("DueDate"+dataSet.get(position).getUserName());
textViewphnum.setText("Status:"+dataSet.get(position).getTaskStatus());
}
#Override
public int getItemCount() {
return dataSet.size();
}
}
IS it right way to get id:
taskadapter.setOnItemClickListener(new Task_List_Adapter.data() {
#Override
public void yog(View v, int position) {
Model_Task_List model_task_list=(Model_Task_List)model_task_lists.get(position);
String yog=model_task_list.getSubject().toString();
int yogeshs=model_task_list.getTaskID();
String yogan=Integer.toString(yogeshs);
Toast.makeText(getContext(),yogan,Toast.LENGTH_SHORT).show();
}
});
}
Where i make recyclerview clickable how to get id of sqlite when i click and need to pass the value to next page
The object you are displaying in recyclerview ,
in your case that code must be in TaskAdapter,
put id in that object so when you click on it you will get that object so retrieve ID from that object
clickedObjecj.getId();
defining onClick in the onBindViewHolder is not a good pratice
the correct way is that declare a interface in the adapter class and implement it on the Activity , Using interface we can pass the value
Steps 1:
Decalre Listener for the OnItemClickListener interface
private OnItemClickListener mListener;
Step 2 : declare an interface , this interface will forward our click and data from adapter to our activity
public interface OnItemClickListener {
void onItemClick(int elementId);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
Step 3 : define the on click on ViewHolder and pass the id
//Assigning on click listener on the item and passing the ID value of the item
itemView.setOnClickListener(new View.OnClickListener() { // we can handle the click as like we do in normal
#Override
public void onClick(View v) {
if (mListener != null) {
int elementId = dataSet.get(getAdapterPosition()).getTaskID(); // Get the id of the item on that position
mListener.onItemClick(elementId); // we catch the id on the item view then pass it over the interface and then to our activity
}
}
});
Step 4: implement TaskAdapter.OnItemClickListener in the activity
Step 6: onItemClick method you will recive the value
#Override
public void onItemClick(int itemId) {
Log.d(TAG, "onItemClick: "+String.valueOf(itemId));
}
first you have to set Cursor position into clicked one
Ex: Cursor products <- storing a set of data
to set Cursor to clicked position for example a position value from RecyclerView click event
products.moveToPosition(position);
then use getString as usual
String name = products.getString(products.getColumnIndex("NAME"));
hope it may help
Hmm, my problem just change setOnClickListener to setOnLongClickListener
i declare puplic static int posit in my Adapter
Second in onBindViewHolder of Adapter, i call:
holder.layout_item.setOnLongClickListener(new View.OnLongClickListener() { #Override public boolean online(View view) { posit = arrayList.get(position).getId(); return false; } });
Next, on MainActivity, i want delete 1 object in sqlite
Boolean checkDeleteData = phamTuanVan_sqlite.deleteData(PhamTuanVan_Adapter.posit);
hope it may help

Categories

Resources