Fetch data from dynamically created TextInputEditText and insert them to an array - android

Currently I have added the dynamic TextInputEditText fields to the LinearLayout where all the dynamically added fields stores(only holds dynamic EditText fields only).
However, when I read each EditText field and fetch it's data, the value of last text field replace all the other values in the array.
Example:
Adds 3 dynamic fields, with the corresponding values of "AA","BB","CC". When i read the array, it shows like this,
Output: "CC,CC,CC"
Code:
private void fetchCertificates(){
ArrayList<String> certs = new ArrayList<>();
for(int i =0;i<linearLayout.getChildCount();i++){
View certificateView = linearLayout.getChildAt(i);
TextInputEditText newCerts = findViewById(R.id.new_certs);
String name = newCerts.getText().toString();
certs.add(name);
}
String certList = android.text.TextUtils.join(",", certs);
Log.i("Certificates",certs);
}
Objective:
Read dynamically added TextInputEditText, and store the values in an array.
References: page-1 (This did not work)

I was able to resolve it in following way, thanks for the questioning hellboy and blackapps, it made me think bit differently.
private void fetchCertificates(){
ArrayList<String> certs = new ArrayList<>();
for(int i =0;i<linearLayout.getChildCount();i++){
View certificateView = linearLayout.getChildAt(i);
TextInputEditText newCerts = certificateView.findViewById(R.id.new_certs);
String name = newCerts.getText().toString();
certs.add(name);
}
String certList = android.text.TextUtils.join(",", certs);
Log.i("Certificates",certs);
}

The problem in your code is at these lines,
View certificateView = linearLayout.getChildAt(i);
TextInputEditText newCerts = findViewById(R.id.new_certs);
Assuming that the LinearLayout(parent) carries only TextInputEditText(children), when you iterate through LinearLayout you will get TextInputEditText only, so your code should be like,
View certificateView = linearLayout.getChildAt(i);
TextInputEditText newCerts = (TextInputEditText) certificateView;
or
TextInputEditText newCerts = (TextInputEditText) linearLayout.getChildAt(i);
In your code since you directly used findViewById you always got the last to the latest view(child) with this id(remember if there are multiple views with the same id, then the latest view defined, both in Activity or layout, will be fetched) that's the reason you get CC, CC, CC.

Related

Android set listview adapter without erasing predefined text of text view

i filling list view items using this piece of code:
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
ShipmentListActivity.this, shipmentList,
R.layout.activity_shipment_list_item, new String[] {
TAG_MWB,
TAG_ORIGIN,
TAG_DESTINATION,
TAG_SHIPMENT_TYPE,
TAG_STATUS,
TAG_WEIGHT,
TAG_PIECES,
}, new int[] {
R.id.mwbNumbTv,
R.id.shipmentOriginTv,
R.id.shipmentDestTv,
R.id.shipmentTypeTv,
R.id.shipmentStateTv,
R.id.shipmentWeightTv,
R.id.shipmentPieces
});
setListAdapter(adapter);
Problem is that in textviews is predefined some text and i would like to append given values to these textviews but not rewrite them, just use something like appendText method.
I know, i can do a new textviews beside of previous pre-filled textviews, but i think that append text is simplier solution.
Thanks for any advice.
You need to create a custom adapter for something like that.
But if you want to use simple adapter only then try to use different TextViews.
have one TextView for static value and another that show value for each row.
To append
String appendedText = "I'm appended";
TextView tv = findViewById(R.id.yourtextview);
tv.setText(tv.getText() +" "+appendedText);
the string that your are going to set i the textview,just hardcode the existing value
in another string and make a new string by adding these two strings like :
String a = "existing text in textview";
String b = "Stirng that you are getting from server";
String c = a + " "+ b;
textview.settext(c);

String usage as TextView ID

I would like to generate a random string(with some rules), than use it as a textview id. For example I would like to use settext with this string.
Purpose: I should select a textview randomly, than set its text to another.
Actually, there are different kinds of way to achieve this purpose. For instance you could have an array of texts that can be selected randomly.
String[] strArr = { "text1", "text2", "text3" };
Random rand = new Random();
int selected = rand.nextInt(3);
textView.setText(strArr[selected]);
If you MUST get the string from other textviews then you can create an array of IDs instead of an array of text. Then use the Random object to get an ID and then something like:
TextView textToGetString = (TextView) findViewById(idArray[selected]);
String newText = textToGetString.getText();
Your thought process seems a little complicated, but there could be a simpler solution. Ids are really only used by Android as placeholders for an integer. Instead of randomly generating an id's placeholder, you could populate an integer array with all the ids you want to use and then randomly select one from that array. Implementation could be as follows in your activity:
Random rand = new Random();
int[] myTextViews = new int[]{R.id.textView1, R.id.textView2, R.id.textView3}
int length = myTextViews.length;
TextView tV = (TextView)findViewById(myTextViews[rand.nextInt() % length]);
tV.setText("Whatever Text You Want");
I hope this helps! Good luck

Attaching random string from an array to a button

