I have been working on saving 4 String arrays to sharedpreference. Currently I am breaking the array down in to a string separating the pieces by a comma. When I go to the string, it does save the pieces accurately as it should; however, when I "load" the data and convert it back to an array, it's coming up empty (not null). I am unable to determine how I should fix this to pull my array back. Below is my Activity:
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 counter = 0;
SharedPreferences sharedPref= getSharedPreferences("chaosdatasnowball", 0);
String tempDebtNames = sharedPref.getString("debtNames", "");
debtName = convertStringToArray(tempDebtNames);
Bundle extras = getIntent().getExtras();
int trigger = 0;
for (int i=0;i<counter || i==counter;i++)
{
if (debtName[i] == null && extras != null && trigger == 0)
{
debtName[i] = extras.getString("debtName");
debtAmount[i] = extras.getString("debtAmount");
debtRate[i] = extras.getString("debtRate");
debtPayment[i] = extras.getString("debtPayment");
trigger = 1;
counter++ ;
}
}
TableLayout tl = (TableLayout) findViewById(R.id.debtListTableView);
for (int i=0;i<counter || i==counter;i++)
{
if (debtName[i] != null)
{
TableRow tr = new TableRow(this);
TextView tv0 = new TextView(this);
TextView tv1 = new TextView(this);
TextView tv2 = new TextView(this);
TextView tv3 = new TextView(this);
TableRow.LayoutParams trlp = new TableRow.LayoutParams();
tv0.setLayoutParams(new LayoutParams(0, LayoutParams.MATCH_PARENT, 0.25f));
tv1.setLayoutParams(new LayoutParams(0, LayoutParams.MATCH_PARENT, 0.25f));
tv2.setLayoutParams(new LayoutParams(0, LayoutParams.MATCH_PARENT, 0.25f));
tv3.setLayoutParams(new LayoutParams(0, LayoutParams.MATCH_PARENT, 0.25f));
trlp.span = 3;
tr.setLayoutParams(trlp);
tv0.setText("" + debtName[i]);
tv1.setText("" + debtAmount[i]);
tv2.setText("" + debtPayment[i]);
tv3.setText("" + i);
tr.addView(tv0);
tr.addView(tv1);
tr.addView(tv2);
tr.addView(tv3);
tl.addView(tr);
}
}
SharedPreferences.Editor editor= sharedPref.edit();
String debtNames = convertArrayToString(debtName, counter);
editor.putString("debtNames", debtNames).commit();
TextView disp = (TextView) findViewById(R.id.dispAdditionalAmount);
disp.setText("" + debtNames); //This is how I confirm that the convertArrayToString is functioning properly
}
public static String convertArrayToString(String[] array, int stop){
String str = "";
for (int i = 0;i<stop; i++) {
str = str+array[i];
// Do not append comma at the end of last element
if(i<stop-1){
str = str+",";
}
}
return str;
}
public static String[] convertStringToArray(String str){
String[] arr = str.split(",");
return arr;
}
You do:
String tempDebtNames = sharedPref.getString("debtNames", "");
debtName = convertStringToArray(tempDebtNames);
It is possible that "debtNames" key does not exist. (It returns "" in this case).
Think about first time the app is run. The key will not exist. Therefore, you should convertStringToArray only if !tempDebtNames.equals(""). If key doesn't exist then proceed with empty values..
Related
Today, I would like to seek your help regarding an issue I have in my acitvity, I am putting three strings in shared preferences using StringTokenizer.Everything is fine, now I would like to remove each textview from parent view and as well as from shared preferences using its long click event .
Here is my code for your reference.
This is the place where I am storing the bitmap and other two string names in shared preferences
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
StringBuilder strCont = new StringBuilder();
screenOnePreferences = PreferenceManager.getDefaultSharedPreferences(AppsActivity.this);
String savedStringCont = screenOnePreferences.getString("appName1", "");
StringTokenizer stCont = new StringTokenizer(savedStringCont, ",");
String[] savedListCont = new String[stCont.countTokens()];
for (int j = 0; j < savedListCont.length; j++) {
savedListCont[j] =stCont.nextToken()+",";
strCont.append(savedListCont[j]);
}
StringBuilder str1 = new StringBuilder();
screenOnePreferences = PreferenceManager.getDefaultSharedPreferences(AppsActivity.this);
String savedString1 = screenOnePreferences.getString("appPackName1", "");
StringTokenizer st1 = new StringTokenizer(savedString1, ",");
String[] savedList1 = new String[st1.countTokens()];
for (int j = 0; j < savedList1.length; j++) {
savedList1[j] =st1.nextToken()+",";
str1.append(savedList1[j]);
}
StringBuilder strImg = new StringBuilder();
screenOnePreferences = PreferenceManager.getDefaultSharedPreferences(AppsActivity.this);
String savedImage = screenOnePreferences.getString("appImage1", "");
StringTokenizer stimg = new StringTokenizer(savedImage, ",");
String[] savedListImg = new String[stimg.countTokens()];
for (int j = 0; j < savedListImg.length; j++) {
savedListImg[j] =stimg.nextToken()+",";
strImg.append(savedListImg[j]);
}
strCont.append(clickedAppName);
str1.append(clickedApp);
strImg.append(Base64.encodeToString(b, Base64.DEFAULT));
PreferenceManager.getDefaultSharedPreferences(AppsActivity.this).edit().putString("appName1",strCont.toString()).commit();
PreferenceManager.getDefaultSharedPreferences(AppsActivity.this).edit().putString("appPackName1",str1.toString()).commit();
PreferenceManager.getDefaultSharedPreferences(AppsActivity.this).edit().putString("appImage1",strImg.toString()).commit();
This is the place where I am retrieving the same and binding to dynamic textviews.
String[] array;
static SharedPreferences prefsCont;
static String[] savedList2;
static List<String> list;
static StringBuilder strCont;
static String savedStringCont;
static String savedString2;
static String savedStringImg;
static StringTokenizer stCont;
static StringTokenizer st2;
static StringTokenizer stImage;
static String[] savedListCont;
static String[] savedListImage;
static List<String> numberList;
static Bitmap yourSelectedImage;
static int numOfContacts;
strCont = new StringBuilder();
prefsCont = PreferenceManager.getDefaultSharedPreferences(context);
savedStringCont = prefsCont.getString("appName1", "");
savedString2 = prefsCont.getString("appPackName1", "") ;
savedStringImg = prefsCont.getString("appImage1", "");
stCont = new StringTokenizer(savedStringCont, ",");
st2 = new StringTokenizer(savedString2, ",");
stImage = new StringTokenizer(savedStringImg, ",");
savedListCont = new String[stCont.countTokens()];
savedListImage = new String[stImage.countTokens()];
savedList2 = new String[st2.countTokens()];
numberList = Arrays.asList(stCont.toString().split(","));
int prevTextViewId = 0;
numOfContacts = stCont.countTokens();
for ( int K = 0; K < numOfContacts; K++) {
final int listenerI = K;
savedListCont[K] = stCont.nextToken();
savedList2[K] = st2.nextToken();
savedListImage[K] = stImage.nextToken();
byte[] b = Base64.decode(savedListImage[K], Base64.DEFAULT);
InputStream is = new ByteArrayInputStream(b);
yourSelectedImage = BitmapFactory.decodeStream(is);
BitmapDrawable bd = new BitmapDrawable(context.getResources(), yourSelectedImage);
for(int i = 0; i < 1; i++)
{
if(savedListCont[K] != null && savedList2[listenerI] != null && yourSelectedImage != null ){
final TextView textView = new TextView(context);
textView.setText(savedListCont[K]);
textView.setCompoundDrawablesRelativeWithIntrinsicBounds(null, bd, null, null);
textView.setPadding(0, 20, 0, 20);
textView.setTextColor(Color.WHITE);
textView.setMaxLines(1);
textView.setEllipsize(TextUtils.TruncateAt.MIDDLE);
int curTextViewId = prevTextViewId + 1;
textView.setId(curTextViewId);
final RelativeLayout.LayoutParams params =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.BELOW, prevTextViewId);
textView.setLayoutParams(params);
textView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// Here I would like to delete individual textview from shared preferences.
return false;
}
});
prevTextViewId = curTextViewId;
ll.addView(textView, params);
use this it help you ................
keyname is value which you want to delete........
prefsCont.edit().remove("KeyName").commit();
in your case example :-prefsCont.edit().remove("appName1").commit();
and if you want to delete all then use this prefsCont.edit().clear().commit();
use this to find out value which is you clicked ....
array = ArrayUtils.removeElement(array, "your textview value");
and use this to put array into the SharePrefernce
Set<String> set = new HashSet<String>();
set.addAll(listOfExistingScores);
prefsCont.putStringSet("key", set).commit();
enjoy coding ...............
To remove specific values use below
--> SharedPreferences.Editor.remove() followed by a commit()
To remove all data then use below
--> SharedPreferences.Editor.clear() followed by a commit()
you can use,
SharedPreferences preferences = getSharedPreferences("Mypref", 0);
if you want to remove particular value from shared preferences use below,
preferences.edit().remove("key").commit();
if you want to remove all data,
preferences.edit().clear().commit();
Hi everybody, I stucked in how to use two delimiters in
StringTokenizer in android for storing null values into db I have
string like this, string1=IMPS 2223 9481851276 7654321 , , 33
But empty fields missing in when used stringtokeniser
I want store result in db like this,
IMPS
2223
9481851276
7654321
null
null
33
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.getactivity_layout);
LinearLayout layout = (LinearLayout) findViewById(R.id.details);
sms = getIntent().getStringExtra("value");
merchantName = getIntent().getStringExtra("merchantName");
tv = (TextView) findViewById (R.id.textview_getactivity_key);
tv.setText("Enter the Detail for-"+merchantName);
keyText = (EditText) findViewById(R.id.edittext_getactivity_value);
//finalKey = "Pay"+" "+merchantName+"-";
keyText.setText(finalKey);
View submitButton = findViewById(R.id.finish);
inputMap = new LinkedHashMap<String, EditText>();
Pattern p = Pattern.compile("\\|.*?\\|");
Matcher m = p.matcher(sms);
while (m.find())
{
//String to be replaced
String s = m.group(0);
Log.d("TestTag", "Value of string in getdetails"+s);
if (!" ".equals(s.replaceAll("\\|", "")))
{
TextView t = new TextView(this);
t.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
t.setText(s.replaceAll("\\|", ""));
t.setPadding(0, 0, 0, 5);
t.setTextColor(getResources().getColor(android.R.color.black));
EditText et = new EditText(this);
et.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
//et.setInputType(1234);
layout.addView(t);
layout.addView(et);
inputMap.put(s, et);
}
}
submitButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
keyValue = keyText.getText().toString().trim();
ArrayList<String> tempArray = new ArrayList<String>();
String string=null;
if(sms != null && inputMap != null){
for(String s : inputMap.keySet()){
String inputValue = inputMap.get(s).getText().toString().trim();
if(inputValue.equalsIgnoreCase("") || inputValue.equals(null)){
//showDialog(s.replaceAll("\\|", "")+ " is mandatory.", inputMap.get(s));
return;
//sms = sms.replace(s, inputValue);
//tempArray.add(sms.replace(s, inputValue));
}
else{
sms = sms.replace(s, inputValue);
tempArray.add(sms.replace(s, inputValue));
}
string = sms.replaceAll("\\|\\s\\|",",");
}
StringTokenizer tokens = new StringTokenizer(string, " ");
String first = tokens.hasMoreTokens() ? tokens.nextToken() : null;
String second =tokens.hasMoreTokens() ? tokens.nextToken() : null;
String third = tokens.hasMoreTokens() ? tokens.nextToken() : null;
String fourth =tokens.hasMoreTokens() ? tokens.nextToken() : null;
String fifth = tokens.hasMoreTokens() ? tokens.nextToken() : null;
String sixth = tokens.hasMoreTokens() ? tokens.nextToken() : null;
String seventh =tokens.hasMoreTokens() ? tokens.nextToken() : null;
Log.d("Test123", "Split String is : "+first+" "+second+" "+third+" "+fourth+" "+fifth+" "+sixth+" "+seventh);
in.setKeyValue(keyValue);
in.setSmsKeyword(first);
in.setCustomerAccountNo(second);
in.setMobileNo(third);
in.setMmid(fourth);
in.setAmount(fifth);
in.setCustomerPin(sixth);
in.setRemarks(seventh);
in.setTempName(merchantName);
accessDB.open();
accessDB.insertMerchant(in);
accessDB.close();
Intent detailsIntent = new Intent(GetDetailsActivity.this,MainScreenTab.class);
detailsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(detailsIntent);
}
Icreate this post, because i am new at this, and i need a little help. I am doing a little exercise about a application you that with some values you can make a tablelayout from class. But after i push the button i get the error "The specified child already has a parent. You must call removeView() on the child's parent first"
public class TabelFlat extends Activity{
//deklarasi variabel
String jumlah,jasa,jangkawaktu;
int jum = 0, jsa = 0, jkwaktu = 0;
int a = 0, b = 0, c = 0, d = 0, i = 0;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
//mengambil value yg diimport dari class lain
if (extras != null) {
jumlah = extras.getString("jumlah");
jasa = extras.getString("jasa");
jangkawaktu = extras.getString("jangkawaktu");
}
//konversi string menjadi int
jum = Integer.parseInt(jumlah);
jsa = Integer.parseInt(jasa);
jkwaktu = Integer.parseInt(jangkawaktu);
//membuat tabel
TableLayout MainLayout = new TableLayout(this);
MainLayout.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.FILL_PARENT));
MainLayout.setStretchAllColumns(true);
//Baris Judul
TableRow row1 = new TableRow(this);
TextView text1 = new TextView(this);
text1.setText("Bulan");
TextView text2 = new TextView(this);
text2.setText("Total Angsuran");
TextView text3 = new TextView(this);
text2.setText("Angsuran");
TextView text4 = new TextView(this);
text2.setText("Bunga");
TextView text5 = new TextView(this);
text2.setText("Sisa Saldo");
text2.setGravity(android.view.Gravity.RIGHT);
//memasukkan nilai text ke row
row1.addView(text1);
row1.addView(text2);
row1.addView(text3);
row1.addView(text4);
row1.addView(text5);
//menambah row ke tabel
MainLayout.addView(row1);
//kalkulasi
TextView tangsuran = new TextView(this);
a = (jum * 120/100);
tangsuran.setText(""+String.valueOf(a));
TextView angsuran = new TextView(this);
b = jum / jkwaktu;
angsuran.setText(""+String.valueOf(b));
TextView bunga = new TextView(this);
c = jum * 20 / 100 / jkwaktu;
bunga.setText(""+String.valueOf(c));
//loop
d = jum;
for (i = 1;i<=jkwaktu;i++){
TableRow barisloop = new TableRow(this);
//membuat string kosong untuk setiap kolom
TextView bulan = new TextView(this);
bulan.setText(""+i);
TextView sisa = new TextView(this);
d = d - b;
sisa.setText(""+String.valueOf(d));
barisloop.addView(bulan);
barisloop.addView(tangsuran);
barisloop.addView(angsuran);
barisloop.addView(bunga);
barisloop.addView(sisa);
MainLayout.addView(barisloop);
}
setContentView(MainLayout);
}
}
here you add the tangsuran, angsuran and bunga text view to new row, but they are already added to another one.You must create new objects for the rows in the loop.
for (i = 1;i<=jkwaktu;i++){
TableRow barisloop = new TableRow(this);
//membuat string kosong untuk setiap kolom
TextView bulan = new TextView(this);
bulan.setText(""+i);
TextView sisa = new TextView(this);
d = d - b;
sisa.setText(""+String.valueOf(d));
barisloop.addView(bulan);
//barisloop.addView(tangsuran);
//barisloop.addView(angsuran); CREATE NEW TEXTVIEWS
//barisloop.addView(bunga);
barisloop.addView(sisa);
MainLayout.addView(barisloop);
}
I have developed a form in dynamically using some edit text,check boxes,radio buttons and buttons.I have created form successfully ,but how i can get the values from that and stored in database.Please can any one help me.
Thanking in Advance.
public void textView() {
idText++;
i++;
LinearLayout linearLayoutHorizantal1 = new LinearLayout(
getApplicationContext());
linearLayoutHorizantal1.setOrientation(LinearLayout.HORIZONTAL);
/*
* LinearLayout.LayoutParams params = new
* LinearLayout.LayoutParams(LayoutParams
* .WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
* linearLayoutHorizantal1.setGravity(Gravity.RIGHT);
*/
txtQuetion = new TextView(getApplicationContext());
txtQuetion.setText(i + ". " + strQuestionText);
txtQuetion.setTextColor(Color.BLACK);
txtQuetion.setTextSize(20);
txtQuetion.setId(idText);
linearLayoutHorizantal1.addView(txtQuetion);
linearLayoutDynamicAdd.addView(linearLayoutHorizantal1);
}
public void RadioButtons() {
radiogroup = new RadioGroup(getApplicationContext());
radiogroup.setOrientation(RadioGroup.HORIZONTAL);
RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(
SurveyFillActivity.this, null);
params.setMargins(10, 10, 10, 0);
linearLayoutDynamicAdd.addView(radiogroup);
for (int j = 0; j < answersList.length; j++) {
if (answersList[j] != null) {
idRadio++;
rb = new RadioButton(getApplicationContext());
rb.setId(idRadio);
rb.setText(answersList[j]);
rb.setTextColor(Color.BLACK);
rb.setButtonDrawable(R.drawable.radio_custom);
// rb.setChecked(true);
rb.setLayoutParams(params);
radiogroup.addView(rb);
}
}
}
private EditText editText(int _intID) {
idEditBox++;
final LayoutParams lparams = new LayoutParams(350, 50);
final EditText et = new EditText(this);
lparams.leftMargin = 20;
lparams.topMargin = 10;
et.setLayoutParams(lparams);
et.setWidth(32);
et.setEms(50);
et.setBackgroundResource(R.drawable.customborder_backbutton);
/*
* EditText et = new EditText(getApplicationContext());
* et.setId(idEditBox); et.setHeight(60); et.setWidth(50);
*/
//et.setBackgroundColor(Color.WHITE);
String s1 = et.getText().toString();
linearLayoutDynamicAdd.addView(et, lparams);
return et;
}
The above code for creating forms and i need to get the values form it and store in Database.
Create the arrays for texviews and radiobuttons ...what ever you need in your form.
take this as reference
TextView tv[] = new TextView[HowManyYouNeed];
TextView tvsa = new TextView(YourContax);
tv[position]=tvsa;//position like o ..1..2
tv[0].getText();
May be help full..
I have an empty LinearLayout, and I need to add a dynamic number of TextViews to it. However when I use the code below, only the first TextView is shown:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] listofnumbers = new String[1000];
for ( int i = 0 ; i < 1000 ; ++i ) {
listofnumbers[i] = "null";
}
Context context = getBaseContext();
String text = null;
Uri uri = Uri.parse("content://sms");
Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
String[] columnNames = cursor.getColumnNames();
LinearLayout lv = new LinearLayout(context);
LinearLayout.LayoutParams textViewParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, dip(48));
boolean v = true;
while (cursor.moveToNext())
{
String numberString = (cursor.getString( cursor.getColumnIndexOrThrow("address") ) ).replace(" ", "");
int i = 0;
boolean numberNotPresent = true;
for ( ; listofnumbers[i] != "null" ; ++i ) {
if ( numberString.equals(listofnumbers[i]) ) {
numberNotPresent = false;
}
}
if ( numberNotPresent == true ) {
text = (CharSequence) "From: " + cursor.getString(cursor.getColumnIndexOrThrow("address")) + ": " + cursor.getString(cursor.getColumnIndexOrThrow("body"));
listofnumbers[i] = numberString;
TextView tv = new TextView(this);
tv.setText(text);
tv.setLayoutParams(textViewParams);
lv.addView( tv );
}
}
setContentView(lv);
}
Where have I gone wrong?
try to change these two lines:
LinearLayout lv = new LinearLayout(context);
LinearLayout.LayoutParams textViewParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, dip(48));
with these:
LinearLayout lv = new LinearLayout(context);
lv.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams textViewParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
basically you need to set the orientation for the lv LinearLayout to vertical as the default one is horizontal.
I am not sure, but may be for each textView you set fill_parent param? The 1st textView shows on all your layout.