Initializing variable in for-loop - java

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.

Related

Change text styling - settextView getString

I have two strings that are pulled from json, need to change styling for both elements.
My code is:
private void settextView(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
String[] tasks = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
tasks[i] = obj.getString("quote") + "\n\n" + obj.getString("name");
TextView quote = null;
quote.setTextColor(Color.parseColor("#FFFFFF"));
textView.setText(tasks[0]);
setBtnCopyOnClick(tasks[0]); //Here
}
}
As you can see, I have tried to insert:
TextView quote = null;
quote.setTextColor(Color.parseColor("#FFFFFF"));
However this doesn't do anything. Anyone have any ideas? I could be doing this the completely wrong way.
I would have had both strings separate in my .xml file, however it is pulled through as one.
TextView quote=null;
quote=findViewById(R.id.textView1);
this is not working because you give only null value to TextView;
here textview1 is id of TextView in you xml file;
replace textView1 with your textview id

Android Studio: Create a for-loop for strings

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

How to programmatically update the variable to match the iteration

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.

how to get values from dynamically created edittexts

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.

setImageResource from a string

I would like to change the imageview src based on my string, I have something like this:
ImageView imageView1 = (ImageView)findViewById(R.id.imageView1);
String correctAnswer = "poland";
String whatEver = R.drawable+correctAnswer;
imageView1.setImageResource(whatEver);
Of course it doesnt work. How can I change the image programmatically?
public static int getImageId(Context context, String imageName) {
return context.getResources().getIdentifier("drawable/" + imageName, null, context.getPackageName());
}
use:
imageView1.setImageResource(getImageId(this, correctAnswer);
Note: leave off the extension (eg, ".jpg").
Example: image is "abcd_36.jpg"
Context c = getApplicationContext();
int id = c.getResources().getIdentifier("drawable/"+"abcd_36", null, c.getPackageName());
((ImageView)v.findViewById(R.id.your_image_on_your_layout)).setImageResource(id);
I don't know if this is what you had in mind at all, but you could set up a HashMap of image id's (which are ints) and Strings of correct answers.
HashMap<String, Integer> images = new HashMap<String, Integer>();
images.put( "poland", Integer.valueOf( R.drawable.poland ) );
images.put( "germany", Integer.valueOf( R.drawable.germany ) );
String correctAnswer = "poland";
imageView1.setImageResource( images.get( correctAnswer ).intValue() );

Categories