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.
Related
I want to call a specific EditText which is named after my matrice location, I mean, building the id for EditText with a string and setting it afterwards.
now I need to set the editText01 text in the layout, normally I would set like this:
EditText et = (EditText) findViewById(R.id.editText01);
editText01.setText("WHATEVER I NEED");
BUT, I can't access by the id name because I have to access a specific one, based on the row, column so it needs to be something like:
String row = "0"; // row index converted to string, for example
String column = "1"; // column index converted to string, for example
String string = "editText" + row + column; // string should be editText01
string.setText("WHATEVER I NEED"); //WRONG LINE
Solution 1:
In your case, you can check the R.java class and get the id of editText.
But I recommend solution 2 to avoid use reflection in your code.
Here is the code of using reflection.
private int findIdByName(String nameOfId) {
try {
Class IdFolder = Class.forName(context.getPackageName()+".R$id");
Field field = IdFolder.getField(nameOfId);
return (int) field.get(null);
} catch (ClassNotFoundException e) {
Log.e(TAG, "can not find R.java class");
e.printStackTrace();
} catch (NoSuchFieldException e) {
Log.e(TAG, "the field of resource not defined");
e.printStackTrace();
} catch (IllegalAccessException e) {
Log.e(TAG, "can not get static field in R");
e.printStackTrace();
} catch (ClassCastException e) {
Log.e(TAG, "the value of field is not integer");
e.printStackTrace();
}
return 0;
}
String idName = "editText" + row + column; // string should be editText01
int id = findIdByName(idName);
if (id != 0)
EditText editText01 = findViewById(id);
Solution 2:
You must create EditText in for and set an id for each one. Then put each EditText into an array list.
So every time that you want access to an EditText you have all object in the array list. for more understanding what I said see below:
List<EditText> list = new ArrayList();
for (int i=0; i<100; i++) {
EditText editText = new EditText(context);
editText.setId("editText" + row + column);
list.add(editText);
}
and when you want an EditText you can call this method:
private EditText findEditText(String id) {
for (EditText editText: list)
if (editText.getId().equals(id)
return editText;
return null;
}
also don't forget to add each EditText in the view. For example you can put a LinearLayout in your layout and after create each EditText add that into LinearLayout. something like this put in the for:
LinearLayout linear = findViewById(R.id.linear);
for (int i=0; i<100; i++) {
//...
linear.addView(editText)
/...
}
If you do not understand what I said, feel free to put the comment and ask questions.
to create id using String to call specific edit text use this code
String viewID="editText" + row + column; // string should be editText01
//id for view
int resID= getResources().getIdentifier(viewID,"id", getPackageName());
EditText edit= (EditText) findViewById(resID);
edit.setText("WHATEVER I NEED");
In this code create Edittext id using string
You should set the tags for all edit text like
EditText et = new EditText(this);
et.setTag(<some tag >);
then make use to findViewByTag API to retrieve the edit text
EditText et = (EditText)findViewByTag(<tag name>);
You can use getIdentifier():
int id = context.getResources().getIdentifier("editText" + row + column, "id", context.getPackageName());
EditText et = (EditText) findViewById(id);
et.setText("WHATEVER I NEED");
You can omit context inside an activity class.
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>
I have an app in which I am showing data from JSON. I am displaying data in a dynamic textview on the right and left side of the relative layout. Now I want to add this layout in an existing layout so that I can apply an OnClickListener on the textview. Right now I am getting data into a string and then setting that string into static textviews in the left and right side of the layout.
How would it be possible to generate textview dynamically on the basis of number of data I am getting from JSON ?
for (Region object : temp.phonelist.regionList)
{
if (object.getCCInfoShortDesc() != null || !(object.getCCInfoShortDesc().equals(null)))
{
Log.i("nullexception", "nullexception");
holder.tvDescription.setText(object.getCCInfoShortDesc());
holder.tvDescription.setVisibility(View.VISIBLE);
}else {
Log.i("nullexception1", "nullexception1");
holder.tvDescription.setVisibility(View.GONE);
}
leftContent += object.getCCInfoLeft() + ":" + "\n";
rightContent += object.getCCInfoRight() + "\n";
}
Log.i("lefftcontent", leftContent);
Log.i("rightcontent", rightContent);
if (leftContent != null) {
holder.tvData2.setText(leftContent);
holder.tvData2.setVisibility(View.VISIBLE);
}
if (rightContent != null) {
holder.tvData1.setText(rightContent);
holder.tvData1.setVisibility(View.VISIBLE);
}
You can do it in this way..
final int Count = < Number of TextViews>; // total number of textviews to add
final TextView[] TextViewsARR = new TextView[N]; // create an empty array;
for (int i = 0; i < Count; i++) {
// create a new textview
final TextView rowTextView = new TextView(this);
// set some properties of rowTextView or something
rowTextView.setText("This is row #" + i);
// add the textview to the linearlayout
myLinearLayout.addView(rowTextView);
// save a reference to the textview for later
TextViewsARR [i] = rowTextView;
}
I have a sample below that generates a checkbox dynamically, If you
observe i am generating the checkbox based on the cursor count.
You can adapt this saple to your needs
Instead of checkbox use a texview
Give any layout like linear, relative etc and generate views
dynamically
private CheckBox chkBoxMealType[] = null;
mCursor = db.rawQuery("SELECT meal_type_id,meal_type_name FROM meal_type_mas", null);
if(mCursor.moveToFirst()){
do{
if(chkBoxMealTypeCnt==0){
chkBoxMealType=new CheckBox[mCursor.getCount()];
}
//create a general view for checkbox
chkBoxMealType[chkBoxMealTypeCnt]= new CheckBox(getActivity());
//Create params for veg-checkbox
//Reason:: we don't need to worry about the data exist in cuisine_type_mas table
chkBoxMealType[chkBoxMealTypeCnt].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
chkBoxMealType[chkBoxMealTypeCnt].setTextColor(getResources().getColor(R.color.searchGoldLight));
chkBoxMealType[chkBoxMealTypeCnt].setTextSize(TypedValue.COMPLEX_UNIT_SP,12);
chkBoxMealType[chkBoxMealTypeCnt].setTag(mCursor.getString(mCursor.getColumnIndexOrThrow(meal_type_mas.COLUMN_MEAL_TYPE_ID)));
chkBoxMealType[chkBoxMealTypeCnt].setText(WordUtils.capitalizeFully(mCursor.getString(mCursor.getColumnIndexOrThrow(meal_type_mas.COLUMN_MEAL_TYPE_NAME))));
mealTypeContainer.addView(chkBoxMealType[chkBoxMealTypeCnt]);
//since cursor count starts from 0 last count must be allowed
chkBoxMealTypeCnt++;
}while(mCursor.moveToNext());
Log.d("", "");
}
I have another sample..... Download this project(Click Here) and run in your editor
Snapshot::
Firstly you need to add a View in your layout ... Like you may try using LinearLayout or HorizontalLayout ... and then attach/add your dynamic textview to that layout.
Pragmatically you may try like this
packageButtons = new ArrayList<TextView>(); // Create your textview arraylist like this
for(int a = 0; a < your_text_view_from_json.size(); a++){
final TextView rowTextView;
rowTextView = new TextView(getApplicationContext());
rowTextView.setText(taxi_type_spin.get(a).taxi_type);
rowTextView.setTextSize(15);
rowTextView.setTextColor(getResources().getColor(R.color.white));
LinearLayout.LayoutParams lparam = new LinearLayout.LayoutParams(0,
LinearLayout.LayoutParams.WRAP_CONTENT, 1);
//rowTextView.setPadding(0, 0, 0, 0);
packageButtons.add(rowTextView);
rowTextView.setLayoutParams(lparam);
rowTextView.setId(a);
final int b = a;
// get value of clicked item over here ..
rowTextView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Button btn = (Button)v;
String get_value = btn.getText().toString();
//Toast.makeText(getApplicationContext(), "Button name is : " + get_value + " AND ID IS : " + rowTextView.getId(), Toast.LENGTH_LONG).show();
if(taxi_type_spin.get(b).taxi_type.equalsIgnoreCase(Utils.Hourly_Package))
{
setTaxiType(rowTextView.getId(),true);
ll_spin.setVisibility(View.VISIBLE);
}
else
{
setTaxiType(rowTextView.getId(),false);
ll_spin.setVisibility(View.GONE);
}
setSelectedButtonColor(b);
}
});
// add the textview to the linearlayout
myLinearLayout.addView(rowTextView);
NOTE rowTextView .. this is your default view attached to your XML file
Hope it helps!
private void setLayout(LinearLayout llayout,
final ArrayList<String> items) {
for (int i = 0; i < items.size(); i++) {
LinearLayout row = null;
LayoutInflater li = getLayoutInflater();
row = (LinearLayout) li.inflate(R.layout.custom_item,
null);
ImageView image = (ImageView) row.findViewById(R.id.image);
llayout.addView(row);
}
}
I would suggest you to use ArrayList, because the class java.util.ArrayList provides resizable-array, which means that items can be added and removed from the list dynamically.
and get value from ArrayList something like this:
for(int i=0; i<arrayList.size(); i++)
{
textName.setText(object.getName());
}
How it is possible to genrate textview dynamically
on the basis of number of data i am getting from json.
You need to create TextView and add it to the parent layout each time you iterate on the forloop. So you will have textView for each of the element of the temp.phonelist.regionList
sample:
for (Region object : temp.phonelist.regionList)
{
TextView tx = new TextView(context); //creating a new instance if textview
//yourstuff goes here
tx.setText(text_you_want);
yourView.addView(tx); //this is to add the textView on each iteration
}
here is your solution do this way,Take one Layout(Linear or Relative) and add control dynamically....
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
for (int i = 0; i < 4; i++)
{
TextView txtDemo = new TextView(getActivity());
txtDemo .setTextSize(16);
txtDemo .setLayoutParams(lp);
txtDemo .setId(i);
lp.setMargins(0, 10, 0, 0);
txtDemo .setPadding(20, 10, 10, 10);
txtDemo .setText("Text View"+ i);
linearlayout.addView(txtDemo );
}
}
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).
I'm trying to update/populate xml on run-time. The textViews are displayed fine but it seems like it fails position them correctly after the first item (see the else statement). Is it because getId() is not recognised or am I totally wrong?
for(int x=1; x<13; x++){
String prompt="PROMPT_"+String.valueOf(x);
String promptValue = myTacorCursor.getString(myTacorCursor.getColumnIndex(prompt));
//if not empty draw a row
if (!promptValue.equals("")){
//insert new rows into layout
RelativeLayout myLayout = (RelativeLayout) findViewById(R.id.RelativeLayout1);
TextView promptLabel = new TextView(this);
promptLabel.setTextAppearance(this, android.R.style.TextAppearance_DeviceDefault_Large);
promptLabel.setText(myTacorCursor.getString(myTacorCursor.getColumnIndex("PROMPT_"+String.valueOf(x))));
promptLabel.setId(1);
((RelativeLayout) myLayout).addView(promptLabel);
RelativeLayout.LayoutParams mLayoutParams1=(RelativeLayout.LayoutParams)promptLabel.getLayoutParams();
mLayoutParams1.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
if (i==1){
mLayoutParams1.addRule(RelativeLayout.BELOW,R.id.textView7);
Log.w("ID is:", String.valueOf(promptLabel.getId()));
} else{
mLayoutParams1.addRule(RelativeLayout.BELOW,promptLabel.getId());
Log.w("ID is:", String.valueOf(promptLabel.getId()));
}
i++;
}
}
I'm trying to display:
(textView)LABEL xx R.id.textview7
<-- here would be the inserted columns -->
(text view) prompt 1
(text view) prompt 2
(text view) prompt 3
... etc ...'
Setting ids dynamically is OK. Just some more attentiveness and your code works.
As far as you're in the for loop, it's better to increment index only in one place.
After you've changed the LayoutParams of the View you need to set it back: promptLabel.setLayoutParams(layoutParams)
Try this. It should work:
public class MainActivity extends Activity {
private static final int BASE_ID = 1;
private static final int ITEMS_COUNT = 13;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout rootLayout = (RelativeLayout) findViewById(R.id.root);
for (int index = BASE_ID; index < ITEMS_COUNT; index++) {
String prompt = "PROMPT_" + String.valueOf(index);
// if not empty draw a row
// insert new rows into layout
TextView promptLabel = new TextView(this);
promptLabel.setTextAppearance(this,
android.R.style.TextAppearance_DeviceDefault_Large);
promptLabel.setText(prompt);
promptLabel.setId(index);
rootLayout.addView(promptLabel);
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) promptLabel
.getLayoutParams();
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
if (index == BASE_ID) {
layoutParams.addRule(RelativeLayout.BELOW, R.id.top);
Log.d("ID is:", String.valueOf(index));
} else {
layoutParams.addRule(RelativeLayout.BELOW, index - 1);
Log.d("ID is:", String.valueOf(index - 1));
}
promptLabel.setLayoutParams(layoutParams);
}
}
}
You don't need to construct the whole layout programatically. Define it in separate layout xml file and then use layout inflater to inflate it. After that add it where you want it.
I have never seen ids assigned programatically, but with my suggestion you can define them in the xml as usual.
PS: Here is a good example explaining how to use LayoutInflater.