Android - Loop to collect all editText values - android

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("");
}
}

Related

Dynamically adding data to more TextView

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.

How to add data in array on button click?

int size = mcq.size();
String arr[] = null;
int i;
{
for (i = 0; i < size; i++) {
if (op1.isPressed()) {
arr[i] = tv1.getText().toString();
// Log.e("Array",arr[i]);
} else if (op2.isPressed()) {
arr[i] = tv2.getText().toString();
//Log.e("Array",arr[i]);
} else if (op3.isPressed()) {
arr[i] = tv3.getText().toString();
// Log.e("Array",arr[i]);
} else if (op4.isPressed()) {
arr[i] = tv4.getText().toString();
//Log.e("Array",arr[i]);
}
I am trying to store the data in an array when the button is pressed,but it always shows null.And when the for loop is over I want to display my array.
here , Arrays in Java have a size so u cannot do like this. Instead of this
use list,
ArrayList<String> arr = new ArrayList<String>();
Inorder to do using String array :
String[] arr = new String[SIZEDEFNE HERE];
For ur answer :
ArrayList<String> arr = new ArrayList<String>();
int i;
{
for (i = 0; i < size; i++) {
if (op1.isPressed()) {
arr.add(tv1.getText().toString());
} else if (op2.isPressed()) {
arr.add(tv2.getText().toString());
} else if (op3.isPressed()) {
arr.add(tv3.getText().toString());
} else if (op4.isPressed()) {
arr.add(tv4.getText().toString());
}
Retrive value using
String s = arr.get(0);
This is because your string array is null. Declare it with the size as
String[] arr = new String[size];
Try Array List. use the following code in your main java
final ArrayList<String> list = new ArrayList<String>();
Button button= (Button) findViewById(R.id.buttonId);
final EditText editText = (EditText) findViewById(R.id.editTextId)
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
list.add(editText.getText().toString());
}
});
To avoid duplication in arraylist .You can use arraylist for faster then String array
ArrayList<String> list = new ArrayList<String>();
list.add("Krishna");
list.add("Krishna");
list.add("Kishan");
list.add("Krishn");
list.add("Aryan");
list.add("Harm");
System.out.println("List"+list);
HashSet hs = new HashSet();
hs.addAll(list);
list.clear();
list.addAll(hs);

How to reference R.id s with indices? [duplicate]

This question already has answers here:
How do I get the resource id of an image if I know its name? [duplicate]
(5 answers)
Closed 8 years ago.
I've got this in my activity.java file.
text[0] = (EditText) findViewById(R.id.editText2);
text[1] = (EditText) findViewById(R.id.editText3);
text[2] = (EditText) findViewById(R.id.editText4);
text[3] = (EditText) findViewById(R.id.editText5);
text[4] = (EditText) findViewById(R.id.editText6);
text[5] = (EditText) findViewById(R.id.editText7);
text[6] = (EditText) findViewById(R.id.editText8);
text[7] = (EditText) findViewById(R.id.editText9);
How can I write it with a for loop.
for(int i=o;i<8;i++)
text[i] = (EditText) findViewById(R.id.<what here>);
How to reference edittext with index here?
You can achieve this by using getIdentifier()
for(int i=0; i<8; i++) {
for(int j=0; j<8; j++) {
String editTextID = "btn" + i + "-" + j;
int resID = getResources().getIdentifier(editTextID
,"id", "com.example.yourpackagename");
buttons[i][j] = ((EditTextID) findViewById(resID));
}
}
You can use a constant array for this.
// in your class
private static final int[] TEXT_IDS = { R.id.editText2, R.id.editText3, ... , R.id.editText9};
//initializing
for(int i = o; i < TEXT_IDS.length; i++)
text[i] = (EditText) findViewById(TEXT_IDS[i]);
You could try something like the answer below, which is taken verbatim from here.
import java.lang.reflect.Field;
/* ... */
for (int i = 1; i < 16; i++) {
int id = R.id.class.getField("s" + i).getInt(0);
tv[i] = (TextView)findViewById(id);
tv[i].setTypeface(face);
tv[i].setClickable(true);
tv[i].setOnClickListener(clickListener);
}

how to get the total of an arraylist of edittext and then display to an arraylist of TextView?

for example i have..
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView excellent_val = (TextView)findViewById(R.id.excellent_val);
TextView best_val = (TextView)findViewById(R.id.best_val);
TextView better_val = (TextView)findViewById(R.id.better_val);
TextView good_val = (TextView)findViewById(R.id.good_val);
TextView poor_val = (TextView)findViewById(R.id.poor_val);
final EditText respondents = (EditText)findViewById(R.id.respondents);
final EditText questions = (EditText)findViewById(R.id.questions);
Button button1 = (Button)findViewById(R.id.btn);
button1.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String c = questions.getText().toString();
final Integer count = Integer.parseInt(c);
questions.setText(Integer.toString(count));
respondents.setText(respondents.getText().toString());
final TableLayout table = new TableLayout(getApplicationContext());
table.setVerticalScrollBarEnabled(true);
table.setPadding(10, 10, 10, 10);
final TableRow tableRow = new TableRow (getApplicationContext());
TextView txt = new TextView (getApplicationContext());
TextView txt2 = new TextView (getApplicationContext());
TextView txt3 = new TextView (getApplicationContext());
TextView txt4 = new TextView (getApplicationContext());
TextView txt5 = new TextView (getApplicationContext());
TextView txt6 = new TextView (getApplicationContext());
tableRow.addView(txt);
tableRow.addView(txt2);
tableRow.addView(txt3);
tableRow.addView(txt4);
tableRow.addView(txt5);
tableRow.addView(txt6);
tableRow.setBackgroundColor(Color.GRAY);
txt.setText("Question ");
txt2.setText("Excellent ");
txt3.setText("Best ");
txt4.setText("Better ");
txt5.setText("Good ");
txt6.setText("Poor ");
txt.setTextColor(Color.BLACK);
txt2.setTextColor(Color.BLACK);
txt3.setTextColor(Color.BLACK);
txt4.setTextColor(Color.BLACK);
txt5.setTextColor(Color.BLACK);
txt6.setTextColor(Color.BLACK);
table.addView(tableRow);
final StringBuilder output = new StringBuilder();
int j=0;
for(j = 1; j<=count; j++){
Random rnd = new Random();
int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
tableRow2 = new TableRow (getApplicationContext());
excellent = new EditText (getApplicationContext());
best = new EditText (getApplicationContext());
better = new EditText (getApplicationContext());
good = new EditText (getApplicationContext());
poor = new EditText (getApplicationContext());
mean_in = new TextView(getApplicationContext());
name = new TextView (getApplicationContext());
excellent.setBackgroundColor(color);
best.setBackgroundColor(color);
better.setBackgroundColor(color);
good.setBackgroundColor(color);
poor.setBackgroundColor(color);
name.setText("Q#"+Integer.toString(j));
mean_in.setTextColor(Color.WHITE);
tableRow2.addView(name);
tableRow2.addView(excellent);
tableRow2.addView(best);
tableRow2.addView(better);
tableRow2.addView(good);
tableRow2.addView(poor);
tableRow2.addView(mean_in);
table.addView(tableRow2);
excellentList.add(excellent);
bestList.add(best);
betterList.add(better);
goodList.add(good);
poorList.add(poor);
mean_array.add(excellent);
mean_array.add(best);
mean_array.add(better);
mean_array.add(good);
mean_array.add(poor);
MEAN.add(mean_in);
}
//Make an ArrayList of EditText
//Put all excellent EditTexts in it.
//In the onClick go through this list and append all the getText().toString() of these EditTexts
tableRow1 = new TableRow (getApplicationContext());
final Button get = new Button(getApplicationContext());
tableRow1.addView(get);
get.setText("Get!");
get.setTextSize(8);
//******************************************************************************//
// GET! //
//******************************************************************************//
get.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String population = respondents.getText().toString();
double n = Double.parseDouble(population);
double Population = 0;
double final_Population =0;
Population = n/(1+(n*(0.003*0.003)));
final_Population = Math.ceil(Population);
String val_excellent=null;
double weigthed_ex=0;
double result =0;
double final_result=0;
for(EditText excellent : excellentList){
val_excellent= excellent.getText().toString();
double values = Double.parseDouble(val_excellent);
for(int z=0;z<val_excellent.length();z++){
weigthed_ex =values*5/final_Population;
}
String weight_excellent =String.format("%.3g",weigthed_ex);
get.setEnabled(false);
excellent.setTextSize(11);
excellent.setTextColor(Color.BLACK);
excellent.setEnabled(false);
excellent.setText((weight_excellent));
}
String val_best=null;
double weigthed_best=0;
for(EditText best: bestList){
val_best = best.getText().toString();
double values_best = Double.parseDouble(val_best);
for(int y =0; y<val_best.length();y++){
weigthed_best = values_best*4/final_Population;
}
String weight_best =String.format("%.3g",weigthed_best);
best.setTextSize(11);
best.setTextColor(Color.BLACK);
best.setEnabled(false);
best.setText(weight_best);
}
String val_better=null;
double weigthed_better=0;
for(EditText better: betterList){
val_better = better.getText().toString();
double values_better = Double.parseDouble(val_best);
for(int k =0; k<val_better.length();k++){
weigthed_best = values_better*3/final_Population;
}
String weight_better =String.format("%.3g",weigthed_better);
better.setTextSize(11);
better.setTextColor(Color.BLACK);
better.setEnabled(false);
better.setText(weight_better);
}
String val_good=null;
double weigthed_good=0;
for(EditText good: goodList){
val_good = good.getText().toString();
double values_good = Double.parseDouble(val_good);
for(int l =0; l<val_good.length();l++){
weigthed_good = values_good*2/final_Population;
}
String weight_good =String.format("%.3g",weigthed_good);
good.setTextSize(11);
good.setTextColor(Color.BLACK);
good.setEnabled(false);
good.setText(weight_good);
}
String val_poor=null;
double weigthed_poor=0;
for(EditText poor: poorList){
val_poor = poor.getText().toString();
double values_poor = Double.parseDouble(val_poor);
for(int m =0; m<val_poor.length();m++){
weigthed_poor = values_poor*1/final_Population;
}
String weight_poor =String.format("%.3g",weigthed_poor);
poor.setTextSize(11);
poor.setTextColor(Color.BLACK);
poor.setEnabled(false);
poor.setText(weight_poor);
}
Button getMean = new Button(getApplicationContext());
tableRow1.addView(getMean);
getMean.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String a=null;
String b=null;
String c=null;
String d=null;
String e=null;
double f=0;
double g=0;
double h=0;
double i=0;
double j=0;
double mean=0;
for(TextView mean_in: MEAN){
for(EditText excellent :excellentList){
a = excellent.getText().toString();
f= Double.parseDouble(a);
}
for(EditText best :bestList){
b = best.getText().toString();
g= Double.parseDouble(b);
}
for(EditText better :betterList){
c = better.getText().toString();
h= Double.parseDouble(c);
}
for(EditText good :goodList){
d = good.getText().toString();
i= Double.parseDouble(d);
}
for(EditText poor :poorList){
e = poor.getText().toString();
j= Double.parseDouble(e);
}
mean = f+g+h+i+j/5;
mean_in.setText(" ");
}
}
});
TextView mean = new TextView(getApplicationContext());
mean.setText("Mean");
mean.setTextColor(Color.RED);
tableRow.addView(mean);
}
});
i want the total values of my 5 edittexts to be displayed in mean_in(TextView) how will i do tha?please help me please...i have a hard time of thinking how will i do it...thank you very much...
Look at the example i provide here
String text="";
for(j = 1; j<=arraylist.size; j++)
{
text=text+arraylist.get(j);
}
mean_in.setText(text);
I think you are looking for something like Integer.parseInt(String s)
This will allow you to get an int out of all your editText elements and then you just have to add them all together.
This code will show the mean value in the mean fields:
//Get text from each field
String sExcellent = this.excellent_val.getText().toString();
String sBest = this.best_val.getText().toString();
String sBetter = this.better_val.getText().toString();
String sGood = this.good_val.getText().toString();
String sPoor = this.poor_val.getText().toString();
//convert to float while adding to array (although it would be better do some checking first)
float frequencies = new float[]{Float.parseFloat(sExcellent),
Float.parseFloat(sBest),
Float.parseFloat(sBetter),
Float.parseFloat(sGood),
Float.parseFloat(sPoor)};
//calculate average
float totalFrequency = 0;
for(float frequency : frequencies)
totalFrequency += frequency;
//set text of mean_in to mean frequency
mean_in.setText(""+totalFrequency/frequencies.length);
TIPS
I must advise you to organise your code a lot better!
Your onCreate() is too long! You should divide large tasks over many methods e.g. a createUserInterface() method to set up the user interface. I would advise reading a book on design patterns or on code refactoring.
variables should have meaningful names. Variable names like 'c' and 'd' are lazy, confusing and considered very bad practice.
I don't understand how you're creating your layout. You're making it very hard for yourself . Here's a really short simple video tutorial explaining how to create a TableLayout in XML and initialise it in Java.
Hope this helps :) Good Luck!

