Getting values of EditTexts from multiple Layouts in Android not working? - android

Not asked a question in a while so it's been long overdue!
I am creating an app where job items can be created onClick, with each new row containing a Description(EditText), a Price(EditText) and a button to delete the current row, but I am having trouble when getting the values from the EditText fields when there is more than one row - it just returns the values of the newest row.
Aside from the 'Job List Container', the views are created dynamically so pardon the lack of XML, but the structure of what I am trying to achieve is as follows, where clicking the Add button adds a row (this can be multiple rows) and clicking the submit button takes all of the Description and Price values and processes them (adds the prices and adds the job to the DB):
...and this is the code I've written for it called from the addNewJobRow onClick listener (all together for simplicity):
private void addJobItem() {
//Create a new row container
final LinearLayout jobRowContainer = new LinearLayout(this);
//Create a new EditText for the Description
final EditText description = new EditText(this);
description.setHint("Description...");
description.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
1.0f
));
//Create an EditText for the Price
final EditText price = new EditText(this);
price.setHint("00.00");
//Create a new button to delete the row
Button delete = new Button(this);
delete.setBackgroundColor(Color.RED);
delete.setText("X");
//Add Description, Price and Delete to the row container
jobRowContainer.addView(description);
jobRowContainer.addView(price);
jobRowContainer.addView(delete);
//Add the Row Container to the Jobs List Container
ll_jobListContainer.addView(jobRowContainer);
//Get the values of the Description and Price, for each row
btn_JobSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < ll_jobListContainer.getChildCount(); i++) {
for(int j = 0; j < jobRowContainer.getChildCount(); j++) {
if (jobRowContainer.getChildAt(i) instanceof EditText){
String descriptionString = description.getText().toString();
String priceString = price.getText().toString();
System.out.println("z! " + descriptionString + " # " + priceString);
}
}
}
}
});
}
I have tried a couple of iterations of this with and without the nested FOR loops and with and without the use of instanceof, but all it does is print out the newest row.
So, if I have multiple job rows, how can I get all of the values as required?
Thanks for your time and all that nice stuff xxx

The basic problem is that you're using only the last instance of description and price instead of each rows instance. (This may be what Dmitry is saying as well). To fix it, you need to get the input for each row. Here's one way.
Set an ID for description & price. (You can't just use '1' or '2', it needs to be a resource type ID so it is guaranteed to be unique). I made a dummy layout file of a row & assigned IDs in that to the 2 EditTexts. There may be a better way to do it. So anyway, add these 2 lines in your declarations
descripton.setId(R.id.description); and price.setId(R.id.price);
Now this is your onClick()
public void onClick(View v) {
for (int i = 0; i < ll_jobListContainer.getChildCount(); i++) {
LinearLayout currentRow = (LinearLayout)ll_jobListContainer.getChildAt(i);
EditText editText = (EditText)currentRow.findViewById(R.id.description);
String descriptionString = editText.getText().toString();
editText = (EditText)currentRow.findViewById(R.id.price);
String priceString = editText.getText().toString();
Log.d(TAG, "z! " + descriptionString + " # " + priceString);
}
}
EDIT: I didn't want to change this answer since it had already been accepted so I've put a more concise solution in another answer.

Of cause, your last setOnClickListener takes strings
String descriptionString = description.getText().toString();
String priceString = price.getText().toString();
Where description and price - is fields in the function (last edittexts).
The good way to do that is to use RecyclerView/ListView, in "onTextChangeListner" of ViewHolder save new text to model of this object and print all text from your models, not directly from views.

I normally try to answer only question that was asked rather than change code that's not necessary. However, in this case, since I had created a dummy layout just to get Resource IDs, I wonder if that layout file could be put to use. I had started to change my answer but original one was accepted before I could make the changes. I've put a different version of the solution here. I didn't want to modify an answer that had already been accepted.
private void addJobItem() {
//Create a new row container
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout jobRowContainer = (LinearLayout)inflater.inflate(R.layout.row_layout, null);
//Add the Row Container to the Jobs List Container
ll_jobListContainer.addView(jobRowContainer);
//Get the values of the Description and Price, for each row
btn_JobSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < ll_jobListContainer.getChildCount(); i++) {
LinearLayout currentRow = (LinearLayout)ll_jobListContainer.getChildAt(i);
EditText editText = (EditText)currentRow.findViewById(R.id.description);
String descriptionString = editText.getText().toString();
editText = (EditText)currentRow.findViewById(R.id.price);
String priceString = editText.getText().toString();
Log.d(TAG, "z! " + descriptionString + " # " + priceString);
}
}
});
}
row_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/single_row">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Description..."
android:id="#+id/description"
/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="00.00"
android:id="#+id/price"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/holo_red_dark"
android:text="X"
android:id="#+id/clear_button"
/>
</LinearLayout>

