I have the following for-each loop:
for(DataSnapshot data: dataSnapshot.getChildren()){
TextView textview = (TextView) findViewById(R.id.textview);
String message = data.getKey().toString();
textview.setText(message);
}
Now there are different textviews with ids textview1 textview2 textview3..etc (can grow and shrink). How do I do that in the for-each loop though? Using some counter and somehow concat it to the variable?
I want the different messages to display in the different textviews
You will have to modify your code like this:
int i = 1;
for(DataSnapshot data: dataSnapshot.getChildren()){
int id = getResources().getIdentifier("textview" + i, "id", getPackageName());
TextView textview = (TextView) findViewById(id);
String message = data.getKey().toString();
textview.setText(message);
i++;
}
with getResources().getIdentifier("textview" + i, "id", getPackageName()); you find the integer id of a View by using its name id.
You may have to supply a Context to getResources() like:
context.getResources().getIdentifier("textview" + i, "id", context.getPackageName());
if this code is not inside an activity.
Related
Ok so im working on a table where i get everything needed from my shared preferences, save them in Strings and then set text in the single rows of the table. Its working but the thing is:
I feel like this would be possible with way less code if i just used a foor loop. Also this would make it possible to add and delete rows if i want to. only problem i have is: i dont know how to make this for loop. i mean i would need to scroll through "e1, e2, e3, d1..." etc. Anyone of you guys have an idea?
Here is the code:
e1 = (TextView) findViewById(R.id.e1);
e2 = (TextView) findViewById(R.id.e2);
e3 = (TextView) findViewById(R.id.e3);
d1 = (TextView) findViewById(R.id.d1);
d2 = (TextView) findViewById(R.id.d2);
d3 = (TextView) findViewById(R.id.d3);
t1 = (TextView) findViewById(R.id.t1);
t2 = (TextView) findViewById(R.id.t2);
t3 = (TextView) findViewById(R.id.t3);
n1 = (TextView) findViewById(R.id.n1);
n2 = (TextView) findViewById(R.id.n2);
n3 = (TextView) findViewById(R.id.n3);
//shared preferences
SharedPreferences mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = mPreferences.edit();
//first row
String event1 = mPreferences.getString("event", "");
String date1 = mPreferences.getString("date", "");
String time1 = mPreferences.getString("time","");
String name1 = mPreferences.getString("name","");
//second row
String event2 = mPreferences.getString("event1", "");
String date2 = mPreferences.getString("date1", "");
String time2 = mPreferences.getString("time1","");
String name2 = mPreferences.getString("name1","");
//third row
String event3 = mPreferences.getString("event2", "");
String date3 = mPreferences.getString("date2", "");
String time3 = mPreferences.getString("time2","");
String name3 = mPreferences.getString("name2","");
//set text in the rows
e1.setText(event1);
d1.setText(date1);
t1.setText(time1);
n1.setText(name1);
e2.setText(event2);
d2.setText(date2);
t2.setText(time2);
n2.setText(name2);
e3.setText(event3);
d3.setText(date3);
t3.setText(time3);
n3.setText(name3);
Well, in Java you should rely on runtime checking. It's good practice! And when you'd want to save some space and dynamically refer to variables doing something like:
for (int i = 0; i < 3; i++) {
---- dynamically refer to variables here somehow ---
}
you deprive yourself of runtime checking. Thus bugs may occur.
You may save some space by doing:
e1.setText(mPreferences.getString("event", ""));
d1.setText(mPreferences.getString("date", ""));
t1.setText(mPreferences.getString("time",""));
n1.setText(mPreferences.getString("name",""));
Let's say, we can do it dynamically:
Create array of string[] NamesTimes. Put all your stuff in array.
Iterate over the array in a loop with adding new fields.
Example:
public class MainActivity extends AppCompatActivity {
LinearLayout linearLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout = findViewById(R.id.linear_layout);
//Adding your TextViews
for (int i = 1; i <= NamesTimes.length; i++) {
TextView textView = new TextView(this);
textView.setText("This is content " + NamesTimes[i]);
linearLayout.addView(textView);
}
}
}
This question already has answers here:
Access resource string by string name in array
(2 answers)
Closed 7 years ago.
I have an Array of countries (Strings) - (Comes from a webservice) as well as a corresponding list of Drawables which are their flags - (In the drawables folder)
The Drawables are labelled "cape_verde" or "canada" but when the names come down from the webservice they come down as "Cape Verde" or "Canada".
When I call the webservice I do a lowercase conversion and replace some characters as seen in the code below:
String lowerCaseName = countryNameInArray.countryName.toLowerCase();
String replacedCountryName = lowerCaseName.replaceAll(" ", "_");
My thought was that I can some how set the
R.drawable.replacedCountryName
but obviously it cant take Strings as its requires an int.
EDIT:
public View getCustomView(int position, View convertView, ViewGroup parent) {
countries = res.getStringArray(R.array.countries);
/********** Inflate spinner_rows.xml file for each row ( Defined below ) ************/
View row = inflater.inflate(R.layout.country_drop_down_rows, parent, false);
/***** Get each Model object from Arraylist ********/
tempValues = null;
tempValues = (countryDropDownItem) data.get(position);
TextView label = (TextView) row.findViewById(R.id.spinner_country_textview);
ImageView country = (ImageView) row.findViewById(R.id.spinner_county_flag_imageview);
if (position == 0) {
// Default selected Spinner item
label.setText("South Africa"); //get the country text
country.setImageResource(R.drawable.south_africa);
} else {
String lowerCaseName = countries.toString().toLowerCase();
String replacedCountryName = lowerCaseName.replaceAll(" ", "_");
// Set values for spinner each row
label.setText(tempValues.countryName); //get the country text
country.setImageResource(res.getIdentifier(replacedCountryName, "drawable", "com.app.app" ));
}
return row;
}
Has anyone got an idea how I can go around this?
Thanks
Try this:
ImageView iw= (ImageView)findViewById(R.id.imageView1);
int resID = getResources().getIdentifier(drawableName, "drawable", getPackageName());
iw.setImageResource(resID);
drawableName is your file/image name, try to store in /src/asset/image.png
getResources().getIdentifier(
"imagename", "drawable", "com.package.application")
is it possible to set a value into a editable edittext like this?
LayoutInflater layoutInflater = LayoutInflater.from(getBaseContext());
View promptView = layoutInflater.inflate(R.layout.prompt_dialog, null);
final EditText input = (EditText) promptView.findViewById(R.id.input_prompt);
TextView txt_prompt_mensaje = (TextView) promptView.findViewById(R.id.txt_prompt_mensaje);
Editable value = input.getText();
int suma_valor = Integer.parseInt(value.toString());
suma_valor = suma_valor + Integer.parseInt(value.toString());
Log.d("#### suma valor", Integer.toString(suma_valor));
input.setText(Integer.toString(suma_valor));
Using input.setText("Testing"); will give the editText the string of "Testing" in it's field. However you question seems vague when you say 'set a value'.
Another thing to add is that the editText will only take the values for when it is first instantiated.
I have created a tablelayout with dynamically created rows with 3 edittexts on every row. Say there are 5 rows with 3 edittexts on each, how can i get the the entered values from every first edittext from each row into an arraylits and calculating them.
Here is my code so far:
Public void addRow (View v) {
TableRow row = new TableRow(this);
EditText et1 = new EditText(this);
EditText et2 = new EditText(this);
EditText et3 = new EditText(this);
idCount++;
mRowCount++;
et1.setTag(a + idCount);
et1.setText(a + idCount);
et2.setTag(b + idCount);
et2.setText(b + idCount);
et3.setTag(c + idCount);
et3.setText(c + idCount);
mLayout.addView(row);
row.setId(mRowCount);
row.addView(et1);
row.addView(et2);
row.addView(et3);
Thanx in advance
ArrayList<String> stringList = new ArrayList<String>(); //Generic ArrayList to Store your Strings
stringList.add(et1.getText()) ;//do this for your 3 textviews
stringList.add(et2.getText()) ;
stringList.add(et3.getText()) ;
int count=0;
Iterator<String> iterator = stringList.iterator();
while (iterator.hasNext()) {
count=count+Integer.parseInt(iterator.next());
}
1) If you have the reference, you can access it with getText().
2) If you haven't the reference, you have to set an ID to every EditText and the you could reach them with findViewById()
by the getText() method
edt1.gettext();
If you are entering string data then use toString() method as
String res=edt1.getText().toString();
Depending how many rows you are likely to end up creating I would store a reference to the EditText objects when you create them. This may mean defining a row object for holding the three EditText objects, but just as east to create a Map:
Map<String, List<EditText>> mRows = new HashMap<String, List<<EditText>>();
When creating the new row you can modify your code so as to store the references:
Public void addRow (View v) {
TableRow row = new TableRow(this);
EditText et1 = new EditText(this);
EditText et2 = new EditText(this);
EditText et3 = new EditText(this);
List<EditText> row = new ArrayList<EditText>();
row.add(et1);
row.add(et2);
row.add(et3);
mRows.add("" + idCount, row);
I would also move that code into a separate function.
On submission you can now iterate over the map and pull the first entry out from each entry.
First of all you have to take EditText(View) from your table layout and
TableRow tr = (TableRow) v.getParent();
// Index of column of table layout it should be an Integer value.
EditText et = (EditText) tr.getChildAt(Your_Index);
EditText et1 = (EditText) tr.getChildAt(Your_Index);
EditText et2 = (EditText) tr.getChildAt(Your_Index);
Then you will get value of that edittext with following code
String a = et.getText().toString();
String b = et1.getText().toString();
String c = et2.getText().toString();
Hope it will help you.
I have code like this:
TextView wyniszczenie_zakres_bmi = (TextView)t.findViewById(R.id.wyniszczenie_zakres_bmi);
TextView wychudzenie_zakres_bmi = (TextView)t.findViewById(R.id.wychudzenie_zakres_bmi);
TextView niedowaga_zakres_bmi = (TextView)t.findViewById(R.id.niedowaga_zakres_bmi);
Can I do something like this?
List<String> arStan = new ArrayList<String>();
arStan.add("wyniszczenie");
arStan.add("wychudzenie");
arStan.add("niedowaga");
for(String s : arStan){
TextView s + _zakres_bmi = (TextView)t.findViewById(R.id. + s + _zakres_bmi);
}
I know it's not work but is there any solution for this?
Try this:
List<String> arStan = new ArrayList<String>();
arStan.add("wyniszczenie");
arStan.add("wychudzenie");
arStan.add("niedowaga");
for(String s : arStan) {
int myId = getResources().getIdentifier(s + "_zakres.bmi", "id", getPackageName());
TextView myTextView = (TextView)t.findViewById(myId);
// Do something with myTextView
}
If you need to save the textView references for later rather than acting on them immediately, then put myTextView into an array or hashtable after it's assigned.
Hashtable textViews = new Hashtable<String, TextView>();
List<String> arStan = new ArrayList<String>();
arStan.add("wyniszczenie");
arStan.add("wychudzenie");
arStan.add("niedowaga");
for(String s : arStan) {
int myId = getResources().getIdentifier(s + "_zakres.bmi", "id", getPackageName());
TextView myTextView = (TextView)t.findViewById(myId);
textViews.put(s + "_zakres.bmi", myTextView);
}
// When you need to get one of the TextViews:
TextView tv = textViews.get("niedowaga_zakres.bmi");
// Do something with tv.