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();
}
Related
Is it possible to dynamically add text to several textview that are defined in xalm? For example, in a loop:
var textView1 = FindViewById<TextView>(Resource.Id.textView1);
var textView2 = FindViewById<TextView>(Resource.Id.textView2);
var textView3 = FindViewById<TextView>(Resource.Id.textView3);
var content = "Add me to more at one textView"
for (i = 1; i = 3; i++)
{
// add me;
}
I can easily do it as it adds textview programmatically by calling GetChildAt () in layout. Is it possible to add dynamic if textView is defined in xalm?
Say your texts ids are text1, text2, tex3, etc. Use:
for (int i=1; i<numberOfTextsViews; i++) {
int id = this.getResources().getIdentifier("text" + i, "id", getPackageName());
TextView temp = findViewById(id);
temp.setText("text you want to add to all your texts");
}
I write like this:
public TextView FindId(string resourceId)
{
var type = typeof(Resource.Id);
var field = type.GetField(resourceId);
int res = (int)field.GetRawConstantValue();
TextView tx = FindViewById<TextView>(res);
return tx;
}
and:
for (int i = 0; i <= 34; i++)
{
TextView tx = FindId($"textView_day{i}");
tx.Text = day[i];
tx.Tag = tx.Text;
tx.Click += Day_Click;
}
THX a lot Mike087 for getting me on the right track.
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 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()
i want to add the data from arraylist to sharedpreferences and retrieve the same.
but it is not working. i am getting only one value which is the last value
not all values are retrieved from shared preferences. i am getting the values from
JSONArray first the added in the arraylist.
below is my code to save the data.
JSONArray arr = new JSONArray(strServerResponse);
JSONObject jsonObj = arr.getJSONObject(0);
for (int i = 0; i < arr.length(); i++) {
pojo = new Pojo();
JSONObject jobj2 = arr.getJSONObject(i);
String tipoftheday = jobj2.optString("tipsoftheday");
ArrayList<String> tii = new ArrayList<String>();
tii.add(tipoftheday);
SharedPreferences.Editor editor = getSharedPreferences("MyPref", MODE_PRIVATE).edit();
for (int i1 = 0; i1 < tii.size(); i1++) {
editor.putString("tipoftheday", TextUtils.join(",", tii));
editor.commit();
}
}
below is the code to retrieve data from shared preferences and using setter to set the d
ata retrieved from shared preferences and adding it to list view adapter. i am not getting what is the mistake.
SharedPreferences prefs=getSharedPreferences("MyPref", MODE_PRIVATE);
String serialized = prefs.getString("tipoftheday", null);
List<String> list = Arrays.asList(TextUtils.split(serialized,","));
for(int i=0; i < list.size(); i++){
String ttt = list.get(i);
pojo.setTip(ttt);
tipsAdapter = new TipsAdapter(TipsActivity.this, tips);
tips.add(pojo);
listTips.setAdapter(tipsAdapter);
}
How to save data in shared preferences? I am getting only one value.
how to save data in shared prefernces. i am getting only one value.
Problem is not related to SharedPreferences it is related to data-source which is currently setting inside for-loop.
Set Adapter as:
for(int i=0; i < list.size(); i++){
String ttt = list.get(i);
pojo.setTip(ttt);
tips.add(pojo);
}
tipsAdapter = new TipsAdapter(TipsActivity.this, tips);
listTips.setAdapter(tipsAdapter);
Try this:
It will work:
To store data:
StringBuilder sb = new StringBuilder();
JSONArray arr = new JSONArray(strServerResponse);
JSONObject jsonObj = arr.getJSONObject(0);
for (int i = 0; i < arr.length(); i++)
{
pojo = new Pojo();
JSONObject jobj2 = arr.getJSONObject(i);
String tipoftheday = jobj2.optString("tipsoftheday");
sb.append(tipoftheday).append(",");
}
SharedPreferences.Editor editor = getSharedPreferences("MyPref", MODE_PRIVATE).edit();
editor.putString("tipoftheday", sb).commit();
To retrieve data:
String[] strArr = getSharedPreferences("MyPref", MODE_PRIVATE).getString("tipsoftheday").split(",");
You are using two for loop when you are adding values to SharedPreference. Move out the inner loop and your code will be good to get you all values of list. Add some more line to it like below code:
for (int i = 0; i < arr.length(); i++) {
pojo = new Pojo();
JSONObject jobj2 = arr.getJSONObject(i);
String tipoftheday = jobj2.optString("tipsoftheday");
ArrayList<String> tii = new ArrayList<String>();
tii.add(tipoftheday);
}
for (int i1 = 0; i1 < tii.size(); i1++) {
SharedPreferences.Editor editor = getSharedPreferences("MyPref", MODE_PRIVATE).edit();
SharedPreferences prefs=getSharedPreferences("MyPref", MODE_PRIVATE);
StringBuffer stringBuffer = new StringBuffer();
stringBuffer = prefs.getString("tipoftheday", null).toString();
editor.putString("tipoftheday", stringBuffer.append(stringBuffer +",", tii.get(i1).toString()));
editor.commit();
}
You are losing your previous values because you are updating the same key inside your SharedPreferences.Editor. What you have to do in order to add more information afterwards is to first retreive your String value, then add your information and finally store all the info inside your SharedPreferences.Editor.
EDIT
I think it should be something like this, I have done it without any IDE or compiler, so it may have some syntax mistakes :)
SharedPreferences prefs=getSharedPreferences("MyPref", MODE_PRIVATE);
String serialized = prefs.getString("tipoftheday", null);
List<String> list;
if(serialized != null)
list = Arrays.asList(TextUtils.split(serialized,","));
list .add(tipoftheday);
SharedPreferences.Editor editor = prefs.edit();
for (int i1 = 0; i1 < tii.size(); i1++) {
editor.putString("tipoftheday", TextUtils.join(",", list));
editor.apply(); // if you do not need the return value, apply is faster than commit
}
Hope it helps
EDIT 2
Check also ρяσѕρєя K answer, he has spotted a different mistake you are making :)
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.