I know that this question has been asked many times but I couldn't find any solution for my problem.
I have a listview with a bookmark Icon in every row, that will save my selected item into shared preferences onClick. I have no problem with scrolling my listview till I click on a single item to save into shared preferences, Then I have a glitch on scrolling and event if I remove that item from my shared preferences I'll still have that glitch. till I uninstall and reinstall the application or clear app's cache.
Adapter
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.android_hive_list_row, null);
holder.title = (TextView) convertView.findViewById(R.id.title);
holder.rating = (TextView) convertView.findViewById(R.id.rating);
holder.genre = (TextView) convertView.findViewById(R.id.genre);
holder.year = (TextView) convertView.findViewById(R.id.releaseYear);
holder.playPauseHive=(ImageView)convertView.findViewById(R.id.playPauseHive);
holder.favoriteImgHive = (ImageView) convertView.findViewById(R.id.favImageHive);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
Product m = movieItems.get(position);
holder.title.setText(m.getTitle());
holder.rating.setText("Rating: " + String.valueOf(m.getRating()));
String genreStr = "";
for (String str : m.getGenre()) {
genreStr += str + ", ";
}
genreStr = genreStr.length() > 0 ? genreStr.substring(0,genreStr.length() - 2) : genreStr;
holder.genre.setText(genreStr);
holder.year.setText(String.valueOf(m.getYear()));
holder.favoriteImgHive.setImageResource(m.getFavId());
holder.favoriteImgHive.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (callback != null) {
callback.favOnClick(position,v);;
}
}
});
if (checkFavoriteItem(m)) {
holder.favoriteImgHive.setImageResource(R.mipmap.bookmarked);
holder.favoriteImgHive.setTag("red");
notifyDataSetChanged();
} else {
holder.favoriteImgHive.setImageResource(R.mipmap.bookmark_border);
holder.favoriteImgHive.setTag("grey");
notifyDataSetChanged();
}
return convertView;
}
/*Checks whether a particular product exists in SharedPreferences*/
public boolean checkFavoriteItem(Product checkProduct) {
boolean check = false;
List<Product> favorites = sharedPreference.getFavorites(activity);
if (favorites != null) {
for (Product product: favorites) {
if (product.equals(checkProduct)) {
check = true;
notifyDataSetChanged();
break;
}
}
notifyDataSetChanged();
}
return check;
}
Shared Pref
public class SharedPreference {
public static final String PREFS_NAME = "PRODUCT_APP";
public static final String FAVORITES = "Favorite_Tones";
public SharedPreference() {
super();
}
// This four methods are used for maintaining favorites.
public void saveFavorites(Context context, List<Product> favorites) {
SharedPreferences settings;
Editor editor;
settings = context.getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
editor = settings.edit();
Gson gson = new Gson();
String jsonFavorites = gson.toJson(favorites);
editor.putString(FAVORITES, jsonFavorites);
editor.commit();
}
public void addFavorite(Context context, Product product) {
List<Product> favorites = getFavorites(context);
if (favorites == null)
favorites = new ArrayList<Product>();
favorites.add(product);
saveFavorites(context, favorites);
Log.w("addPrefLog", favorites.toString());
}
public void removeFavorite(Context context, Product product) {
ArrayList<Product> favorites = getFavorites(context);
if (favorites != null) {
favorites.remove(product);
saveFavorites(context, favorites);
}
}
public ArrayList<Product> getFavorites(Context context) {
SharedPreferences settings;
List<Product> favorites;
settings = context.getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
Gson gson = new Gson();
Product[] favoriteItems = gson.fromJson(jsonFavorites,Product[].class);
favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList<Product>(favorites);
} else
return null;
return (ArrayList<Product>) favorites;
}
}
I just fix your SharedPreference class.. avoid using commit() and avoid to initialize repeatly your sharedPreferences
public class SharedPreference {
public static final String PREFS_NAME = "PRODUCT_APP";
public static final String FAVORITES = "Favorite_Tones";
SharedPreferences settings;
SharedPreferences.Editor editor;
Gson gson = new Gson();
#SuppressLint("CommitPrefEdits")
public SharedPreference(Context context) {
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
editor = settings.edit();
}
// This four methods are used for maintaining favorites.
public void saveFavorites(List< Product > favorites) {
String jsonFavorites = gson.toJson(favorites);
editor.putString(FAVORITES, jsonFavorites);
editor.apply();
}
public void addFavorite(Product product) {
List < Product > favorites = getFavorites();
if (favorites == null)
favorites = new ArrayList < Product > ();
favorites.add(product);
saveFavorites(favorites);
Log.w("addPrefLog", favorites.toString());
}
public void removeFavorite(Product product) {
ArrayList < Product > favorites = getFavorites();
if (favorites != null) {
favorites.remove(product);
saveFavorites(favorites);
}
}
public ArrayList < Product > getFavorites() {
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
Product[] favoriteItems = gson.fromJson(jsonFavorites, Product[].class);
favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList < Product > (favorites);
} else
return null;
return (ArrayList < Product > ) favorites;
}
}
Related
I want to save this array list data in sharedpreferences and access that data in another fragment .Please Give me suggestion
Array list content given bellow
public String productname;
public String productunit;
public String productquantity;
public String productprice;
public String productdiscount;
Here is solution,
Step 1: Create a class like
SharedPreference
public static final String FAVORITES = "PRODUCTS";
private SharedPreferences settings;
private Editor editor;
public SharedPreference() {
super();
}
Now code to save ArrayList
public void saveArrayList(Context context, List<String> unread_ids) {
settings = context.getSharedPreferences(AppConfig.KEY_PREFS_NAME,
Context.MODE_PRIVATE);
editor = settings.edit();
Gson gson = new Gson();
String jsonFavorites = gson.toJson(unread_ids);
editor.putString(FAVORITES, jsonFavorites);
editor.apply();
}
Now code to get saved Arraylist
public ArrayList<String> getSavedList(Context context) {
// SharedPreferences settings;
List<String> unReadId;
settings = context.getSharedPreferences(AppConfig.KEY_PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, "");
Gson gson = new Gson();
String[] favoriteItems = gson.fromJson(jsonFavorites,
String[].class);
unReadId = Arrays.asList(favoriteItems);
unReadId = new ArrayList<>(unReadId);
} else {
return new ArrayList<String>();
}
return (ArrayList<String>) unReadId;
}
Code to save list:
sharedPreferences.saveArrayList(context, <YOUR LIST NAME>);
Now code to get your Arraylist in other Fragment
<LIST NAME> = sharedPreference.getSavedList(getActivity());
Before get and save array list you have to declare "sharedPreference" and create its object.
Hope this will help you.
I did something similar to this before Please check this code
private List<String> list; /// adding checked items to list
inside your OnCreate() add this line
list = new ArrayList<>(); /// checked items list
and to get array from model and store it local please use next.
int searchListLength = items.size();
for (int i = 0; i < searchListLength; i++) {
if (items.get(i).isChecked()) {
items.get(i).getId();
Log.d("listitem", String.valueOf("id=" + items.get(i).getId()));
list.add("id=" + items.get(i).getId());
}
}
StringBuilder stringBuilder = new StringBuilder();
for (String s : list) {
stringBuilder.append(s);
stringBuilder.append("&");
}
SharedPreferences notif_array = getSharedPreferences("items_array", Context.MODE_PRIVATE);
SharedPreferences.Editor editor_notaif = notif_array.edit();
editor_notaif.putString("id", stringBuilder.toString());
editor_notaif.apply();
Intent intent = new Intent(MainActivity.this, Filtered_Activity.class);
startActivity(intent);
Inside your another activity / fragment
private String new_result;
SharedPreferences notif_array = getSharedPreferences("items_array", Context.MODE_PRIVATE);
new_result = notif_array.getString("id", null);
I am trying when press favorite button saving Object to SharedPreferences I have done it but When I press again favorite button to Remove Object to SharedPreferences I can't do this, I got old Objects without removed Objects I shared below used code for this process.How can I do this?
Saving and Removing to Favorite Object
String tag = holder.order.getTag().toString();
if (tag.equalsIgnoreCase("deactive")) {
//order_models.add(new RetroPhoto(1,dataList.get(position).getSurname(),dataList.get(position).getName()));
sharedPreference.addFavorite(context, dataList.get(position));
//dataList.get(position).getName();
holder.order.setTag("active");
holder.order.setImageResource(R.drawable.ic_favorite);
} else {
sharedPreference.removeFavorite(context, dataList.get(position));
//dataList.get(position).getName();
//dataList.remove(dataList.get(position));
holder.order.setTag("deactive");
holder.order.setImageResource(R.drawable.ic_favorite_outline);
}
public class SharedPreference {
public static final String PREFS_NAME = "NKDROID_APP";
public static final String FAVORITES = "Favorite";
public SharedPreference() {
super();
}
public void storeFavorites(Context context, List<RetroPhoto> favorites){
SharedPreferences settings;
SharedPreferences.Editor editor;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
editor = settings.edit();
Gson gson = new Gson();
String jsonFavorites = gson.toJson(favorites);
editor.putString(FAVORITES, jsonFavorites);
editor.commit();
}
public ArrayList<RetroPhoto> loadFavorites(Context context) {
SharedPreferences settings;
List<RetroPhoto> favorites;
settings =
context.getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
Gson gson = new Gson();
RetroPhoto[] favoriteItems =
gson.fromJson(jsonFavorites,RetroPhoto[].class);
favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList<RetroPhoto>(favorites);
} else
return null;
return (ArrayList<RetroPhoto>) favorites;
}
public void addFavorite(Context context, RetroPhoto beanSampleList) {
List<RetroPhoto> favorites = loadFavorites(context);
if (favorites == null){
favorites = new ArrayList<RetroPhoto>();
}
favorites.add(beanSampleList);
storeFavorites(context, favorites);
}
public void removeFavorite(Context context, RetroPhoto beanSampleList) {
ArrayList<RetroPhoto> favorites = loadFavorites(context);
if (favorites != null) {
favorites.remove(beanSampleList);
storeFavorites(context, favorites);
}
}
}
Getting Update LoadSharedPreferences
#Override
protected void onResume() {
super.onResume();
Log.e("onResume", "onResume Called");
if(order_models != null ) {
try {order_models = sharedPreference.loadFavorites(getApplicationContext());
order_adapter = new OrderAdapter(getApplicationContext(), order_models);
recycle.setAdapter(order_adapter);
} catch (NullPointerException e) {
e.printStackTrace();
}
order_adapter.notifyDataSetChanged();
}
}
you actually just add item in SharedPreference and remove item just from your array.
for removing item from SharedPreference you should use this code
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
preferences.edit().remove("key").apply();
I'm saving my playlists as json file, but oncreate I want to load every playlist already saved.
This is my save function;
void Kaydet(PLAYLIST liste_mp3)
{
SharedPreferences appSharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this.getApplicationContext());
SharedPreferences.Editor prefsEditor = appSharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(liste_mp3);
prefsEditor.putString(liste_mp3.ad, json);
prefsEditor.commit();
}
And this is PLAYLIST class,
public class PLAYLIST
{
public String ad;
public ArrayList<MP3> liste;
public PLAYLIST(String ad1,ArrayList<MP3> liste1)
{
ad = ad1;
liste = liste1;
}
public String toString()
{
return ad;
}
public ArrayList<MP3> LISTE()
{
return liste;
}
}
This where I load specific one;
if(Yukle("A liste") != null) {
playlist.add(Yukle("A liste"));
} else { playlist.add(new PLAYLIST("A liste",a_liste)); }
and this is Load function,
PLAYLIST Yukle(String playlist_name)
{
SharedPreferences appSharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this.getApplicationContext());
Gson gson = new Gson();
String json = appSharedPrefs.getString(playlist_name, "");
PLAYLIST p = gson.fromJson(json, PLAYLIST.class);
return p;
}
I fixed my problem with that idea, I created a new function that saves names of all playlists as string arraylist, and load string arraylist of playlists' names then make a for-loop and load per playlist with name.
This is in onCreate()
ArrayList<String> yukleniyor = YukleHepsi();
if(yukleniyor != null) {
for (String isimler : yukleniyor) {
playlist.add(Yukle(isimler));
}
}
This function loads names:
ArrayList<String> YukleHepsi()
{
SharedPreferences appSharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this.getApplicationContext());
Gson gson = new Gson();
String json = appSharedPrefs.getString("isimler", "");
ArrayList<String> p = gson.fromJson(json, ArrayList.class);
return p;
}
And this function saves the names of all playlits,
void KaydetHepsi()
{
ArrayList<String> isimler = new ArrayList<String>();
for(PLAYLIST p: playlist)
{
if(p.ad != "None") {
isimler.add(p.ad);
}
}
SharedPreferences appSharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this.getApplicationContext());
SharedPreferences.Editor prefsEditor = appSharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(isimler);
prefsEditor.putString("isimler", json);
prefsEditor.commit();
}
I am trying to implement swipe to refresh in my app. When swipe to refresh is triggered, first all the data is fetched from JSON and then stored in the database. After storing the data, all the new data will be added to the top of the recyclerview. I read a few articles and only managed to find out about adding a single item at the top of the list. But in the case of my app, where more than one item may be available to show, what should I do?
Here is my code for the database table where first new post is fetched with the last post id which is shown in recyclerview:
#Override
public ArrayList<Post> getAllNewPost(int T) {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<Post> postList = null;
try {
postList = new ArrayList<Post>();
String QUERY = "SELECT * FROM " + TABLE_NAME + " INNER JOIN "+TABLE_FOLLOWER+
" ON post_table.user_id = follower.user_id WHERE follower.follow = '1' AND post_table.post_id > "+T+" ORDER BY "+POST_ID+" DESC";
Cursor cursor = db.rawQuery(QUERY, null);
if (!cursor.isLast()) {
while (cursor.moveToNext()) {
Post post = new Post();
post.setPost_id(cursor.getString(0));
Log.d("post_id",cursor.getString(0));
post.setUser_id(cursor.getString(1));
post.setUser_name(cursor.getString(2));
post.setImg_link(cursor.getString(3));
post.setPost_title(cursor.getString(4));
post.setPost_cat(cursor.getString(6));
post.setPost_time(cursor.getString(8));
postList.add(post);
}
}
db.close();
} catch (Exception e) {
Log.e("error", e + "");
}
return postList;
}
Here is array adapter of recyclerview:
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {
Context context;
ArrayList<Post> listData = new ArrayList<>();
String rpostid,ruserid,rname,rcat,rdate,rtittle,urlThumnail;
private VolleySingleton volleySingleton;
ImageLoader imageLoader = VolleySingleton.getsInstance().getImageLoad();
public PostAdapter(ArrayList<Post> postList) {
this.listData=postList;
}
public PostAdapter(Context context){
this.context = context;
}
#Override
public PostAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.post_item, viewGroup, false);
return new posts(v);
}
public class posts extends ViewHolder {
TextView tvTittle,tvPostId,tvUseId,tvName,tvCat,tvDate;
ImageView row_img;
public posts(View v) {
super(v);
tvTittle = (TextView) v.findViewById(R.id.row_cmnt);
tvPostId = (TextView) v.findViewById(R.id.row_postid);
tvUseId = (TextView) v.findViewById(R.id.row_userid);
tvName = (TextView) v.findViewById(R.id.row_name);
tvCat = (TextView) v.findViewById(R.id.row_cat);
tvDate = (TextView) v.findViewById(R.id.row_date);
row_img = (ImageView) v.findViewById(R.id.row_img);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent;
TextView text = (TextView) v.findViewById(R.id.row_postid);
String lst_txt = text.getText().toString().trim();
intent = new Intent(v.getContext(), PostView.class);
intent.putExtra("post_id", lst_txt);
v.getContext().startActivity(intent);
}
});
}
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
final posts holder = (posts) viewHolder;
Post post = listData.get(position);
rpostid = post.getPost_id();
ruserid = post.getUser_id();
rname = post.getUser_name();
rcat = post.getPost_cat();
rdate = post.getPost_time();
rtittle = post.getPost_title();
holder.tvPostId.setText(rpostid);
holder.tvUseId.setText(ruserid);
holder.tvName.setText(rname);
holder.tvCat.setText(rcat);
holder.tvDate.setText(rdate);
holder.tvTittle.setText(rtittle);
urlThumnail = post.getImg_link();
Log.d("qwerty","link of image lru: "+ urlThumnail);
if (urlThumnail != null){
imageLoader.get(urlThumnail, new ImageLoader.ImageListener() {
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
holder.row_img.setImageBitmap(response.getBitmap());
Log.d("qwerty","post attached 2");
}
#Override
public void onErrorResponse(VolleyError error) {
Log.d("qwerty","post attached 3");
}
});
}
}
#Override
public int getItemCount() {
return (null != listData ? listData.size() : 0);
}
}
And here is the code by which all the new posts will be fetched from the DB:
private ArrayList<Post> parseJSONResponse(JSONObject response) {
if (response == null || response.length() == 0) {
} else {
try {
JSONArray jsonArray = response.getJSONArray("post");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjectPOST = jsonArray.getJSONObject(i);
String post_id = jsonObjectPOST.getString(Key_post_id);
String user_id = jsonObjectPOST.getString(Key_user_id);
String user_name = jsonObjectPOST.getString(Key_user_name);
String img_link = jsonObjectPOST.getString(Key_img_link);
String post_title = jsonObjectPOST.getString(Key_post_title);
String post_desc = jsonObjectPOST.getString(Key_post_desc);
String post_exp_date = jsonObjectPOST.getString(Key_post_exp);
String post_cat = jsonObjectPOST.getString(Key_post_cat);
String post_time = jsonObjectPOST.getString(Key_post_time);
Log.d("response",post_id+" "+user_id+" "+user_name+" "+img_link);
Post postitem = new Post();
postitem.setPost_id(post_id);
postitem.setUser_id(user_id);
postitem.setUser_name(user_name);
postitem.setImg_link(img_link);
postitem.setPost_title(post_title);
postitem.setDesc(post_desc);
postitem.setEXP(post_exp_date);
postitem.setPost_cat(post_cat);
postitem.setPost_time(post_time);
if(jsonObjectPOST.has(Key_post_id) &&
jsonObjectPOST.has(Key_user_id) &&
jsonObjectPOST.has(Key_user_name) &&
jsonObjectPOST.has(Key_img_link) &&
jsonObjectPOST.has(Key_post_title) &&
jsonObjectPOST.has(Key_post_desc) &&
jsonObjectPOST.has(Key_post_exp) &&
jsonObjectPOST.has(Key_post_cat) &&
jsonObjectPOST.has(Key_post_time)){
if(!jsonObjectPOST.isNull(Key_post_id) &&
!jsonObjectPOST.isNull(Key_user_id) &&
!jsonObjectPOST.isNull(Key_user_name) &&
!jsonObjectPOST.isNull(Key_img_link) &&
!jsonObjectPOST.isNull(Key_post_title) &&
!jsonObjectPOST.isNull(Key_post_desc) &&
!jsonObjectPOST.isNull(Key_post_exp) &&
!jsonObjectPOST.isNull(Key_post_cat) &&
!jsonObjectPOST.isNull(Key_post_time)){
handler.addPost(postitem);
new CountDownTimer(2000, 1000) {
public void onTick(long millisUntilFinished) {}
public void onFinish() {
postList = handler.getAllPost();
t = Integer.parseInt(postList.get(1).getPost_id().toString().trim());
Log.d("Check", "postid: "+t);
Hpbar.setVisibility(View.INVISIBLE);
Log.d("jsonCount", String.valueOf(postList));
String AdapterData = String.valueOf(postList);
if(AdapterData.equals("[]")){
Htvnopostfound.setVisibility(View.VISIBLE);
}else{
adapter = new PostAdapter(postList);
listView.setAdapter(adapter);
}
}
}.start();
}else{
}
}else{
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return postList;
}
private ArrayList<Post> swipeJSONResponse(JSONObject response) {
if (response == null || response.length() == 0) {
} else {
try {
JSONArray jsonArray = response.getJSONArray("post");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjectPOST = jsonArray.getJSONObject(i);
String post_id = jsonObjectPOST.getString(Key_post_id);
String user_id = jsonObjectPOST.getString(Key_user_id);
String user_name = jsonObjectPOST.getString(Key_user_name);
String img_link = jsonObjectPOST.getString(Key_img_link);
String post_title = jsonObjectPOST.getString(Key_post_title);
String post_desc = jsonObjectPOST.getString(Key_post_desc);
String post_exp_date = jsonObjectPOST.getString(Key_post_exp);
String post_cat = jsonObjectPOST.getString(Key_post_cat);
String post_time = jsonObjectPOST.getString(Key_post_time);
Post postitem = new Post();
postitem.setPost_id(post_id);
postitem.setUser_id(user_id);
postitem.setUser_name(user_name);
postitem.setImg_link(img_link);
postitem.setPost_title(post_title);
postitem.setDesc(post_desc);
postitem.setEXP(post_exp_date);
postitem.setPost_cat(post_cat);
postitem.setPost_time(post_time);
if(jsonObjectPOST.has(Key_post_id) &&
jsonObjectPOST.has(Key_user_id) &&
jsonObjectPOST.has(Key_user_name) &&
jsonObjectPOST.has(Key_img_link) &&
jsonObjectPOST.has(Key_post_title) &&
jsonObjectPOST.has(Key_post_desc) &&
jsonObjectPOST.has(Key_post_exp) &&
jsonObjectPOST.has(Key_post_cat) &&
jsonObjectPOST.has(Key_post_time)){
if(!jsonObjectPOST.isNull(Key_post_id) &&
!jsonObjectPOST.isNull(Key_user_id) &&
!jsonObjectPOST.isNull(Key_user_name) &&
!jsonObjectPOST.isNull(Key_img_link) &&
!jsonObjectPOST.isNull(Key_post_title) &&
!jsonObjectPOST.isNull(Key_post_desc) &&
!jsonObjectPOST.isNull(Key_post_exp) &&
!jsonObjectPOST.isNull(Key_post_cat) &&
!jsonObjectPOST.isNull(Key_post_time)){
handler.addPost(postitem);
new CountDownTimer(2000, 1000) {
public void onTick(long millisUntilFinished) {}
public void onFinish() {
postList = handler.getAllNewPost(t);
adapter.notifyItemInserted(1);
Log.d("check","post_id "+t+" hello");
/*adapter = new PostAdapter(postList);
listView.setAdapter(adapter);
Log.d("check","post_id "+t+" hello 2");*/
Log.d("check","post_id "+t+" hello 2");
Hpbar.setVisibility(View.INVISIBLE);
swipeRefreshLayout.setRefreshing(false);
}
}.start();
}else{
}
}else{
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return postList;
}
On startup parseJSONResponse is used and for swipeToRefresh swipeJSONResponse is used. In parseJSONResponse, the last displayed post's id is stored in int t and then this int t is passed to swipeJSONResponse to get the new post.
But after refreshing, new data will not show in the list. SO, please tell me how to do so. I've read a few articles where add is used, as such:
listview.add(0, item);
But I don't know how to implement this with multiple rows of data at same time. Thanks in advance.
The correct way to update data in a listView should be:
1) create an update data method in your adapter. In your case could be like this:
public updateData(ArrayList<Post> postList) {
this.listData=postList;
notifyDataSetChanged();
}
or, if you want just append data on the top:
public addNewDataOnTop(ArrayList<Post> postList) {
this.listData.addAll(0,postList);
notifyDataSetChanged();
}
2) When you have new data to add, do not create a new adapter but just update the data
When you create the listView at the beginning you set the empty adapter:
adapter = new PostAdapter(new ArrayList());
listView.setAdapter(adapter);
When you receive the new data, you just update the adapter:
adapter.addNewDataOnTop(postList);
I hope it helped
I would insert each item at the top using:
mArrayList.add(0, item1);
notifyItemInserted(0);
mArrayList.add(0, item2);
notifyItemInserted(0);
Do the following for all your items.
I have an app that shows notification in a listview. I want these notifications to be saved so that if I open the app and see notification I can see these notifications again when I close the app and then open it. I tried this
but nothing was saved.
Another major question is how can I run this app in background? So if notification is received the app lists that notification in the listview without being opened?
My Code
public class MainActivity extends Activity {
ListView list;
CustomListAdapter adapter;
ArrayList<Model> modelList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
modelList = new ArrayList<Model>();
adapter = new CustomListAdapter(getApplicationContext(), modelList);
list=(ListView)findViewById(R.id.list);
list.setAdapter(adapter);
LocalBroadcastManager.getInstance(this).registerReceiver(onNotice, new IntentFilter("Msg"));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);//Menu Resource, Menu
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent intent = new Intent(
"android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private BroadcastReceiver onNotice= new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String pack = intent.getStringExtra("package");
String title = intent.getStringExtra("title");
String text = intent.getStringExtra("text");
//int id = intent.getIntExtra("icon",0);
Context remotePackageContext = null;
if (pack.contains("fake")){
try {
// remotePackageContext = getApplicationContext().createPackageContext(pack, 0);
// Drawable icon = remotePackageContext.getResources().getDrawable(id);
// if(icon !=null) {
// ((ImageView) findViewById(R.id.imageView)).setBackground(icon);
// }
byte[] byteArray = intent.getByteArrayExtra("icon");
Bitmap bmp = null;
if (byteArray != null) {
bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
}
Model model = new Model();
if(text.contains("") && !text.contains(" messages")) {
model.setName(title + ": " + text);
model.setImage(bmp);
if (modelList != null) {
modelList.add(model);
adapter.notifyDataSetChanged();
} else {
modelList = new ArrayList<Model>();
modelList.add(model);
adapter = new CustomListAdapter(getApplicationContext(), modelList);
list = (ListView) findViewById(R.id.list);
list.setAdapter(adapter);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
}
Make a class Cache which has the capabilities to serialize and deserialize data.
public class Cache {
private static Cache CACHE;
public static Cache get() {
if (!SharedPreferencesHelper.isCacheAvailable()) {
CACHE = new Cache();
SharedPreferencesHelper.saveCache(CACHE);
} else {
CACHE = SharedPreferencesHelper.getCache();
}
return CACHE;
}
ArrayList<Taxonomy> cachedTaxonomies;
public Cache() {
cachedTaxonomies = new ArrayList<Taxonomy>();
}
public ArrayList<Taxonomy> getCachedTaxonomies() {
return cachedTaxonomies;
}
public static String serialize(Cache cache) {
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.enableComplexMapKeySerialization().setPrettyPrinting().create();
return gson.toJson(cache);
}
public static Cache deserialize(String json) {
Type type = new TypeToken<Cache>() {
}.getType();
return new Gson().fromJson(json, type);
}
public void update() {
SharedPreferencesHelper.saveCache(this);
}
}
Here Taxonomy is a model.
Below is the class which helps you save in SharedPrefs
public class SharedPreferencesHelper {
private static final String PREFS_CACHE = "prefs_cache";
public static SharedPreferences getSharedPreferences() {
return SpreeApplication.getSharedPreferences();
}
// Cache -------------------------------------
public static boolean isCacheAvailable() {
SharedPreferences sharedPreferences = getSharedPreferences();
String json = sharedPreferences.getString(PREFS_CACHE, "");
if(json.equals("")) {
return false;
} else {
return true;
}
}
public static Cache getCache() {
SharedPreferences sharedPreferences = getSharedPreferences();
String json = sharedPreferences.getString(PREFS_CACHE, "");
if(json.equals("")) {
return null;
} else {
return Cache.deserialize(json);
}
}
public static void saveCache(Cache cache) {
saveString(PREFS_CACHE, Cache.serialize(cache));
}
// -----------------------------------------------------
private static void saveString(String prefKey, String value) {
SharedPreferences sharedPreferences = getSharedPreferences();
SharedPreferences.Editor prefEditor = sharedPreferences.edit();
prefEditor.putString(prefKey, value);
prefEditor.commit();
}
private static void saveBoolean(String prefKey, boolean value) {
SharedPreferences sharedPreferences = getSharedPreferences();
SharedPreferences.Editor prefEditor = sharedPreferences.edit();
prefEditor.putBoolean(prefKey, value);
prefEditor.commit();
}
}
To save write this :
List<Taxonomy> taxonomies = new ArrayList<Taxonomy>();
Cache cache = Cache.get();
cache.getCachedTaxonomies().clear();
cache.getCachedTaxonomies().addAll(taxonomies);
SharedPreferencesHelper.saveCache(cache);
this is my spreeapplication class which is a custom application class
Remember you have to mention in manifest if you create a custom application class
public class SpreeApplication extends Application{
private final static String DEFAULT_PREFERENCES = "spree";
private static SharedPreferences sharedPreferences;
private static Context applicationContext;
#Override
public void onCreate() {
super.onCreate();
applicationContext = this;
sharedPreferences = getSharedPreferences(DEFAULT_PREFERENCES, Context.MODE_PRIVATE);
}
public static SharedPreferences getSharedPreferences() {
return sharedPreferences;
}
public static SharedPreferences.Editor getSharedPreferencesEditor() {
return sharedPreferences.edit();
}
public static Context getContext() {
return applicationContext;
}
}