Related

Inputting Array In Multiline Text In Android

I am new to android and am trying to make an app where the user inputs an array in a text box with inputType = textMultiLine. The problem is that I want to make it so that whenever user hits enter, the app takes input of the next array element and not treat the entire text in the textbox as one element. The code is as below :
EditText input = findViewById(R.id.inputtext);
Button show = findViewById(R.id.button);
TextView output = findViewById(R.id.output);
String [] name = new String[3];
for (int i = 0 ; i < 3 ; i++)
{
name[i] = input.getText().toString();
output.setText(name[i]);
}
But whenever i try to take name[1] after hitting enter the app doesnt treat the next line as name[2] but instead treats it as name[1]. For example if type the names john,steve and frank, then i should get an array that is like this :
name[0] = john
name[1] = steve
name[2] = frank
but instead whenever I typejohn,press enter,type steve, press enter and type frank the app treats it as :
name[0] = john
steve
frank
also if i set the output to something like this :
output.setText(name[i] + i)
instead of getting an oupt like this :
john 0
steve 1
frank 2
I get an output like this :
john
steve
frank2
Any and all help would be much appreciated.
Thanks
======================================================================================================================================================
EDIT 1
I tried this code but didn't work:
String name[] = input .getText().toString().split("\\r?\\n");
for (int i = 0 ; i < name.length; i++)
{
output.setText(name[i]);
}
Still get only frank when I input john,steve and frank
If you want to put each line to different array item :
String [] name = input.getText().toString().split("\n");
input.getText().toString() gives you string containing whole EditText content with lines separated by new line - "\n". You need to split this string to get each line.
try below code
String name[] = input .getText().toString().split("\\r?\\n");
String disp="";
for (int i = 0 ; i < name.length; i++)
{
disp += name[i] +"\n";
}
output.setText(disp);
Maybe the following example will be useful:
XML file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<EditText
android:id="#+id/edit_text"
style="#style/Widget.AppCompat.EditText"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_marginBottom="100dp"
android:inputType="textMultiLine"/>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show"/>
<TextView
android:id="#+id/text_view"
style="#style/Widget.AppCompat.EditText"
android:layout_width="300dp"
android:layout_height="wrap_content"/>
</LinearLayout>
Java Code
final EditText input = findViewById(R.id.edit_text);
final Button show = findViewById(R.id.button);
final TextView output = findViewById(R.id.text_view);
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
final String inputString = input.getText().toString();
if (!TextUtils.isEmpty(inputString)) {
final String newLine = System.getProperty("line.separator");
final String[] inputText = inputString.split(newLine);
String outputText = "";
for (int i = 0; i < inputText.length; i++) {
outputText += inputText[i];
if (i != inputText.length - 1) {
outputText += newLine;
}
}
output.setText(outputText);
}
}
});
}
You can download de APK here or here the complete source code
(another way:simple!) In the following code it is not necessary to make a split on the input text.
final EditText input = findViewById(R.id.edit_text);
final Button show = findViewById(R.id.button);
final TextView output = findViewById(R.id.text_view);
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
final String inputString = input.getText().toString();
if (!TextUtils.isEmpty(inputString)) {
output.setText(inputString);
}
}
});
Note that, your code is wrong, because in for each loop, you override the text was setted in the previous loop.

How to get id value from programmatically created Edittext

calculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mul=0;
sum=0;
for(j=0;j<=a-1;j++){
Log.d("TAG","a ko value inside calc "+a);
et_grade_grabber=(EditText) findViewById(grade[j]);
int grade= Integer.parseInt(et_grade_grabber.getText().toString());
Log.d("TAG","Grade Value of Grade"+j+ " is "+grade);
et_credit_grabber=(EditText) findViewById(credit[j]);
int credit=Integer.parseInt(et_credit_grabber.getText().toString());
Log.d("TAG","Credit Value of Credit "+j+" is "+credit);
tot_credit= credit+tot_credit;
Log.d("TAG","Total Credit = "+tot_credit);
mul=credit*grade;
sum= sum + mul;
Log.d("Sum Inside Loop ",""+sum);
}
Log.d("TAG","Sum"+sum);
Toast.makeText(getApplicationContext(),""+sum,Toast.LENGTH_SHORT).show();
sgpa= sum/tot_credit;
tv_sgpa= new TextView(MainActivity.this);
tv_sgpa.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT,TableLayout.LayoutParams.WRAP_CONTENT));
tv_sgpa.setText("Your SGPA is "+sgpa);
tv_sgpa.setTextSize(40);
LinearLayout ll_sgpa = new LinearLayout(MainActivity.this);
ll_sgpa.setLayoutParams(new ActionBar.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT));
ll_sgpa.addView(tv_sgpa);
LinearLayout linear = (LinearLayout) findViewById(R.id.ll_spga);
linear.addView(ll_sgpa);
}
});
}
I have successfully create EditText fields using a for(i=0;i<4-1;i++) loop from java file and assign id by setid(Array[i]) inside a loop.
Now again I have retrive the values by method getText().toString() inside a loop for(j=0;j<4-1;j++)
When I input the values in edit text everything works fine except it only retrieves the first value of edit text to all array.
If I understood your question correctly, you should use
for(int i = 0; i < arrayOfEditTexts.size(); i++){
//if you need only some of Ids, just check conditions with `if`statement. example:
if(!((EditText)arrayOfEditTexts.get(i)).getText().toString().equalsIgnoreCase("")){
arrayOfEditTexts.get(i).getId(); // and do whatever you want
}
}

Android : How to get Dynamic EditText values

In my application I'am creating 10 EditText by dynamically. Now I want to give different value in run time and I want to add it to the list. I have assigned EditText object to the String variable like object.getText.toString(). But i cant get any value.I'am a beginner in android. Can anyone help me how to achieve this? Thanks in advance.
for(int i=0;i<=10;i++)
{
requirement = require.get(i);
RelativeLayout rl1 = new RelativeLayout(getActivity());
rl1.addView(req1);
req1estimate_value = new EditText(getActivity());
String value = req1estimate_value.getText().toString();
rl2.addView(req1estimate_value);
}
Try this. You should instantiate relative layout (rl1) at out of for loop, and should add child views with in that, so that all views could belongs to a parent layout. After that for accessing the values of all EditText you can use following:
String viewValue;
ViewGroup rootView = (ViewGroup) rl1;
int count = rootView.getChildCount();
for (int i = 0; i < count; i++) {
View view = rootView.getChildAt(i);
if (view instanceof EditText) {
viewValue = ((EditText) view).getText().toString();
Log.v("Value:: ", i + " " + viewValue);
} else if (view instanceof Spinner) {
viewValue = ((Spinner) view).getSelectedItem()
.toString();
Log.v("Value:: ", i + " " + viewValue);
}
}
Now after getting values you can put on a List or anywhere you want to use.

android TextView arrays

I am making a word game in which each a user has multiple guesses, each one made up of multiple TextViews. So far my code reads:
TextView[] guess1 = new TextView[numTextViews];
guess1[0] = (TextView) findViewById(R.id.Guess1_1);
guess1[1] = (TextView) findViewById(R.id.Guess1_2);
guess1[2] = (TextView) findViewById(R.id.Guess1_3);
guess1[3] = (TextView) findViewById(R.id.Guess1_4);
guess1[4] = (TextView) findViewById(R.id.Guess1_5);
with the xml looking like:
<TextView
android:id="#+id/Guess1_1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center"
android:text="#string/guessChar" />...
which repeats with android:id= changing.
I am going to be repeating myself if I type out TextView[] guess2 and all its elements.
What is a better way to go about this?
Would it be better to create all the TextViews programmatically as they are so similar?
This is how you can iterate through your views without the use of ids in repetitive code:
LinearLayout ll = (LinearLayout) findViewById(R.id.layout_containing_textviews);
for (int i = 0; i < ll.getChildCount(); i++) {
if (ll.getChildAt(i).getClass() == TextView.class) {
guess1[i] = (TextView)ll.getChildAt(i);
}
}
Make sure to tweak this in case you have non-TextView views since the i index will not be consecutive in that case. You can use another counter just for the TextViews.
Now if your layout has only TextViews, you don't even need an array. You can use that layout as a container/array the way it's used in the snipped above.
Do you know what is the amount of guesses for each text view?
I would suggest you to use reflection
Class clazz = R.id.class; // get the R class
Field f = clazz.getField("Guess1_" + "1");
int id = f.getInt(null); // pass in null, since field is a static field.
TextView currcell = (TextView) findViewById(id);
in this case it will bring the Guess1_1
for you case:
for (int i =0; i < numTextViews; i++)
{
Class clazz = R.id.class;
Field f = clazz.getField("Guess1_" + Integer.toString(i+1));
int id = f.getInt(null);
guess[i] = (TextView)findViewById(id);
}
but this only bring you the first array of Guess1 you need to convert it to generic code..
so some problems can be occur.. so read it with the xml as you have right now would be the easiest way..
Edit:
If the all textView have the same attributes you can also create it programmatically
LinearLayout view = new LinearLayout(this); // create new linear layout
view.setOrientation(LinearLayout.HORIZONTAL); // optional.. so the
// view will be horizontaly
view.setLayoutParams(new LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT)); // set the layout
// height and width
for (int i = 0; i < numOf ; i ++)
{
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
guess[i] = new TextView();
guess[i].setLayoutParams(lp);
guess[i].setID(i+1);
}
You could either create the textViews programmatically (and use inflate if you wish to use some xml too), or you could use the getIdentifier method , for example:
private static final String ID_FORMAT="Guess1_%d";
...
for(int i=0;i<10;++i)
{
String id=String.format(FORMAT,i);
TextView tv = (TextView) findViewById(getResources().getIdentifier(id, "id", getPackageName()));
//...
}
same goes if you wish to do a loop within a loop.
If the layout has a lot of views, I would suggest using an adapterView (listView,gridView,...) instead, and avoid creation of so many views (either programmatically or by xml).