I am trying to make a random string from an array in my strings.xml file to appear on a random button in a linear layout. I inflate the button, choose a random string from my file, and them attach the random string to the button, then repeat for three buttons. everything works fine, I can see that it is attaching random strings every time, but the problem is that the button displays the name that I would use to refer to the string, not the strings actual value. For example if I have a string with a name of: string and value of: "Hello World", it just displays "string" as my button text.
private void loadButtons()
{
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int row = 0; row < guessRows; row++)
{
random = new Random();
Resources res = getResources();
String[] truthString = res.getStringArray(R.array.truthArray);
String truth = truthString[random.nextInt(truthString.length)];
Button newGuessButton = (Button) inflater.inflate(R.layout.guess_button, null);
newGuessButton.setText(truth);
buttonLayout.addView(newGuessButton);
}
Are you sure you're setting the string array correctly? Individual strings in an array shouldn't have name tags, the only name should be the array name. See the docs, and make sure you're declaring it properly.

update My Spinner from SQlite Database

I FOUND A SOLUTION FOR RESTORING MY VALUES, SEE MY NEW VERSION of populateFields()
Okay so I have been reading through all the Spinner and SQlite posts on here and cannot seem to find a good answer for what I am looking for so I am posting this scenario.
My app has two screens and uses the sqlite database on my device saving a name and weight fields from editTexts as strings like so
String eName = name.getText().toString();
String eWeight = weight.getText().toString();// where name and weight are EditTexts
and I have two spinners as follows
String eReps = spinReps.getSelectedItem().toString();
String eSets = spinSets.getSelectedItem().toString();
Then I call this to add to the database
long id = mDbHelper.createExercise(eName, eWeight, eReps, eSets);
Here is where my issue is, upon someone selecting to create a new exercise my app crashes because it is trying to populate a spinner incorrectly. Here is what I have currently.
private void populateFields(){
if(mRowId != null){ // where mRowId is the selected row from the list
Cursor exercise = mDbHelper.fetchExercise();
name.setText(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_NAME)));
weight.setText(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_WEIGHT)));
// this is the part that i need help with, I do not know how to restore
// the current items spinner value for reps and sets from the database.
spinReps.setSelection(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_REPS)));
spinSets.setSelection(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_SETS)));
}
I assume I need to use some sort of adapter to restore my list items along with the current value from the database, I am just not sure how.
Can someone please help me with this???
** BELOW IS MY SOLUTION**
I had to move my ArrayAdapters repsAdapter, spinAdapter out of my onCreate()
and then implement this new populateFields()
private void populateFields(){
if(mRowId != null){
Cursor exercise = mDbHelper.fetchExercise(mRowId);
// same as before
name.setText(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_NAME)));
// get the string for sReps and sSets from the database
String sReps = exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_REPS));
String sSets = exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_SETS));
// use the strings to get their position in my adapters
int r = repsAdapter.getPosition(sReps);
int s = setsAdapter.getPosition(sSets);
// set their returned values to the selected spinner Items
spinReps.setSelection(r);
spinSets.setSelection(s);
// same as before
weight.setText(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_WEIGHT)));
}
}
The way to set a Spinner to a value, not a position, depends on what adapter you are using.
ArrayAdapter, this one is easy:
int position = adapter.getPosition(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_REPS)));
spinReps.setSelection(position);
SimpleCursorAdapter, this one is a little harder:
String match = exercise.getString(exercise.getColumnIndexOrThrow(ExerciseDbAdapter.KEY_REPS));
Cursor cursor = adapter.getCursor();
cursor.moveToPosition(-1);
int columnIndex = cursor.getColumnIndexOrThrow(ExerciseDbAdapter.KEY_REPS);
while(cursor.moveToNext()) {
if(cursor.getString(columnIndex).equals(match))
break;
}
spinReps.setSelection(cursor.getPosition());
If you are using a different type of adapter and can't modify the code above to fit it, let me know. Hope that helps!

Store multiple dynamic EditText value

I have a code adding multiple EditText. How can i store them into a array. This number 10 is just example, the number may bigger than that. How can i store it after click a button
for(int i=0; i<10; i++) {
String store[] = new String[10];
EditText addAnsMCQ = new EditText(this);
AnswerRG.addView(addAnsMCQ, 1);
addAnsMCQ.setWidth(200);
addAnsMCQ.setId(1000);
}
In your example the store variable isn't actually being used, did you intend do use it for storing the EditTexts?
Instead of using an array of String, just use an array of EditText and store a reference to them:
EditText store[] = new EditText[10];
for(int i=0; i<10; i++) {
EditText addAnsMCQ = new EditText(this);
AnswerRG.addView(addAnsMCQ, 1);
addAnsMCQ.setWidth(200);
addAnsMCQ.setId(1000);
store[i] = addAnsMCQ; //store a reference in the array to the EditText created
}
Then outside of the for loop, you can access the reference to each EditText, e.g.
store[0].setWidth(300);
You need to keep/get a reference to each of your EditText's then you can look up its value with .getText().toString() which you can store in whatever manner you like.
However if as you say
This number 10 is just example, the number may bigger than that.
If the number is going to be larger you should be using an Adapter and a ListView or something to hold your View objects. That will make it easier to get everything on to the screen. And will give you the benefit of view recycling.

Categories

Resources