Android Studio: Create a for-loop for strings - java

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

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

Java Dynamic Names

I know, that Java doesn't have a pre-processor, so some stuff is more or less impossible in java.
Is there really NO way to fill those arrays with dynamic names in a loop?
I'd like to have something like:
for(int i=0;i<5;i++){
earnTvs[i]=(TextView) findViewById(R.id.INSERT_GREAT_TRICK_HERE("earn"+i+"Tv"));
}
instead of
earnTvs[0] = (TextView) findViewById(R.id.earn1Tv);
earnTvs[1] = (TextView) findViewById(R.id.earn2Tv);
earnTvs[2] = (TextView) findViewById(R.id.earn3Tv);
earnTvs[3] = (TextView) findViewById(R.id.earn4Tv);
earnTvs[4] = (TextView) findViewById(R.id.earn5Tv);
timeTvs[0] = (TextView) findViewById(R.id.time1Tv);
...
ownTvs[0] = (TextView) findViewById(R.id.own1Tv);
...
costTvs[0] = (TextView) findViewById(R.id.build1Tv);
...
buyBtns[0] = (ImageButton) findViewById(R.id.buy1Bt);
...
progressBars[0] = (ProgressBar) findViewById(R.id.prog1pB);
...
buildBtns[0] = (Button) findViewById(R.id.build1Bt);
...
Or is there any kinky trick, that can be used?
I would do it like that:
final int[] earnTvsId = new int[] {R.id.earn1Tv, R.id.earn2Tv, R.id.earn3Tv, R.id.earn4Tv ...};
for(int i = 0; i < earnTvsId.length; ++i){
earnTvs[i] = (TextView) findViewById(earnTvsId[i]);
}
If you want to use the getIdentifier() method:
for (int i = 0; i < NUMBER_OF_TEXTVIEWS; ++i) {
final int resId = getResources().getIdentifier("earn" + i + "Tv", "id", getPackageName());
earnTvs[i] = (TextView) findViewById(resId);
}
With reflection. But I'm not sure if reflections are good here...
Class<?> idClass = R.id.getClass();
Field field = idClass.getField("earn" + i + "Tv");
TextView textView = (TextView) field.get(R.id);
You could use reflection for this purpose, but that's known to be slow on Android (especially older versions) and for the specified use case pretty unmaintainable; what if the ID's change? You'd have to make your changes in 2 places (XML & code) rather than let your IDE handle propagating the change.
If it's boilerplate you're annoyed with, perhaps you should take a look at Android Annotations. It uses compile-time annotations & an annotation processor to help you reduce boilerplate code.

How could I set a value on edittext

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.

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.

Initializing variable in for-loop

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.

Categories