Saving String[] as a single String in Android - android

I am trying to take my 4 String arrays and convert them in to a single string separated by a ",". It seems to save the information easy enough when I debug; however, when I try and getString - it doesn't retrieve the data. I'm trying to determine why:
String[] debtName = new String[10];
String[] debtAmount = new String[10];
String[] debtRate = new String[10];
String[] debtPayment = new String[10];
//Load Data
SharedPreferences sharedPref= getSharedPreferences("chaosdatasnowball", 0);
debtName = sharedPref.getString("debtNames", null).split(",");
//End Load
Bundle extras = getIntent().getExtras();
int flipper = 0;
for(int i=0;i<debtName.length;i++)
{
if(debtName[i].equals(null) && !extras.equals(null) && flipper!=1)
{
debtName[i] = extras.getString("newDebtName");
debtAmount[i] = extras.getString("newDebtAmount");
debtRate[i] = extras.getString("newDebtRate");
debtPayment[i] = extras.getString("newDebtPayment");
flipper = 1;
}
}
..............
StringBuilder value = new StringBuilder("");
SharedPreferences.Editor editor= sharedPref.edit();
for (String i : debtName) {
value.append(i + ",");
}
editor.putString("debtNames", value.toString());
for (String i : debtAmount) {
value.append(i + ",");
}
editor.putString("debtAmounts", value.toString());
for (String i : debtRate) {
value.append(i + ",");
}
editor.putString("debtRates", value.toString());
for (String i : debtPayment) {
value.append(i + ",");
}
editor.putString("debtPayments", value.toString());
editor.commit();
Correction, when run outside of debug, this gives a nullpointer exception on:
SharedPreferences sharedPref= getSharedPreferences("chaosdatasnowball", 0);
debtName = sharedPref.getString("debtNames", null).split(","); <---this line
Here is where the activity is called:
EditText editDebtName = (EditText) findViewById(R.id.dispDebtName);
debtName = editDebtName.getText().toString();
EditText editDebtAmount = (EditText) findViewById(R.id.dispDebtAmount);
String debtAmountStr = editDebtAmount.getText().toString();
EditText editDebtRate = (EditText) findViewById(R.id.dispDebtRate);
String debtRateStr = editDebtRate.getText().toString();
EditText editDebtPayment = (EditText) findViewById(R.id.dispDebtPayment);
String debtPaymentStr = editDebtPayment.getText().toString();
Intent i = new Intent(this, DebtList.class);
i.putExtra("newDebtName", debtName);
i.putExtra("newDebtAmount", debtAmountStr);
i.putExtra("newDebtRate", debtRateStr);
i.putExtra("newDebtPayment", debtPaymentStr);
startActivity(i);

The problem is with this line:
debtName = sharedPref.getString("debtNames", null).split(",");
It is possible that the key debtNames does not exist. Therefor null is returned.
This will happen when you run the app for the first time and have not saved anything to the shared preference yet.
Add a check for null and handle this case. Something like, if null is returned, then show default values, else show values that are read from sharedpreference.

I have surrendered to the apparent fact that there is no valid way to do this so I have hard coded 40 variables in to the app now. If anyone comes up with anything useful, please feel free to post it and I'll check this every so often.

Related

SharedPreferences not saving all the data after restart

