DESCRIPTION:
I have used the concept of Shared preferences GSON concept to save/un save using "heart-icon" in list view.
My Design(fig.1)
. I can display only the titles as in Retrieved titles in a listview (fig.2) but cannot retrieve the icon of heart with titles like this figure 3.
The desired output (figure 3)
PROBLEM: I have a problem while displaying image from shared preferences in listview.
Following block of code is from CustomListAdapter::
public class CustomListAdapter extends ArrayAdapter {
private final Activity context;
private final String[] infoArray;
List<Object> selectlist = new ArrayList<Object>();
public static final String PREFERENCE_NAME = "favourite";
private final SharedPreferences sharedpreferences;
List<Object> favourites;
int[] image;
public CustomListAdapter(Activity context, String[] infoArrayParam, int[] imageIds){
super(context,R.layout.listview_row , infoArrayParam);
this.context=context;
this.infoArray = infoArrayParam;
this.image = imageIds;
sharedpreferences = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
}
public View getView(final int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
final View rowView = inflater.inflate(R.layout.listview_row, parent, false);
TextView nameTextField = (TextView) rowView.findViewById(R.id.textView2);
final ImageView imageView = (ImageView) rowView.findViewById(R.id.imageView4);
imageView.setOnClickListener(new View.OnClickListener(){
#SuppressLint({"NewApi", "ResourceType"})
#Override
public void onClick(View view) {
view.setSelected(!view.isSelected());
boolean favSelected = view.isSelected();
if (favSelected) {
imageView.setImageResource(R.drawable.ic_baseline_favorite1_24);
imageView.setTag(position);
imageView.setId(R.drawable.ic_baseline_favorite1_24);
Object chk = infoArray[position];
selectlist.add(chk);
view.setSelected(true);
saveData(context, selectlist);
}
else{
imageView.setImageResource(R.drawable.ic_baseline_favorite_border_24 );
imageView.setTag(position);
imageView.setId(R.drawable.ic_baseline_favorite_border_24);
view.setSelected(false);
removeFavorite(context,selectlist);
}
}
private boolean saveData(Context context, List<Object> selectlist){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor aSharedPreferencesEdit = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(selectlist);
aSharedPreferencesEdit.putString("task list",json);
aSharedPreferencesEdit.apply();
return false;
}
private ArrayList<Object> loadData(Context context){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
Gson gson = new Gson();
String json = sharedPreferences.getString("task list", null);
System.out.println("The value of jsonnnnnnnn is " + json);
Type type = new TypeToken<List<Object>>(){}.getType();
System.out.println("The value of typpppppppppe is " + type);
return gson.fromJson(json, type);
}
public void removeFavorite(Context context, List<Object> selectlist) {
ArrayList<Object> favourites = loadData(context);
if (favourites != null) {
favourites.remove(selectlist);
saveData(context, favourites);
}
}
private boolean favOnClick(int position,View v, List<Object> selectlist){
ImageView button = (ImageView) v.findViewById(R.id.imageView4);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase(valueOf(position))){
saveData(context, selectlist);
button.setTag(position);
button.setImageResource(R.drawable.ic_baseline_favorite1_24);
}
else {
removeFavorite(context,selectlist);
button.setTag(position);
button.setImageResource(R.drawable.ic_baseline_favorite_border_24);
}
return true;
}
});
nameTextField.setText(infoArray[position]);
imageView.setImageResource(image[position]);
return rowView;
}
}
Following block of code is for DashBoard:
public class DashBoard extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {
ListView listView;
Toolbar mActionBarToolBar;
Context context;
List<Object> selectlist ;
private ArrayAdapter<Object> adapter;
int[] drawableIds = new int[]{R.drawable.ic_baseline_favorite1_24, R.drawable.ic_baseline_favorite_border_24};
String[] infoArray = {
//Listed
};
protected void onCreate(Bundle savedInstanceState) {
SharedPreferences sharedPreferences = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
CustomListAdapter listItems = new CustomListAdapter(this, infoArray,drawableIds);
listView = (ListView) findViewById(R.id.listviewId);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
//To do
}
});
listView.setAdapter(listItems);
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.navigation_notifications:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
Gson gson = new Gson();
String json = sharedPreferences.getString("task list", null);
System.out.println("The value of jsonnnnnnnn is " + json);
Type type = new TypeToken<List<Object>>(){}.getType();
System.out.println("The value of typpppppppppe is " + type);
selectlist = gson.fromJson(json, type);
if (selectlist == null){
selectlist= new ArrayList<>();
}
adapter = new ArrayAdapter<Object>(DashBoard.this,
android.R.layout.simple_list_item_1, (selectlist));
listView.setAdapter(adapter);
}
return false;
}
}
REFERENCES:How to save dynamically added items in Listview with sharedpreferences?
AnyHelp will be appreciated.
Thank You.
Related
I have an ArrayList that keeps getting overwritten instead of adding new values to the list. I'm not recreating the list each time its only getting made once. If I add the details in manually that data doesn't get overwritten but when I try to add per the method populate data it doesn't stay. so I'm not sure as to what the issue is. Here is my full Main Activity class where everything goes down.
public class MainActivity extends AppCompatActivity {
ListView listView;
Button button;
public static final String PREFS_NAME = "MyPreferencesFile";
String date_out,date_in;
String part_number,serial_number;
int employee_number;
Context context;
ArrayList<Toolinfo> toolinfos = new ArrayList<>();
String currentDateandTime;
Toolinfo tool1;
public static String TAG = "Main";
ToolListAdapter myadapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myadapter = new ToolListAdapter(this,R.layout.logrowlayout,toolinfos );
button = findViewById(R.id.button);
listView = findViewById(R.id.listview);
listView.setAdapter(myadapter);
loadData();
//Toolinfo too = new Toolinfo("part number","serial number",333,"date","out");
// Toolinfo too1 = new Toolinfo("part number","serial number",333,"date","out");
// toolinfos.add(too);
// toolinfos.add(too1);
for (int i = 0; i < toolinfos.size() ; i++) {
Log.d(TAG, "onCreate: tools:" + toolinfos.get(i).getPart_number());
}
Intent getData = getIntent();
if(getData.hasExtra("part number")&& getData.hasExtra("serial number") && getData.hasExtra("employee number")) {
final String part_number = getData.getStringExtra("part number");
showToast("has extras");
String serial_number = getData.getStringExtra("serial number");
showToast(serial_number);
int employee_number = getData.getIntExtra("employee number", 0);
populateData(part_number,serial_number,employee_number,date_out,"out");
}else {
showToast("info not present");
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addTool();
}
});
}
public void populateData(String part_number,String serial_number,int employee_number, String date_out, String date_in) {
//loadData();
SimpleDateFormat sdf = new SimpleDateFormat("MMdd");
String currentDateandTime = sdf.format(new Date());
Toolinfo tool = new Toolinfo(part_number, serial_number, employee_number, currentDateandTime, "out");
myadapter.notifyDataSetChanged();
for (int i = 0; i < 1 ; i++) {
//Log.d(TAG, "onCreate: tools:" + toolinfos.get(i).getPart_number());
toolinfos.add(tool);
}
saveData(tool);
}
private void saveData(Toolinfo tool) {
SharedPreferences preferences = getSharedPreferences("Shared prefs", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
Gson gson = new Gson();
String json = gson.toJson(tool);
editor.putString("toolobj",json);
showToast(json);
editor.commit();
editor.apply();
showToast("Data Saved");
}
private void loadData(){
SharedPreferences preferences = getSharedPreferences("Shared prefs", MODE_PRIVATE);
Gson gson = new Gson();
String json = preferences.getString("toolobj","");
if (json.isEmpty()){
showToast("no data");
}else {
Toolinfo tool1 = gson.fromJson(json, Toolinfo.class);
if (tool1 != null)
toolinfos.add(tool1);
else{
showToast("Object is null ");
}
}
}
private void addTool(){
Intent i = new Intent(MainActivity.this,Toolsignout.class);
startActivity(i);
//saveData(tool1);
}
public void showToast(String msg){
Toast.makeText(this,msg,Toast.LENGTH_LONG).show();
}
#Override
protected void onResume() {
// loadData();
super.onResume();
}
}
here is the arrayadapter class
public class ToolListAdapter extends ArrayAdapter<Toolinfo> {
private Context mcontext;
int mResource;
ArrayList<Toolinfo> objects;
public ToolListAdapter(Context context, int resource, ArrayList<Toolinfo> objects) {
super(context, resource, objects);
mcontext = context;
mResource = resource;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
String part_number = getItem(position).getPart_number();
String serial_number = getItem(position).getSerial_number();
int employee_number = getItem(position).getEmployee_nummber();
String date_out = getItem(position).getOut_time();
String date_in = getItem(position).getIn_time();
Toolinfo toolinfo = new Toolinfo(part_number,serial_number,employee_number,date_out,date_in);
LayoutInflater layoutInflater = LayoutInflater.from(mcontext);
convertView = layoutInflater.inflate(mResource,parent,false);
TextView parnum = (TextView)convertView.findViewById(R.id.patnum);
TextView sernum = (TextView)convertView.findViewById(R.id.sernum);
TextView empnum = (TextView)convertView.findViewById(R.id.empnum);
TextView timeout = (TextView)convertView.findViewById(R.id.timeout);
TextView timein = (TextView)convertView.findViewById(R.id.timein);
parnum.setText(part_number);
sernum.setText(serial_number);
empnum.setText(String.valueOf(employee_number));
timeout.setText((date_out));
timein.setText((date_in));
return convertView;
}
}
in your Adapter make the following changes
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
// **added the if else condition**
View listItem = convertView;
if (listItem == null)
{
LayoutInflater layoutInflater = LayoutInflater.from(mcontext);
convertView = layoutInflater.inflate(mResource,parent,false);
}
String part_number = getItem(position).getPart_number();
String serial_number = getItem(position).getSerial_number();
int employee_number = getItem(position).getEmployee_nummber();
String date_out = getItem(position).getOut_time();
String date_in = getItem(position).getIn_time();
Toolinfo toolinfo = new Toolinfo(part_number,serial_number,employee_number,date_out,date_in);
TextView parnum = (TextView)convertView.findViewById(R.id.patnum);
TextView sernum = (TextView)convertView.findViewById(R.id.sernum);
TextView empnum = (TextView)convertView.findViewById(R.id.empnum);
TextView timeout = (TextView)convertView.findViewById(R.id.timeout);
TextView timein = (TextView)convertView.findViewById(R.id.timein);
parnum.setText(part_number);
sernum.setText(serial_number);
empnum.setText(String.valueOf(employee_number));
timeout.setText((date_out));
timein.setText((date_in));
return convertView;
}
I just put your Inflater inside the if Statement
View listItem = convertView;
if (listItem == null)
{
LayoutInflater layoutInflater = LayoutInflater.from(mcontext);
convertView = layoutInflater.inflate(mResource,parent,false);
}
Although your code is not easy to read, I found that in populateData() you do something inexplicable:
Toolinfo tool = new Toolinfo(part_number, serial_number, employee_number, currentDateandTime, "out");
myadapter.notifyDataSetChanged();
for (int i = 0; i < 1 ; i++) {
//Log.d(TAG, "onCreate: tools:" + toolinfos.get(i).getPart_number());
toolinfos.add(tool);
}
why do you use a for loop to add 1 element? and myadapter.notifyDataSetChanged(); should be called after the addition:
Toolinfo tool = new Toolinfo(part_number, serial_number, employee_number, currentDateandTime, "out");
toolinfos.add(tool);
myadapter.notifyDataSetChanged();
I need to save values from the checkbox to shared preferences so that even after exiting, the checked boxes are still checked. Could anyone please show me how to solve this issue?
public class MainActivity extends Activity implements AdapterView.OnItemClickListener {
ListView listView;
ArrayAdapter<Model> adapter;
List<Model> list = new ArrayList<Model>();
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.my_list);
adapter = new MyAdapter(this,getModel());
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
TextView label = (TextView) v.getTag(R.id.label);
CheckBox checkbox = (CheckBox) v.getTag(R.id.check);
Toast.makeText(v.getContext(), label.getText().toString() + " " + isCheckedOrNot(checkbox), Toast.LENGTH_LONG).show();
}
private String isCheckedOrNot(CheckBox checkbox) {
if(checkbox.isChecked())
return "is checked";
else
return "is not checked";
}
private List<Model> getModel() {
list.add(new Model("1"));
list.add(new Model("2"));
list.add(new Model("3"));
return list;
}
}
I made this class, use it:
public class SavePreferences {
private final static String MYAPP_PREFERENCES = "MyAppPreferences";
public void savePreferencesData(View view, String KEY, String TEXT) {
SharedPreferences prefs = view.getContext().getSharedPreferences(MYAPP_PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
if (TEXT != null && KEY != null) {
editor.putString(KEY, TEXT);
editor.commit();
}
}
private String loadPreferencesData(View view, String KEY){
SharedPreferences prefs = view.getContext().getSharedPreferences(MYAPP_PREFERENCES, Context.MODE_PRIVATE);
String data = prefs.getString(KEY, "No Data!");
return data;
}
}
And then:
savePreferencesData(View, "CheckBox1", "true");
This is my list of songs from the NewList.class: http://postimg.org/image/uieab0wuv/ and i want in another activity to have a favorite list with the songs i get when the star button is long-pressed .
I used this tutorial(http://androidopentutorials.com/android-how-to-store-list-of-values-in-sharedpreferences/) to adapt my project but it doesn't work for an ArrayList
**the activity which generates the list **:
public class NewList extends Activity implements
AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {
public static final String ARG_ITEM_ID = "product_list";
Activity activity;
ListView productListView;
ArrayList<Track> tracks;
SharedPreference sharedPreference;
private ListView newListView;
private EditText inputSearch;
private int TRACK_POSITION;
private AdapterExploreListView adapterExploreListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_explore_music);
newListView = (ListView) findViewById(R.id.newListView);
Bundle extras = getIntent().getExtras();
int temp = extras.getInt("id");
TextView mTextView = (TextView) findViewById(R.id.title_genre);
mTextView.setText(Consts.genresArray[temp]);
fillListWithStyle(Consts.genresArray[temp]);
newListView.setOnItemClickListener(this);
newListView.setOnItemLongClickListener(this);
Toast.makeText(getApplicationContext(),
"Position :" + temp, Toast.LENGTH_LONG)
.show();
}
private void fillListWithStyle(final String style)
{
new AsyncTask<Void,Void,ArrayList<Track>>()
{
#Override
protected ArrayList<Track> doInBackground(Void... voids) {
JsonParser parser = new JsonParser();
String encodedURL="";
try {
encodedURL = URLEncoder.encode(style, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return parser.getTracksForUrl(Consts.url1 + encodedURL + Consts.url2, "tracks");
}
#Override
protected void onPostExecute(ArrayList<Track> tracks) {
super.onPostExecute(tracks);
DataHolder.getInstance().setTracks(tracks);
adapterExploreListView = new AdapterExploreListView(NewList.this, tracks);
newListView.setAdapter(adapterExploreListView);
}
}.execute();
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(this, PlayerActivity.class);
intent.putExtra(PlayerActivity.TRACK_POSITION, i);
startActivityForResult(intent, 1);
TRACK_POSITION=i;
}
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View view,
int position, long arg3) {
ImageView button = (ImageView) view.findViewById(R.id.favbutton);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(activity, tracks.get(position));
Toast.makeText(activity,
activity.getResources().getString(R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.favoritespic);
} else {
sharedPreference.removeFavorite(activity, tracks.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.favoritespicg);
Toast.makeText(activity,
activity.getResources().getString(R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
return true;
}
}
the adapter
public class AdapterExploreListView extends ArrayAdapter<Track> {
private Context context;
ArrayList<Track> tracks;
SharedPreference sharedPreference;
public AdapterExploreListView(Context context, ArrayList<Track> tracks) {
super(context, R.layout.row_list_explore, tracks);
this.context = context;
this.tracks = new ArrayList<>();
this.tracks = tracks;
sharedPreference = new SharedPreference();
}
#Override
public int getCount() {
return tracks.size();
}
#Override
public Track getItem(int position) {
return tracks.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View rowView = view;
// reuse views
if (rowView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
rowView = inflater.inflate(R.layout.row_list_explore, null);
// configure view holder
ViewHolder viewHolder = new ViewHolder();
viewHolder.title = (TextView) rowView.findViewById(R.id.titleTextView);
viewHolder.userName = (TextView) rowView.findViewById(R.id.userNameTextView);
viewHolder.favoriteImg = (ImageView) rowView.findViewById(R.id.favbutton);
rowView.setTag(viewHolder);
}
// fill data
final ViewHolder holder = (ViewHolder) rowView.getTag();
Track track = tracks.get(i);
holder.title.setText(track.getTitle());
holder.userName.setText(track.getUsername());
if (checkFavoriteItem(track)) {
holder.favoriteImg.setImageResource(R.drawable.favoritespic);
holder.favoriteImg.setTag("red");
} else {
holder.favoriteImg.setImageResource(R.drawable.favoritespicg);
holder.favoriteImg.setTag("grey");
}
return rowView;
}
static class ViewHolder {
TextView title;
TextView userName;
ImageView favoriteImg;
}
/*Checks whether a particular product exists in SharedPreferences*/
public boolean checkFavoriteItem(Track checkProduct) {
boolean check = false;
List<Track> favorites = sharedPreference.getFavorites(context);
if (favorites != null) {
for (Track track : favorites) {
if (track.equals(checkProduct)) {
check = true;
break;
}
}
}
return check;
}
#Override
public void add(Track track) {
super.add(track);
tracks.add(track);
notifyDataSetChanged();
}
#Override
public void remove(Track track) {
super.remove(track);
tracks.remove(track);
notifyDataSetChanged();
}
}
**the SharedPreference class **
public class SharedPreference {
public static final String PREFS_NAME = "PRODUCT_APP";
public static final String FAVORITES = "Product_Favorite";
public SharedPreference() {
super();
}
// This four methods are used for maintaining favorites.
public void saveFavorites(Context context, ArrayList<Track> 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, Track track) {
ArrayList<Track> favorites = getFavorites(context);
if (favorites == null)
favorites = new ArrayList<Track>();
favorites.add(track);
saveFavorites(context, favorites);
}
public void removeFavorite(Context context, Track track) {
ArrayList<Track> favorites = getFavorites(context);
if (favorites != null) {
favorites.remove(track);
saveFavorites(context, favorites);
}
}
public ArrayList<Track> getFavorites(Context context) {
SharedPreferences settings;
ArrayList<Track> favorites;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
Gson gson = new Gson();
Track[] favoriteItems = gson.fromJson(jsonFavorites,
Track[].class);
favorites = (ArrayList<Track>) Arrays.asList(favoriteItems);
favorites = new ArrayList<Track>(favorites);
} else
return null;
return (ArrayList<Track>) favorites;
}
}
and the activity where i want to generate my list of favorites
public class ForthActivity extends Activity {
SharedPreference sharedPreference;
ArrayList<Track> favorites;
ListView favoriteList;
AdapterExploreListView adapterExploreListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.forthact);
// Get favorite items from SharedPreferences.
sharedPreference = new SharedPreference();
favorites = sharedPreference.getFavorites(ForthActivity.this);
if (favorites == null) {
} else {
if (favorites.size() == 0) {
}
favoriteList = (ListView) findViewById(R.id.forthlistview);
if (favorites != null) {
adapterExploreListView = new AdapterExploreListView(ForthActivity.this, favorites);
favoriteList.setAdapter(adapterExploreListView);
favoriteList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View arg1,
int position, long arg3) {
}
});
favoriteList
.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(
AdapterView<?> parent, View view,
int position, long id) {
ImageView button = (ImageView) view
.findViewById(R.id.favbutton);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(ForthActivity.this,
favorites.get(position));
Toast.makeText(
ForthActivity.this,
ForthActivity.this.getResources().getString(
R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.favoritespic);
} else {
sharedPreference.removeFavorite(ForthActivity.this,
favorites.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.favoritespicg);
adapterExploreListView.remove(favorites
.get(position));
Toast.makeText(
ForthActivity.this,
ForthActivity.this.getResources().getString(
R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
return true;
}
});
}
}
}
}
Please help me .Thank you !
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View view,
int position, long arg3) {
ImageView button = (ImageView) view.findViewById(R.id.favbutton);
sharedPreference = new SharedPreference();
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(NewList.this, tracks.get(position));
Toast.makeText(NewList.this,
NewList.this.getResources().getString(R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.favoritespic);
} else {
sharedPreference.removeFavorite(NewList.this, tracks.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.favoritespicg);
Toast.makeText(NewList.this,
NewList.this.getResources().getString(R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
return true;
}
and this code
private void fillListWithStyle(final String style)
{
new AsyncTask<Void,Void,ArrayList<Track>>()
{
#Override
protected ArrayList<Track> doInBackground(Void... voids) {
JsonParser parser = new JsonParser();
String encodedURL="";
try {
encodedURL = URLEncoder.encode(style, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return parser.getTracksForUrl(Consts.url1 + encodedURL + Consts.url2, "tracks");
}
#Override
protected void onPostExecute(ArrayList<Track> trackss) {
super.onPostExecute(trackss);
DataHolder.getInstance().setTracks(trackss);
adapterExploreListView = new AdapterExploreListView(NewList.this, trackss);
tracks = trackss;
newListView.setAdapter(adapterExploreListView);
}
}.execute();
}
I solved my problem ,these are the edits .I hope it will help someone else !
on the new list .class
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View view,
int position, long arg3) {
TextView textView4 = (TextView)view.findViewById(R.id.titleTextView);
TextView textView5 = (TextView)view.findViewById(R.id.userNameTextView);
n =textView4.getText().toString();
m=textView5.getText().toString();
MyObject=new CustomObject(n,m);
sharedPreference = new SharedPreference();
sharedPreference.addFavorite(NewList.this, MyObject);
Toast.makeText(NewList.this,
NewList.this.getResources().getString(R.string.add_favr),
Toast.LENGTH_SHORT).show();
return true;
}
}
the favorites activity *
public class FavActivity extends Activity {
ListView lv;
SharedPreference sharedPreference;
List<CustomObject> favorites;
ProductListAdapter productListAdapter;
Activity context = this;
public static final String FAVORITES = "Favorite";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.forthact);
sharedPreference = new SharedPreference();
favorites = sharedPreference.getFavorites(context);
lv = (ListView) findViewById(R.id.forthlistview);
fillFavoriteList();
}
private void fillFavoriteList() {
if (favorites != null) {
productListAdapter = new ProductListAdapter(ForthActivity.this, favorites);
lv.setAdapter(productListAdapter);
productListAdapter.notifyDataSetChanged();
}
}
}
the SharedPreferences class
public class SharedPreference {
public static final String PREFS_NAME = "PRODUCT_APP";
public static final String FAVORITES = "Product_Favorite";
public SharedPreference() {
super();
}
// This four methods are used for maintaining favorites.
public void saveFavorites(Context context, List<CustomObject> 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 void addFavorite(Context context, CustomObject product) {
List<CustomObject> favorites = getFavorites(context);
String s=product.getProp1();
if (favorites == null)
favorites = new ArrayList<CustomObject>();
favorites.add(product);
saveFavorites(context, favorites);
}
public void removeFavorite(Context context, CustomObject product) {
ArrayList<CustomObject> favorites = getFavorites(context);
if (favorites != null) {
favorites.remove(product);
saveFavorites(context, favorites);
}
}
public ArrayList<CustomObject> getFavorites(Context context) {
SharedPreferences settings;
List<CustomObject> favorites;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
Gson gson = new Gson();
CustomObject[] favoriteItems = gson.fromJson(jsonFavorites,
CustomObject[].class);
favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList<CustomObject>(favorites);
} else
return null;
return (ArrayList<CustomObject>) favorites;
}
}
I am storing values in ArrayList and pass it to using bundle to next Fragment, and there I set values to my TextView, till here it works fine, now when go to another page and proceed to app and come back again to that Fragment, my all data goes, so I am trying to store it in preferences but preference don't allow to access ArrayList, following is my code
public class Add_to_cart extends Fragment {
private Button continue_shopping;
private Button checkout;
ListView list;
private TextView _decrease,mBTIncrement,_value;
private CustomListAdapter adapter;
private ArrayList<String> alst;
private ArrayList<String> alstimg;
private ArrayList<String> alstprc;
private String bname;
private ArrayList<String> alsttitle;
private ArrayList<String> alsttype;
public static ArrayList<String> static_Alst;
public Add_to_cart(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.list_view_addtocart, container, false);
alst=new ArrayList<String>();
alstimg=new ArrayList<String>();
Bundle bundle = this.getArguments();
alst = bundle.getStringArrayList("prducts_id");
alsttype = bundle.getStringArrayList("prducts_type");
alstimg=bundle.getStringArrayList("prducts_imgs");
alsttitle=bundle.getStringArrayList("prducts_title");
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
System.out.println("TEst--" + alst);
// Toast.makeText(getActivity(),"Testing"+alstimg,Toast.LENGTH_LONG).show();
list=(ListView)rootView.findViewById(R.id.list_addtocart);
adapter = new CustomListAdapter(getActivity(),alst,alstimg,alsttitle,alsttype);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
// TODO Auto-generated method stub
}
});
return rootView;
}
public class CustomListAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> listData;
private ArrayList<String> listDataimg;
private ArrayList<String> listDatatitle;
private ArrayList<String> listDatatype;
private AQuery aQuery;
String dollars="\u0024";
public CustomListAdapter(Context context,ArrayList<String> listData,ArrayList<String> listDataimg,ArrayList<String> listDatatitle,ArrayList<String> listDatatype) {
this.context = context;
this.listData=listData;
this.listDataimg=listDataimg;
this.listDatatitle=listDatatitle;
this.listDatatype=listDatatype;
aQuery = new AQuery(this.context);
}
public void save_User_To_Shared_Prefs(Context context) {
SharedPreferences appSharedPrefs = PreferenceManager
.getDefaultSharedPreferences(context.getApplicationContext());
SharedPreferences.Editor prefsEditor = appSharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(listData);
Add_to_cart.static_Alst=listData;
prefsEditor.putString("user", json);
prefsEditor.commit();
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(getActivity()).inflate(R.layout.list_item_addtocart, null);
holder.propic = (ImageView) convertView.findViewById(R.id.img_addtocart);
holder.txtproname = (TextView) convertView.findViewById(R.id.proname_addtocart);
holder.txtprofilecast = (TextView) convertView.findViewById(R.id.proprice_addtocart);
holder.txtsize = (TextView) convertView.findViewById(R.id.txt_size);
_decrease = (TextView) convertView.findViewById(R.id.minuss_addtocart);
mBTIncrement = (TextView) convertView.findViewById(R.id.plus_addtocart);
_value = (EditText)convertView.findViewById(R.id.edt_procount_addtocart);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
mBTIncrement.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
increment();
}
});
_decrease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
decrement();
}
});
holder.txtprofilecast.setText(dollars+listData.get(position));
holder.txtproname.setText(listDatatitle.get(position));
holder.txtsize.setText(listDatatype.get(position));
System.out.println("Image ka array " + listDataimg.get(position));
//Picasso.with(mContext).load(mThumbIds[position]).centerCrop().into(imageView);
// Picasso.with(context).load(listDataimg.get(position)).into(holder.propic);
aQuery.id(holder.propic).image(listDataimg.get(position), true, true, 0, R.drawable.ic_launcher);
return convertView;
}
class ViewHolder{
ImageView propic;
TextView txtproname;
TextView txtprofilecast;
TextView txtsize;
}
}
}
Complete example of storing and retrieving arraylist in sharedpreference:http://blog.nkdroidsolutions.com/arraylist-in-sharedpreferences/
public void storeFavorites(Context context, List favorites) {
// used for store arrayList in json format
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 ArrayList loadFavorites(Context context) {
// used for retrieving arraylist from json formatted string
SharedPreferences settings;
List favorites;
settings = context.getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
Gson gson = new Gson();
BeanSampleList[] favoriteItems = gson.fromJson(jsonFavorites,BeanSampleList[].class);
favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList(favorites);
} else
return null;
return (ArrayList) favorites;
}
public void addFavorite(Context context, BeanSampleList beanSampleList) {
List favorites = loadFavorites(context);
if (favorites == null)
favorites = new ArrayList();
favorites.add(beanSampleList);
storeFavorites(context, favorites);
}
public void removeFavorite(Context context, BeanSampleList beanSampleList) {
ArrayList favorites = loadFavorites(context);
if (favorites != null) {
favorites.remove(beanSampleList);
storeFavorites(context, favorites);
}
}
Use tinydb. check following link you might get some idea.
https://github.com/kcochibili/TinyDB--Android-Shared-Preferences-Turbo
using tinydb you can store array in local db.
You can use gson:
To Save Preferences:
public void save_User_To_Shared_Prefs(Context context, List<User> users) {
SharedPreferences settings;
Editor editor;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
editor = settings.edit();
Gson gson = new Gson();
String jsonUsers = gson.toJson(users);
editor.putString(USERS, jsonUsers);
editor.commit();
}
To get Preferences:
public ArrayList<User> getUsers(Context context) {
SharedPreferences settings;
List<User> users;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(USERS)) {
String jsonUsers = settings.getString(USERS, null);
Gson gson = new Gson();
User[] userItems = gson.fromJson(jsonUsers,
User[].class);
users = Arrays.asList(userItems);
users= new ArrayList<User>(users);
} else
return null;
return (ArrayList<User>) users;
}
To add user:
public void addUser(Context context, User user) {
List<Product> favorites = getUsers(context);
if (users == null)
users = new ArrayList<User>();
users.add(user);
save_User_To_Shared_Prefs(context, users);
}
First download Gson.jar from below link and then add it to libs folder of your project
http://www.java2s.com/Code/Jar/g/Downloadgson17jar.htm
then put That ArrayList in the Class and make object of that class then you can save that object to SharedPreferences like below
public static void save_User_To_Shared_Prefs(Context context, User _USER) {
SharedPreferences appSharedPrefs = PreferenceManager
.getDefaultSharedPreferences(context.getApplicationContext());
SharedPreferences.Editor prefsEditor = appSharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(_USER);
prefsEditor.putString("user", json);
prefsEditor.commit();
}
above code is an example _USER objext contain ArrayList.
And to read the object have a look at below code
public static User get_User_From_Shared_Prefs(Context context) {
SharedPreferences appSharedPrefs = PreferenceManager
.getDefaultSharedPreferences(context.getApplicationContext());
Gson gson = new Gson();
String json = appSharedPrefs.getString("user", "");
User user = gson.fromJson(json, User.class);
return user;
}
now when you want to get the _USER object call the above function and in result you will have the object and in that you will have the ArrayList
An alternative solution (just thought of it):
If you have an array called addtos and you want to add the array to shared preferences, since the variable is represented in the dictionary as a String, you could append the array index to the end of that string.
e.g -
Storing
for(int i = 0; i<addtos.size(); i++)
prefsEditor.putString("addtos"+i, addtos.get(i));
Receiving
int i = 0;
while(true){
if(prefs.getString("addtos"+i, "")!=""){ // or whatever the default dict value is
// do something with it
i++;
}else{break;}
}
Seems ok to me, if anyone sees a problem with this, let me know.
Also, no need for ArrayLists
I have a FragmentStatePager with two EditText and a custom ListView.
The User can make two inputs and click on a Button and they will be added to the ListView but they won't be stored in the ListView.The ListView contains a ArrayList.
I want that the inputs of the EditText will be stored in that ArrayList.
Can somebody write how to do it ?
My onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.swipeview, container, false);
txtTitel = (TextView) rootView.findViewById(R.id.swipeviewtitle);
// Capture position and set to the TextViews
txtTitel.setText(titel[position]);
// Locate the ImageView in viewpager_item.xml
image = (ImageView) rootView.findViewById(R.id.swipeViewimage);
// Capture position and set to the ImageView
String title = titel[position];
Integer imageRes = TITLE_IMAGES.get(title);
if (imageRes == null) { // not found in map
image.setImageResource(0);
} else {
image.setImageResource(imageRes);
}
final ListView listView = (ListView) rootView.findViewById(R.id.listViewswipeview);
final EditText wdhedittext = (EditText) rootView.findViewById(R.id.editTextswipeView);
final EditText kgedittext = (EditText) rootView.findViewById(R.id.editText2);
final Button btnswipeview = (Button) rootView.findViewById(R.id.imagebuttonswipeview);
adapter2 = new CustomListViewAdapter2(getActivity(),
R.layout.swipeviewrowitem, rowItems);
listView.setAdapter(adapter2);
btnswipeview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View View) {
if (wdhedittext.getText().toString().matches("")) {
Toast toast = Toast.makeText(getActivity(),
"Bitte Wiederholungszahl angeben",
Toast.LENGTH_SHORT);
toast.show();
} else if (kgedittext.getText().toString().matches("")) {
final rowitem2 item = new rowitem2(wdhedittext.getText().toString() + "wdh", kgedittext.getText().toString());
adapter2.add(item);
rowItems.add(item);
} else {
final rowitem2 item = new rowitem2(wdhedittext.getText().toString() + "wdh", kgedittext.getText().toString() + "kg");
adapter2.add(item);
rowItems.add(item);
/*String name = wdhedittext.getText().toString();
int rowId = workoutDBAO2.addWorkout2(name);
HashMap rowValsSets = new HashMap();
rowValsSets.put("sets", name);
rowValsSets.put("id", rowId);
adapter3.add(rowValsSets);*/
}
}
});
rowItems = new ArrayList<rowitem2>();
return rootView;
}
CustomListViewAdapter2 and rowitem2 classes
class CustomListViewAdapter2 extends ArrayAdapter<rowitem2> {
private final ArrayList<rowitem2> items;
Context context;
public CustomListViewAdapter2(Context context, int resourceId,
ArrayList<rowitem2> items) {
super(context, resourceId, items);
this.context = context;
this.items=items;
}
public View getView(int position, View convertView, ViewGroup parent) {
rowitem2 rowItem = items.get(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = mInflater.inflate(R.layout.swipeviewrowitem, null);
TextView txtTitle = (TextView) view.findViewById(R.id.mainText2);
TextView txtDesc = (TextView) view.findViewById(R.id.textView2);
txtDesc.setText(rowItem.getDesc());
txtTitle.setText(rowItem.getTitle());
return view;
}
#Override
public boolean areAllItemsEnabled() {
return true;
}
}
}
class rowitem2 {
private String edittexttitle;
private String edittexttitle2;
public rowitem2(String title, String desc) {
this.edittexttitle = title;
this.edittexttitle2 = desc;
}
public String getTitle() {
return edittexttitle;
}
public String getDesc() {
return edittexttitle2;
}
public void setTitle(String title) {
this.edittexttitle = title;
}
#Override
public String toString() {
return edittexttitle + "\n" + edittexttitle2;
}
}
dapter2.notifyDataSetChanged() after adding the item will do the work.
You can not persist any data in the ArrayList. If you want to store them permanently, you should use a SQLite database or SharedPreferences.
Here is a good example on how to solve your problem using a SQLite database. This is useful if you plan to store and manage a lot of data.
If you do not plan on storing a lot of data, using SharedPreferences would be a neat option. For example:
//Store a String in SharedPreferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("your_key", your_string_variable);
And whenever you want to retrieve it (for instance, onResume or onCreate)
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String your_string_variable = settings.getString("your_key", "default_value");
More information regarding SharedPreferences can be found here.