I'm trying to make favorites module in my app. If user click favorite button for a radio, this radio must displayed in Favorites screen. But just last clicked radio shown in Favorites screen. I want to save more than one radios in Favorites. Where I'm doing wrong? thanks in advance.
This is favorite button in RadioFragment
add_favorites_button= (Button) view.findViewById(R.id.add_favorites_button);
add_favorites_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences settings = getActivity().getSharedPreferences("PREFS", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("radio_link", radio_play_link);
editor.putString("radio_namee", radio_name);
editor.commit();
}
});
And I'm trying to get these values and put in ArrayList in FavoritesFragment. To display received values, I sent them in textview to try.
public class FavoritesFragment extends Fragment {
public FavoritesFragment() {
// Required empty public constructor
}
TextView radio_name_txt, radio_link_txt;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_favorites, container, false);
List<String> radio_name_list = new ArrayList<>();
List<String> radio_link_list = new ArrayList<>();
SharedPreferences settings = getActivity().getSharedPreferences("PREFS",0);
radio_name_list.add(settings.getString("radio_namee", ""));
radio_link_list.add(settings.getString("radio_link", ""));
radio_name_txt = (TextView) view.findViewById(R.id.radio_name_txt);
radio_link_txt = (TextView) view.findViewById(R.id.radio_link_txt);
String a= "";
String b= "";
for (int i =0; i<radio_name_list.size(); i++) {
a = a +radio_name_list.get(i);
b = b +radio_link_list.get(i);
}
radio_name_txt.setText(a);
radio_link_txt.setText(b);
return view;
}
}
You have a lot of data and Shared Preferences is not the write option to store your data for 7000 items. Shared preference is good for easy and less frequent data storage, For your case you need to make a SQLite Database. If its totally new to your then pay a visit in Androids only Documentation Training in this link.
since you are using same key for every radio button insert it will overwrite the previous values.
You need to store values in an array and then store array in the preferneces.
Or the better way is to use sqllite database in the android to store the likes in a table.
Try displaying the values from the Lists radio_name_list and radio_link_list in a ListView:
Save the values in an Array List.
Create a ListView instead of a TextView.
Create an ArrayAdapter and set it as the adapter for your ListView.
As far as I can see you only have one TextView. Try creating a ListView instead of a TextView. It will be more organized.
editor.putString("radio_link", radio_play_link);
editor.putString("radio_namee", radio_name);
You are overwriting the favorite every time you try to add a new one, so instead of doing the above, do this:
editor.putString(radio_play_link, radio_play_link);
editor.putString(radio_name, radio_name);
So now you have a key-value pair, and you can iterate over your favorites like this:
String radioLink = "", radioKey = "";
for (Map.Entry<String, ?> entry : getSharedPreferences("PREFS",0).getAll().entrySet()) {
radioKey = entry.getKey();
radioLink = (String) entry.getValue();
}
Related
I have a spinner that have 3 values populated from array-list.
I want to save the spinner selected value to shared preferences so it can be loaded back again when the use comes back to the app. What is the correct way to do this (to avoid future problems)
1- Save position of the selection
2- Save the text of the selection
3- Get the position/text of the selection, get the corresponding enum, and save the enum name.
I am leaning towards the 3rd option incase the positions/texts changed in later updates but I am wondering what is the correct way of doing such task
Thank you
Save position (1 variant) and text (2 variant) are bad practice. Because text for your spinner items may will change in the future and their position can be changed.
I think, that you need to create enum or #TypeDef element and save it to sharedPreferences. #TypeDef is more performance but enum is more functionality (if you use Kotlin you can use sealed classes). For this solution just write mapper that can map enum to spinner item.
If you use enum, the best way is to save it name ENUM.name().
Read carefully and understand. Get the post and use at your own understanding.
Declare your spinner and sharedPreferences
public Spinner crimeType;
SharedPreferences sharedPreferencesFirstTime;
//////
sharedPreferencesFirstTime = getPreferences
(Context.MODE_PRIVATE);
String firstTime = getResources().getString(R.string.saved_first_time);
firstTimekey = sharedPreferencesFirstTime.getString
(getString(R.string.saved_first_time),
firstTime);
crimeType = v.findViewById(R.id.crimeType);
Initializing a String Array
String[] plants = new String[]{
"Antisocial behaviour",
"Arson",
"Burglary"
};
Initializing an ArrayAdapter
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<>(
getActivity(), android.R.layout.simple_spinner_item, plants
);
Sets the layout resource to create the drop down views.
/*
Parameters : resource
the layout resource defining the drop down views
*/
spinnerArrayAdapter.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
Sets the Adapter used to provide the data which backs this
/*
setAdapter(SpinnerAdapter adapter)
Sets the Adapter used to provide the data which backs this Spinner.
*/
crimeType.setAdapter(spinnerArrayAdapter);
crimeType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//Get the text content
crime_string= parent.getItemAtPosition(position).toString();
//Get Position of the crime
selectionPosition=
parent.getItemAtPosition(position);
SharedPreferences.Editor editor = sharedPref.edit();
String key2 = crime_string;
editor.putString(getString(R.string.saved_login_key), key2);
editor.apply();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
//Another interface callback
}
});
I'm Adding Some Elements Dynamically, and i'm succeed in that. Now i want to store them in SQLite or any other database option. Also i want to retrieve them too.
Here's the code of how i'm adding elements dynamically in my fragment.
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
final TableLayout tableLayout = (TableLayout) view.findViewById(R.id.tableLayout);
final ScrollView scrollView = (ScrollView) view.findViewById(R.id.scrollview);
FloatingActionButton fab = (FloatingActionButton)view.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
number = number + 1;
EditText text = new EditText(getActivity());
TextView id = new TextView(getActivity());
id.setHint(number + ". ");
text.setHint("Enter Device Name");
tableLayout.addView(id);
tableLayout.addView(text);
}
}
});
FloatingActionButton fab_save = (FloatingActionButton)view.findViewById(R.id.fab_save);
fab_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// save added elements
// save added elements
}
});
}
I want to save my data in fab_save.
You can not save your objects directly within a database.
You should save the data of the object, like text or states into corresponding sqlite table. When you need the element again, read the data from the database and generate a new view out of that data.
See the official android developer page on how to save/store data into database (in my oppinion it's quite easy to understand that even as a newbie):
https://developer.android.com/training/basics/data-storage/databases.html
To generate views out of data look at this related post:
Android - Dynamically Add Views into View
My first activity contains a listview with textviews in each cell and uses a custom adapter. So if you click on any of the items, it will open up a form activity containing textfields. The user can fill up the details and once they press the save form button the details appear on the listview. Now I am trying to add items to the list dynamically. I have created a button which when clicked adds a new instance item so that more users can register the same way. I have been able to implement these functions. However, my problem now is when i click on the newly added item and go to the form activity and click save, i am not able to see the newly added entry after i come back to the listview activity.All I see is the first entry alone. So i am guessing it gets destroyed as soon as i leave the activity. How to ensure all newly added items are not destroyed when i keep moving between these two activities.
Here is my code of the ListView Activity:
public class FormTableActivity extends Activity {
private PassengerListAdapter adapter;
Button add_passenger;
String mrzdata,ic_data,name_data;
SharedPreferences nPref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.final_display_listview);
nPref = PreferenceManager.getDefaultSharedPreferences(this);
mrzdata = nPref.getString("MRZ", "");
name_data = nPref.getString("resultData", "");
ic_data = nPref.getString("icdata", "");
final ListView lv1 = (ListView) findViewById(R.id.custom_list);
adapter = new PassengerListAdapter(this);
adapter.add(new CustomerDetails(ic_data, name_data, mrzdata));
add_passenger = (Button) findViewById(R.id.add_user);
add_passenger.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// mrzdata = "";
// name_data = "";
// ic_data = "";
adapter.add(new CustomerDetails(ic_data, name_data, mrzdata));
}
});
lv1.setAdapter(adapter);
lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Intent intent = new Intent(v.getContext(), FirstActivity.class);
startActivity(intent);
}
});
}
The easiest way to pass data between Intent is
Intent intent = new Intent(getBaseContext(), your_list_view_activity.class);
intent.putExtra("String_Key", data1);
//data1 could be an array of string where you have hold the values previously
startActivity(intent);
now on your list_view_activity
Bundle extras = getIntent().getExtras();
if (extras != null) {
String [] value = extras.getString("String_Key");
}
This way you won't get any exception but you get to populate your listView if there is data.
Another way to get data is via SharedPreference but I won't recommend it as it increases the size of the app.
You have to save these newly added items somewhere , e.g. to a SQLite database and retrieve them on create to populate the listview
You can see here if You want, the code is commented ,
here I have a listview with custom adapter with two items
the feed's name and it's url
i add URL and name using a text input dialog (with two edit text), save to DB, and retrieve them on create to populate the listview
https://github.com/enricocid/iven-feed-reader/blob/master-as/project/app/src/main/java/com/iven/lfflfeedreader/mainact/ListActivity.java
I have a static array in my code and I am trying to remember the checks on them (only 1 is checkable at a time). Say I have items 1 ,2 ,3 and 4 and 3 is checked (1 2 4 will be unchecked) and if i click done button and return to the view later I would like to see 3 checked from last time. Is there a way I CAN DO THIS?
here's my code :
public static final String[] groups = new String[] { "A", "B", "C", "D" };
public static final String[][] children = new String[][] {
{ "1" } ,
{ "2" },
{ "3"},
{ "4" }
};
View view = inflater.inflate(R.layout.fragment_dead, container, false);
categoriesList1 = (ExpandableListView)view.findViewById(R.id.categories);
String currTemplate = MainFragment.Default;
for(#SuppressWarnings("rawtypes") Map.Entry entry: map.entrySet()){
if(mTemplateId.equals(entry.getValue())){
currTemplate = (String) entry.getKey();
break;
}
}
mAdapter = new MenuExpandableListAdapter(Fragment.groups,
MainFragment.children, currTemplate, this.getActivity());
mAdapter.setSelectionListner(this);
categoriesList1.setGroupIndicator(null);
categoriesList1.setChildIndicator(null);
categoriesList1.setAdapter(mAdapter);
categoriesList1.setOnChildClickListener(mAdapter);
return view;
#Override
public void onClick(final View view) {
MainActivity activity = (MainActivity) getActivity();
switch (view.getId()) {
case R.id.button_done:
saveUserPreferences();
activity.hideSoftKeyboard(getView());
break;
default:
break;
}
You should read this to learn more about the basics of data storage, it's actually really easy :
http://developer.android.com/guide/topics/data/data-storage.html#pref
You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).
you should generate another array containing only the checked choices , and save it (by shared data or singleton class).
than when you are showing this Activity you put this values checked. so of course if this activity is opened for the first time, your checked items array will be null, so all the values would be unchecked.
to check by java , you can try this :
// also check this lines in the above example
ViewHolder holder = (ViewHolder) view.getTag();
holder.checkbox.setChecked(list.get(position).isSelected());
I have a listview populated from database and on onItemLongClick I have a context menu which I want to use it to edit and update the selected item of list. The problem is that I don' t know how to get the selected item' s values so to use them on another activity which has a form with edittexts. I want when the new activity starts, these string values to be on the apporopriate edittexts.
Here is the onItemLongClick code:
**REMOVED AND ADDED CORRECT CODE BELOW**
With the cursor I get the selected item's values and store them on Strings nameOfSong and artistOfSong.
How can I achive when the activity starts to be filled the respective edittexts?
==EDIT==
I used SharedPreferences in this way which works:
OnItemLongClick of first activity:
public boolean onItemLongClick(AdapterView<?> listview, View arg1,
final int position, final long arg3) {
//bind context menu to listview' s onIitemLongClick(touch and hold)
// Get the cursor, positioned to the corresponding row in the result set
Cursor cursor = (Cursor) listview.getItemAtPosition(position);
// Get the state's capital from this row in the database.
registerForContextMenu(listView);
openContextMenu(listView);
String nameOfSong =
cursor.getString(cursor.getColumnIndexOrThrow("songname"));
String artistOfSong =
cursor.getString(cursor.getColumnIndexOrThrow("artist"));
SharedPreferences.Editor editor = prefs.edit();
editor.putString("key1", nameOfSong);
editor.putString("key2", artistOfSong);
editor.commit();
second activity code:
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.update_item);
etEditSong = (EditText) findViewById(R.id.etEditSong);
etEditArtist = (EditText) findViewById(R.id.etEditArtist);
sEditDance = (Spinner) findViewById(R.id.sUpdDanceList);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
etEditSong.setText(prefs.getString("key1", null));
etEditArtist.setText(prefs.getString("key2", null));
}
Now I'm getting the strings on second activity. Now need to find how to update the database row from above editTexts values.
If you are starting the next activity from that long click, you can use
Intent intent = new Intent(CurrentActivity.this, DestinationActivity.class);
intent.putExtra(KEY1, nameOfSong);
intent.putExtra(KEY2, artistOfSong);
startActivity(intent);
Then, in the receiving activity
String nameOfSong = getIntent().getStringExtra(KEY1);
String artistOfSong = getIntent().getStringExtra(KEY2);
If you're starting the activity from somewhere else, you can create a global instance variable and set it in your onItemLongClick, then do the same process wherever you start your activity.
If you're using SharedPreferences just get the data in he onCreate() method of the activity that is using it.
SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_PRIVATE);
String song = myPrefs.getString("key1", null);
String artist = myPrefs.getString("key2", null);
Then just set the text for the textviews you want to display the info
TextView song1 = (TextView) findViewById(R.id.song);
song1.setText(song);
you could do that with edittext if you want but if you're just displaying the title idk why you'd make it editable