I am new to Android App Development and I am supposed to make a TodoList App for a course. But the SharedPreference in my code is not working. I dont know if I'm supposed to use it in a specific way in a specific method like onCreate or onStop.
It is saving the first input the user is entering permanently, but in the same position:
(The "task0" is what I used to track the different variable names I used as argument for "putString" in addStuff method, to avoid replacing values)
It is saving the inputs after that in the same session, but if the user ends that session, all those values after "t" are gone. If the user restarts the app and inputs something else (like "g"), it is saving "g" in that same 3rd position.
I have basic Java knowledge and I tried to understand what is going on using it, but failed. Please let me know where is the mistake and how to use SharedPreferences properly.
public class TodoActivity extends AppCompatActivity {
public ArrayList<String> items;
public ArrayAdapter<String> itemsAdapter;
public ListView list;
public String s;
public EditText taskBox;
public static final String filename = "itemsList";
public TextView text;
public static int counter = 0;//counter starting at 0 no matter what, everytime the app starts
public String newtask= "task";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_todo);
list = (ListView) findViewById(R.id.list1);text = (TextView) findViewById(R.id.text1);
taskBox = (EditText) findViewById(R.id.box);
s = taskBox.getText().toString();
items = new ArrayList<String>();
itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
list.setAdapter(itemsAdapter);
//add items to list
items.add("First Item");
items.add("Second Item");
//restore
SharedPreferences sp = this.getSharedPreferences("itemsList", 0);
//checking if it stores the previous values, this gives the last input but not the previous ones after restarting the app
String dummyname = "task";
text.setText(String.valueOf(counter));//since counter is again at
for(int c=0; c<=50; c++){
String num = String.valueOf(c);
dummyname = dummyname + num;
String x = sp.getString(dummyname, "not found");
if (x.equalsIgnoreCase("not found")){
counter=c-1;
break;
} else {
items.add(x);
text.setText(dummyname);
}
}
}
public void addItem(View v){
s = taskBox.getText().toString();
itemsAdapter.add(s);//adding the new task as string
String temp = String.valueOf(counter);
newtask = "task" + temp;
//trying to store the new tasks with different variable names to avoid being replaced
text.setText(newtask);
SharedPreferences sp = this.getSharedPreferences("itemsList", 0);
SharedPreferences.Editor e = sp.edit();
e.putString(newtask,s);
e.apply();
counter++;
}
}
If you have relatively small collection of key-values that you would like to save,
You should use Shared preference API
Read from the shared preference:
Pass the key and value you want to write,create a SharedPreferences.Editor by calling edit() on your SharedPreferences.
Pass key and values you want to save by using this method putInt() ,putString() ,Then call commit() to save the changes. For example:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("KeyName", newHighScore);
editor.commit();
Write from the shared preference:
To retrieve values from a shared preferences file, call methods such as getInt() and getString(),
providing the key for the value you want, and optionally a default value to return if the key isn't present. For example:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt("KeyName", defaultValue);
Two things :
1) To initialize SharedPreferences use :
sharedPreferences = getSharedPreferences("itemsList", Context.MODE_PRIVATE);
2) Where are you calling addItem() method??
The problem is about the Tag you use to save items. See this Line :
dummyname = dummyname + num;
You add item by this format :
task0
task1
task2
but you are getting values in this format
task0
task01
task012
Just change these two line of code :
//dummyname = dummyname + num;
//String x = sp.getString(dummyname, "not found");
String newDummy= dummyname + num;
String x = sp.getString(newDummy, "not found");

How to get the searched text in a string?

