I need access to Radio Button outside onCreateView()
public void loadArray(String arrayName, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
int size = prefs.getInt(arrayName + "_size", 0);
int array[] = new int[size];
for(int i=0;i<size;i++) {
array[i] = prefs.getInt(arrayName + "_" + i, 0);
}
for(int i=0; i<size; i++) {
RadioButton radio1 = (RadioButton) findViewById(array[i]);
}
}
Of course findViewById() is not resolved here, inside onCreateView(), I can easily do rootView.findViewById()
Related
I am implementing favorite button in ListView trying from the last five days. I have created a ListView which gets the current textview text and saves it in the ArrayList (names) and if the data is already present then deletes it, works perfectly but when I close the app the ArrayList gets empty i wants to save the array list in preferences.
array declaration:
ArrayList<String> names = new ArrayList<>();
Below is the code
favoritebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick( View v) {
if (!names.contains(textView_name.getText())){
names.add((String) textView_name.getText());
for (int i=0; i<names.size(); i++) {
System.out.println(names.get(i));
favoritebutton.setBackgroundResource(R.drawable.fav_checked);
}
}
else {
System.out.println(textView_name.getText() + " is already present in the Array at index " + names.indexOf(textView_name.getText()));
int currentIndex = names.indexOf(textView_name.getText());
names.remove(currentIndex);
for (int i=0; i<names.size(); i++) {
System.out.println(names.get(i));
favoritebutton.setBackgroundResource(R.drawable.star_off);
}
}
}
});
You can use SharedPreferences to retrieve and store data like below:
private ArrayList<String> names;
private SharedPreferences sharedPreferences;
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
String favoriteItems = sharedPreferences.getString("FAVORITE_ITEMS", "");
if(favoriteItems.isEmpty())
names = new ArrayList<>();
else
names = new ArrayList<>(Arrays.asList(favoriteItems.split(",")); //Update like this
favoritebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick( View v) {
if (!names.contains(textView_name.getText())){
names.add((String) textView_name.getText());
for (int i=0; i<names.size(); i++) {
System.out.println(names.get(i));
favoritebutton.setBackgroundResource(R.drawable.fav_checked);
}
}
else {
System.out.println(textView_name.getText() + " is already present in the Array at index " + names.indexOf(textView_name.getText()));
int currentIndex = names.indexOf(textView_name.getText());
names.remove(currentIndex);
for (int i=0; i<names.size(); i++) {
System.out.println(names.get(i));
favoritebutton.setBackgroundResource(R.drawable.star_off);
}
}
sharedPreferences.edit().putString("FAVORITE_ITEMS", TextUtils.join(",", names)).apply();
}
});
You will have to save that list in preferences after each update you can use Gson lib for that which convert array list to JsonArray and JsonArray to Arraylist which will help to you...
String str = fetchFromPref();
ArrayList<String> names = covertToArrayListFromJSOnString(str);
favoritebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick( View v) {
if (!names.contains(textView_name.getText())){
names.add((String) textView_name.getText());
for (int i=0; i<names.size(); i++) {
System.out.println(names.get(i));
favoritebutton.setBackgroundResource(R.drawable.fav_checked);
}
}
else {
System.out.println(textView_name.getText() + " is already present in the Array at index " + names.indexOf(textView_name.getText()));
int currentIndex = names.indexOf(textView_name.getText());
names.remove(currentIndex);
for (int i=0; i<names.size(); i++) {
System.out.println(names.get(i));
favoritebutton.setBackgroundResource(R.drawable.star_off);
}
}
String str = convertArrayListToJson(names).toString();
saveToPrefrences(str);
}
});
I have a dynamically created radio buttons inside a RadioGroup since the values are coming from the database. I want to be able to implement setOnClickListener so I can get the whatever the selected value is. Whenever I try to click on the radio button, nothing shows up.
public void viewAll() {
Cursor res = myDb.getAllData();
LinearLayout bg = (LinearLayout) findViewById(R.id.backgroundSM);
LinearLayout display = (LinearLayout) findViewById(R.id.viewAllMsg);
final RadioButton[] rb = new RadioButton[5];
rg = new RadioGroup(this); //create the RadioGroup
rg.setOrientation(RadioGroup.VERTICAL);//or RadioGroup.VERTICAL
res.moveToFirst();
for(int i=0; i<res.getCount(); i++){
rb[i] = new RadioButton(this);
//Toast.makeText(getApplicationContext(),res.getString(1) + " ", Toast.LENGTH_LONG).show();
rb[i].setText(" " + res.getString(1)
+ " " + res.getInt(0));
rb[i].setId(i + 100);
rg.addView(rb[i]);
res.moveToNext();
}
display.addView(rg); // add the whole RadioGroup to the layout
rg.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
for(int i = 0; i < 5; i++) {
rg.removeView(rb[i]); // now the RadioButtons are in the RadioGroup
}
int id = rg.getCheckedRadioButtonId();
Toast.makeText(getApplicationContext(),id + " worked", Toast.LENGTH_LONG).show();
}
});
}
What is wrong with my code? Thank you so much for your help.
Selected position will be saved in position variable
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int id) {
for (int i = 0; i < radioGroup.getChildCount(); i++) {
if (radioGroup.getChildAt(i).getId() == id) {
position = i + 1; //+1 is used to have a start value of 1 like your example
break;
}
}
}
});
I have around 50 EditText fields and I want to get their values using a loop. Getting the values individually as below works fine:
SharedPreferences settings = getSharedPreferences(filename, 0);
SharedPreferences.Editor editor = settings.edit();
editor.clear(); //not sure if this is required
final EditText t1 = (EditText) findViewById(R.id.text1Value);
String T1 = t1.getText().toString();
editor.putstring("text1",T1);
final EditText t2 = (EditText) findViewById(R.id.text2Value);
String T2 = t2.getText().toString();
editor.putstring("text2", T2);
................................ and so on till EditText t50.
I have tried achieving this through the loop below but couldn't get it to work.
for(int x=1; x<50; x++)
{
EditText et[x] = (EditText) findViewById(R.id.text[x]Value);
String t[x] = et[x].getText().toString();
String Ref = "text" + x;
editor.putString(Ref, t[x]);
}
You can try this by creating an array of the ids of the textview and looping through the array.
Try this:
int[] ids = new int[]{R.id.text1Value,R.id.text2Value,R.id.text3Value};//and so on
int i =1;
for(int id : ids){
EditText t = (EditText) findViewById(id);
String Ref = "text" + i;
editor.putString(Ref, t.getText().toString());
i++;
}
If I assume you have all of these EditTexts inside a Layout called ll (should work for structures other than Layout too, such as a ViewGroup etc.):
ArrayList<String> values = new ArrayList<String>();
for (int i = 0; i < ll.getChildCount(); i++) {
if (ll.getChildAt(i) instanceof EditText) {
EditText et = (EditText)ll.getChildAt(i);
values.add(et.getText().toString());
}
}
My Android is a little rusty so apologies if there is something wrong with that, but should give you the general idea anyway
int[] ids = new int[]{R.id.text1Value,R.id.text2Value,R.id.text3Value};//and so on
int i =1;
for(int id : ids){
EditText t = (EditText) findViewById(id);
String Ref = "text" + i;
editor.putString(Ref, t.getText().toString());
i++;
}
private void clearScreen() {
int[] _ids = null;
_ids = new int[]{R.id.etIdTAtividade, R.id.etNomeTAtividade, R.id.etNmAtividade};
for (int i = 0; i < (_ids.length); i++) {
EditText t = (EditText) findViewById(_ids[i]);
t.setText("");
}
}
i built some text view programmatically and i want to save them in my layout but i do not know how to do it.is Shared Preferences do that ? and how ?
here is my code
LinearLayout main = (LinearLayout) findViewById(R.id.mainLayout);
String[] textArray = { weatherResult };
for (int i = 0; i < textArray.length; i++) {
TextView textView = new TextView(RestFulWebservice.this);
textView.setText(textArray[i]);
main.addView(textView);
i checked this question but it was not what i want.
Create a new TextView programmatically then display it below another TextView
You can't save textview, I think you need code like this to save texts for your textview
String[] textArray = { "" };
for (int i = 0; i < textArray.length; ++i) {
SharedPreferences sharedPreferences = getSharedPreferences(getString(R.string.app_name), MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("textview_" + i + "_text", textArray[i]);
editor.commit();
}
I have a listview with choice mode, and it working. I want to save that checked item to shared preference, then use it in another activity. But, my SharedPreferences doesn'nt save my string correct, and save another file call DATA_Preferences that i never call in my code.
The result is my Next activity get wrong value..
Here is my code that i use to save my string and call it use by another activity:
public void onClick(View v) {
SparseBooleanArray checked = listView.getCheckedItemPositions();
ArrayList<DBLokasi> selectedItems = new ArrayList<DBLokasi>();
// Item position in adapter
SharedPreferences prefs = getSharedPreferences("DATA_COOR", Context.MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = prefs.edit();
for (int i = 0; i < checked.size(); i++) {
int position = checked.keyAt(i);
// Add slected if truee
if (checked.valueAt(i))
selectedItems.add(adapter.getItem(position));
prefsEditor.putFloat(POINT_LATITUDE_KEY + i, Float.parseFloat(values.get(position).getLat()));
prefsEditor.putFloat(POINT_LONGITUDE_KEY + i, Float.parseFloat(values.get(position).getLng()));
}
prefsEditor.commit();
String[] outputStrArr = new String[selectedItems.size()];
for (int i = 0; i < selectedItems.size(); i++) {
outputStrArr[i] = String.valueOf(selectedItems.get(i));
}
Bundle b = new Bundle();
Location location = new Location("POINT_LOCATION");
for (int i = 0; i < checked.size(); i++) {
location.setLatitude(prefs.getFloat(POINT_LATITUDE_KEY + i, 0));
location.setLongitude(prefs.getFloat(POINT_LONGITUDE_KEY + i, 0));
double latitude = prefs.getFloat(POINT_LATITUDE_KEY + i, 0);
double longitude = prefs.getFloat(POINT_LONGITUDE_KEY + i, 0);
prefsEditor.commit();
b.putDouble("Latitude" + i, latitude );
b.putDouble("Longitude" + i, longitude);
}
int banyakPilih = checked.size();
b.putInt("banyakPilih", banyakPilih);
Intent intent = new Intent(getApplicationContext(),
HasilPilihanActivity.class);
// Create a bundle object
b.putStringArray("selectedItems", outputStrArr);
// Add the bundle to the intent.
intent.putExtras(b);
// start the ResultActivity
startActivity(intent);
}
I save my Prefernces in DATA_COOR.xml file name, it save my string, but i got another file that save my preference with file name DATA_Preferences in my Explorer. Some body can give me solution? Thanks before..
Define private SharedPreferences mediaPrefs = null;
put this on your constructor mediaPrefs = this.getSharedPreferences("Testing", 1);
put below method to the source:
public void storeStateString(String prefsKeys, Float prefsValue) {
SharedPreferences.Editor prefEditor = mediaPrefs.edit();
prefEditor.putFloat(prefsKeys, prefsValue);
prefEditor.commit();
}
Use this method to store the state like:
storeStateString("POINT_LATITUDE_KEY"+i,Float.parseFloat(values.get(position).getLat()));
and now you can get this preference through:
Float finalValue = mediaPrefs.getFloat("POINT_LATITUDE_KEY1","2.0l");
where 2.0l is defalut value if mediaPrefs is null;
Let me know if any issues regarding that.