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.
Related
I am very new to android programming and am trying to complete my first app. It is a recipe converter.
I have stored my recipe details in a SQLite DB and the text for ingredients is just one multiline string separated by carriage returns. I have used a cursor to get the ingredient data into a textview which returns text like (could be numerous variants):
100ml Water
500 g Mince
2 x 400g can crushed tomatoes
etc.
I originally had each Qty, Unit and Ingredient Description stored separately in the database which made life easy when converting but I chose to store it in a multiline string to allow copying and pasting of ingredients from the internet or another source.
I am attempting to extract the numbers and then multiply them by a percentage, then return the new converted numbers, and the corresponding unit and description to get something like this:
(multiplied by 200%)
200ml Water
1000g Mince
4 x 400g can crushed tomatoes
I just don't know how to do it though. Can anyone help please?
Thanks
UPDATE:
I have tried to do something like this to get the numbers.
public void Split() {
TextView tvSplit = (TextView) findViewById(R.id.tvSplit);
final TextView tvTest = (TextView) findViewById(R.id.tvTest);
String s = tvTest.getText().toString();
for (int i =0;i <= tvTest.getLineCount();i++){
tvSplit.setText("");
String text = s.replaceAll("\\D+", ",");
tvSplit.append(text);
tvSplit.append("\n");
}
That shows me all of the numbers with a "," between them but it also includes all numbers in the string like in the above example prior to conversion it would show 100,500,2,400 when I only need 100,500,2. Then from that point I'm not sure how I would convert them all. My "fresh to programming mind" thought that I could store these in a temp SQL table by INSERT INTO tablename (id, originalvalues) VALUES (my string ie 100,500,2).
I could then pull them back out, do the calculation, update the table, then add them back into my textview with the remaining string. I haven't got that far yet, so I'm just wondering what the correct way to do it is.
UPDATE 2:
As per my comments, this is the code I used to show an alert dialog with each item listed on a separate line, I then used the selected line to find the number before any " " to then display the text on the screen.
public void PopUpSpinnerDialogue() {
final TextView tvTest = (TextView) findViewById(R.id.tvTest);
final TextView tv2 = (TextView) findViewById(R.id.tvTest2);
String s = tvTest.getText().toString();
final ArrayAdapter myAdapter = new ArrayAdapter<String>(this,
R.layout.my_dropdown_style, s.split("\n"));
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
builder.setTitle("Please choose the key ingredient you need to scale your recipe by.")
.setCancelable(false)
.setAdapter(myAdapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
try {
String itemName = myAdapter.getItem(which).toString();
String[] parts = itemName.split(" ");
String itemNumStr = parts[0];
TextView tvLineName = (TextView) findViewById(R.id.tvIngredientSelect);
EditText et1 = (EditText) findViewById(R.id.etRecipeQtyConvert);
EditText et2 = (EditText) findViewById(R.id.etQtyHave);
tvLineName.setText(itemName);
String b4Space = itemNumStr.replaceAll("\\D+", "");
tv2.setText(b4Space);
et1.setText(b4Space);
et2.setText(b4Space);
calculateKeyIngredientPercent();
} catch (Exception e) {
Toast.makeText(SelectConvertMethod.this, "Your ingredient must have a QTY. eg. 100ml.", Toast.LENGTH_SHORT).show();
}
}
});
android.app.AlertDialog alert = builder.create();
alert.show();
}
It is this idea that I think I can use but I don't know how to code it and then display the results.
UPDATE 3:
The code or at least the idea of the code I am trying to use is this.
TextView tvSplit = (TextView) findViewById(R.id.tvSplit);
final TextView tvTest = (TextView) findViewById(R.id.tvTest);
String s = tvTest.getText().toString();
for (int i =0;i <= tvTest.getLineCount();i++){
String[] ingreds = s.split("\n");
tvSplit.setText("");
String[] parts = ingreds.split(" ");
String Qty = parts[0];
String Units = parts[1];
String Ingredients = parts[2];
Integer QtyInt = Integer.parseInt(Qty);}
ingreds.split doesn't work and also, I don't know how to specify splitting the parts for each i.
I ended up using regex. It allowed the data to be entered with or without a space. So I ended up using this code to pull out the Qty of each line, multiply it by a percentage, append the text (units,ingredient description) to the line, then add it to a string array, to add to my alert dialog.
Code is here.
public void Split() {
final TextView tv2 = (TextView) findViewById(R.id.tvTest2);
TextView tvTest = (TextView) findViewById(R.id.tvTest);
TextView tvPercent = (TextView) findViewById(R.id.tvPercent);
String tvP = tvPercent.getText().toString();
String tvNumOnly = tvP.replaceAll("\\D+", "");
Integer PercentVal = Integer.parseInt(tvNumOnly);
String s = tvTest.getText().toString();
StringBuilder sb = new StringBuilder();
Pattern p = Pattern.compile("((\\d*) ?(.*)(?:\\n*))");
Matcher m = p.matcher(s);
while (m.find()) {
String Qty = m.group(2) + ".00";
String Ingred = m.group(3);
Float QtyFloat = Float.parseFloat(Qty);
Float newQTY = (QtyFloat * PercentVal) / 100;
String newQTYstr = newQTY.toString();
sb.append(newQTYstr + " " + Ingred + "\n");
}
String[] lines = sb.toString().split("\n");
String[] IngredArray = Arrays.copyOfRange(lines, 0, lines.length - 1);
final ArrayAdapter myAdapter = new ArrayAdapter<String>(this,
R.layout.my_dropdown_style, IngredArray);
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
builder.setTitle("Please choose the key ingredient you need to scale your recipe by.")
.setCancelable(false)
.setAdapter(myAdapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
try {
String itemName = myAdapter.getItem(which).toString();
String[] parts = itemName.split(" ");
String itemNumStr = parts[0];
TextView tvLineName = (TextView) findViewById(R.id.tvIngredientSelect);
EditText et1 = (EditText) findViewById(R.id.etRecipeQtyConvert);
EditText et2 = (EditText) findViewById(R.id.etQtyHave);
tvLineName.setText(itemName);
String b4Space = itemNumStr.replaceAll("\\D.\\D+", "");
tv2.setText(b4Space);
et1.setText(b4Space);
et2.setText(b4Space);
calculateKeyIngredientPercent();
} catch (Exception e) {
Toast.makeText(SelectConvertMethod.this, "Your ingredient must have a QTY. eg. 100ml.", Toast.LENGTH_SHORT).show();
}
}
});
android.app.AlertDialog alert = builder.create();
alert.show();
// Toast.makeText(SelectConvertMethod.this, sb, Toast.LENGTH_LONG).show();
}
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
}
}
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.
I have two editText. First edit text is amount, second edit text is description. I get the amunt edit text values float, description edit text values string. But error when control values. I think wrong "(tutarEdit.getText().toString().equals("")".
Thanks in Advance..
final EditText tutarEdit = (EditText) layout.findViewById(R.id.editTextTutar);
final EditText aciklamaEdit = (EditText) layout.findViewById(R.id.editTextAciklama);
Float tutar = Float.parseFloat(tutarEdit.getText().toString());
String aciklama = aciklamaEdit.getText().toString();
if(tutarEdit.getText().toString().equals("") || aciklamaEdit.getText().toString().equals("")){
Toast.makeText(MainActivity.this, "Void", Toast.LENGTH_LONG).show();
}
You are getting parse error when tutarEdit is "", surround it with try/catch
Float tutar = 0;
try {
tutar = Float.parseFloat(tutarEdit.getText().toString());
} catch (Exception e) {
e.printStackTrace();
}
My button sends a parameter to the function.
<Button
android:id="#+id/tela1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Chinese Day"
android:onClick="loadPage"
android:tag="page1"
/>
My function should use this parameter to load the page1 activity.
public void loadPage(View view) {
String page = (String) view.getTag();
setContentView(R.layout.page);
}
How to make this work?
Tks
You want to specify in the button's tag the name of the layout, right?
Try the following:
String page = (String) view.getTag();
int layoutId= getResources().getIdentifier(page, "layout", getPackageName());
setContentView(layoutId);
Hope this helps.
You could use Java reflection API.
Each activity is an integer in R.layout. You only need to search for the attribute inside R.layout and then get its integer value to shove into setContentView.
try {
String tag = (String) btn.getTag(); // Button in variable "btn"
Class<R.layout> cls = R.layout.class;
Field field = cls.getDeclaredField(tag);
Integer obj = (Integer) field.get(null); // You could do these two in one line
int value = obj.intValue();
Log.i("Test", "Actvity id code = " + obj.toString()); // Testing code
setContentView(value);
}
catch (Exception e) {
e.printStackTrace();
return;
}