Java Dynamic Names - java

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.

Related

obj.getString - Styling in android studio, possible?

Looking to style (bold, italic etc.) "quote" and "name", but have tried several potential solutions with no luck:
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.setText(tasks[0]);
setBtnCopyOnClick(tasks[0]); //Here
String a = "quote";
SpannableString spanned = new SpannableString(a);
spanned.setSpan(new UnderlineSpan(), 1, a.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
}
}
They both generate in the same textView, so unfortunately I can only style all, or not at all.
If you are looking to style only specific parts of text you should be using spans. The Android Developers site has good documentation on this which you can read here.
For your particular use case pay most attention to the StyleSpan which allows you to set Typeface flags.
For example:
String a = "underlined text";
String b = " normal text";
SpannableString spanned = new SpannableString(a + b);
spanned.setSpan(new UnderlineSpan(), 0, a.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

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.

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