How to create Custom Text Views in android?

Hai Friends,
I am parsing the url to display the contents in it, my requirement i have to display the each content in separate textviews.
For Instance:
Let us assume the contents in that url are FootBall, Carom , chess, VolleyBall and so on . I want to display FootBall as a individual textview similarly others. so i cannot declare the textviews in xml what i usually do.
(<TextView android:text=" " android:layout_width="wrap_content"
android:gravity="center_horizontal" android:paddingLeft="7dp" android:layout_height="wrap_content"
/>).
so i planned to create textview via java code
This is my parsing code which parse the url contents and store the result in a string array namely san_tagname; depending upon the length of this variable i want to create number of textviews.
List<Message_category> l_obj_tagname = new ArrayList<Message_category>();
l_obj_tagname = obj_parse1.parse_tagname();
System.out.println("l_obj_tagname"+l_obj_tagname.size());
String[] san = new String[l_obj_tagname.size()];
Iterator<Message_category> it_id1 = l_obj_tagname.iterator();
i=-1;
while (it_id1.hasNext()) {
i++;
san[i] = it_id1.next().toString();
System.out.println("Id="+san[i].toString());
san_tagname[i]=san[i];
//vm.setTitle(it.next().toString());
}
for(int z=0;z<san_tagname.length;z++)
{
//how to create textview here ...............
}
I am really struggling on this, pls help me regarding on this friends.................
Thanks In Advance
Tilsan The Fighter...
TextView tv = new TextView(context);
tv.setText(myText);
parent.addView(tv, {LayoutParams for parent container type})
Here is the answer,
Parse the Contents from web
//manipulation to parse id
List<Message_category> l_obj_id = new ArrayList<Message_category>();
l_obj_id = obj_parse1.parse_id();
VAL1 = new String[l_obj_id.size()];
Iterator<Message_category> it_id = l_obj_id.iterator();
while (it_id.hasNext()) {
i++;
VAL1[i] = it_id.next().toString();
System.out.println("Id="+VAL1[i].toString());
//vm.setTitle(it.next().toString());
}
//manipulation to parse tagname
List<Message_category> l_obj_tagname = new ArrayList<Message_category>();
obj_parse1.parse_tagname();
obj_parse1.storedata();
san_tagname= new String[obj_parse1.santagname.length];
for(int k=0;k<obj_parse1.santagname.length;k++)
{
san_tagname[k]=ParsingHandler.temptag[k];
if(san_tagname[k].contains("%20"))
{
san_tagname[k]=san_tagname[k].replace("%20"," ");
System.out.println("San_tagName1"+san_tagname[k]+"S"+k);
}
else
{
System.out.println("San_tagName2"+san_tagname[k]+"S"+k);
}
}
gal_lay = (LinearLayout) findViewById(R.id.rl_1);
navagtion_bar= (LinearLayout) findViewById(R.id.san_tag);
hv = (HorizontalScrollView)findViewById(R.id.gv);
// This is the Code i needed finally i stirkes with the help of hackbod
**for(int z=0;z<san_tagname.length;z++)
{
TextView san_text[]= new TextView[san_tagname.length];
san_text[z]= (TextView) new TextView(this);
san_text[z].setText(" "+san_tagname[z]+" ");
san_text[z].setTextSize(15);
navagtion_bar.addView(san_text[z]);
}**

Categories

Resources