Creating dynamic variable in Android

I have multiple strings like st1, st2, st3, st4, st5, st6, st7. now i want to get that strings dynamically through for loop using its counter(in my case int i). like "st"+ i , but the android doesnot accept it so what should i do to get the string dynamically. for more info here is the chunk of the code
String image1 = cData.getString(cData.getColumnIndex("fld_image_url1"));
String image2 = cData.getString(cData.getColumnIndex("fld_image_url2"));
String image3 = cData.getString(cData.getColumnIndex("fld_image_url3"));
String image4 = cData.getString(cData.getColumnIndex("fld_image_url4"));
ArrayList<String> imagesArray = new ArrayList<String>();
//for adding the string in the arraylist dynamically
for(int i=1;i<=4;i++){
if("image"+i!=null){
imagesArray.add(String.valueOf("image"+ i));
}
}
How about something like:
List<String> imagesArray = new ArrayList<String>();
for (int i = 1; i <= 4; i++) {
String image = cData.getString(cData.getColumnIndex("fld_image_url" + i));
if (image != null) {
imagesArray.add(image);
}
}
if you want to get value from cursor dynamically then change your code as:
//for adding the string in the arraylist dynamically
for(int i=1;i<=4;i++){
int count = cData.getColumnIndex("fld_image_url"+i));
if(count != -1)
imagesArray.add(cData.getString(count));
}

Categories

Resources