I want to get a text that it is a part of an string.For example: I have a string like "I am Vahid" and I want to get everything that it's after "am".
The result will be "Vahid"
How can I do it?
Try:
Example1
String[] separated = CurrentString.split("am");
separated[0]; // I am
separated[1]; // Vahid
Example2
StringTokenizer tokens = new StringTokenizer(CurrentString, "am");
String first = tokens.nextToken();// I am
String second = tokens.nextToken(); //Vahid
Try:
String text = "I am Vahid";
String after = "am";
int index = text.indexOf(after);
String result = "";
if(index != -1){
result = text.substring(index + after.length());
}
System.out.print(result);
Just use like this, call the method with your string.
public String trimString(String stringyouwanttoTrim)
{
if(stringyouwanttoTrim.contains("I am")
{
return stringyouwanttoTrim.split("I am")[1].trim();
}
else
{
return stringyouwanttoTrim;
}
}
If you prefer to split your sentence by blank space you could do like this :
String [] myStringElements = "I am Vahid".split(" ");
System.out.println("your name is " + myStringElements[myStringElements.length - 1]);

Android studio keeps setting int[] variable to null

I have an int variable with 6 elements. All the time in the code android sets it to null. I even redefined it in the code in debug mode like this
if (yeahsort == null) {
SharedPreferences prefs2 = getSharedPreferences("KARANTÄN", MODE_PRIVATE);
String savedString = prefs2.getString("string", null);
StringTokenizer st = new StringTokenizer(savedString, ",");
int[] yeahsort = new int[6];
for (int i = 0; i < 6; i++) {
yeahsort[i] = Integer.parseInt(st.nextToken());
}
}
during the for loop the variable yeahsort becomes an int[], but right after it becomes null again. Seriously right after the for loop.
So what can I do to fix this?
Instead of int[] yeahsort = new int[6] change it to yeashsort = new int[6] here is a lesson on variable scoping http://www.java-made-easy.com/variable-scope.html

Intent not being received

I have 2 activities involved in this question. The first one the user inputs data on a simple form style layout. It then should save the 4 pieces of data to an intent (putextra) and startActivity(intent).
The second should retrieve the data and have them ready to be loaded in to arrays. When i run the debug, the intent from activity1 successfully holds the values; however, activity2 says the intent is null.. I'm unsure of what is happening in between.
ACTIVITY1
EditText editDebtName = (EditText) findViewById(R.id.dispDebtName);
debtName = editDebtName.getText().toString();
EditText editDebtAmount = (EditText) findViewById(R.id.dispDebtAmount);
String debtAmountStr = editDebtAmount.getText().toString();
EditText editDebtRate = (EditText) findViewById(R.id.dispDebtRate);
String debtRateStr = editDebtRate.getText().toString();
EditText editDebtPayment = (EditText) findViewById(R.id.dispDebtPayment);
String debtPaymentStr = editDebtPayment.getText().toString();
Intent i = new Intent(this, DebtList.class);
i.putExtra("newDebtName", debtName);
i.putExtra("newDebtAmount", debtAmountStr);
i.putExtra("newDebtRate", debtRateStr);
i.putExtra("newDebtPayment", debtPaymentStr);
startActivity(i);
ACTIVITY2
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.debtlist);
String[] debtName = new String[10];
String[] debtAmount = new String[10];
String[] debtRate = new String[10];
String[] debtPayment = new String[10];
int trigger = 5;
SharedPreferences sharedPref= getSharedPreferences("chaosdatasnowball", 0);
debtName = getFromSharedPreference("debtNames", this.getApplicationContext());
debtAmount = getFromSharedPreference("debtAmounts", this.getApplicationContext());
debtRate = getFromSharedPreference("debtRates", this.getApplicationContext());
debtPayment = getFromSharedPreference("debtPayments", this.getApplicationContext());
trigger = sharedPref.getInt("trigger", trigger);
Bundle extras = getIntent().getExtras();
debtName[trigger] = extras.getString("newDebtName");
debtAmount[trigger] = extras.getString("newDebtAmount");
debtRate[trigger] = extras.getString("newDebtRate");
debtPayment[trigger] = extras.getString("newDebtPayment");
There are no error messages being throw out either. What I'm trying to determine is.. why is my intent not being received..?
I think that problem cause by this code
SharedPreferences sharedPref= getSharedPreferences("chaosdatasnowball", 0);
debtName = getFromSharedPreference("debtNames", this.getApplicationContext());
debtAmount = getFromSharedPreference("debtAmounts", this.getApplicationContext());
debtRate = getFromSharedPreference("debtRates", this.getApplicationContext());
debtPayment = getFromSharedPreference("debtPayments", this.getApplicationContext());
Because i test without above code, activity2 still receive bundle value. If you try without above code and still have that problem, you should try to debug & show all values of string array to determine problem again.

Remove the brackets when saved in Database in Android

I am saving an arraylist in my database. But what happens when I saved it, is this:
I want to remove the brackets from the data of the last column and I want my database to be like this one:
Here's my code:
ArrayList<String> content = new ArrayList<String>();
for (int j=0; j<checkSelected.length; j++) {
if(checkSelected[j]==true) {
String values = BrandListAdapter.mListItems.get(j);
Cursor rSubBrand = databaseHandler.getReport_SubBrandCode(values);
String SubBrandCode = rSubBrand.getString(rSubBrand.getColumnIndex(Constants.SUBBRAND_CODE));
content.clear();
content.add(SubBrandCode);
String subBrand = content.toString();
databaseHandler.SaveSubBrand(new Cons_iReport (ReportCode, subBrand));
}
}
I just figure it out. The reason why I cannot remove the brackets is because I didn't assigned it to the 'subBrand' that will be saved to the database.
ArrayList<String> content = new ArrayList<String>();
for (int j=0; j<checkSelected.length; j++) {
if(checkSelected[j]==true) {
String values = BrandListAdapter.mListItems.get(j);
Cursor rSubBrand = databaseHandler.getReport_SubBrandCode(values);
String SubBrandCode = rSubBrand.getString(rSubBrand.getColumnIndex(Constants.SUBBRAND_CODE));
content.clear();
content.add(SubBrandCode);
String subBrand = content.toString();
subBrand = subBrand.replace("[", ""); // this is what I mean...
subBrand = subBrand.replace("]", "");
databaseHandler.SaveSubBrand(new Cons_iReport (ReportCode, subBrand));
}
}
You can use the replaceAll function:
subBrand = subBrand.replaceAll("\\[|\\]", "");
that replaces all brackets found in the string.

Categories

Resources