txtt.setText(getString(R.string.("i" + j++))); - android

What's wrong with this code? I want to use id automatically. I think after R.string there is a mistake. What can ı do

Do it like this
public static int getStringIDFromName(String stringName)
{
int stringID= 0;
if(stringName == null
|| stringName.equalsIgnoreCase(""))
{
return 0;
}
try
{
#SuppressWarnings("rawtypes")
Class res = R.string.class;
Field field = res.getField(stringName);
stringID = field.getInt(null);
}
catch(Exception e)
{
// Error
}
return stringID;
}
Set your value like this
int stringVal = getStringIDFromName("i" + j++);
if( stringVal != 0)
txtt.setText(getResource().getString(stringVal));
This would work only if you are doing everything else right.

// initialization for TextView
TextView txtt = (TextView) findViewById(R.id.myTextViewId);
// set the text
txtt.setText(getResources().getString(R.string.mystring));

Related

get android element Id in Activity

How can I get element Id in android
<EditText
android:id="#+id/etCustomerNo"
I need access to id of editText in my activity (for example get "etCustomerNo" as a String).
Thank you.
I need to know id of all editText on layout
for (int i = 0; i < rl.getChildCount(); i++) {
if (rl.getChildAt(i) instanceof EditText) {
String id = String.valueOf(rl.getChildAt(i).getId());
}
}
getId() returns an int value instead of "etCustomerNo"
String s = getResources().getResourceEntryName(et.getId());
Et is your EditText object.
s is your id name.
by looking at View's source code inside toString() method, we can see how you can get the id name as string:
final int id = getId();
if (id != NO_ID) {
out.append(" #");
out.append(Integer.toHexString(id));
final Resources r = mResources;
if (Resources.resourceHasPackage(id) && r != null) {
try {
String pkgname;
switch (id&0xff000000) {
case 0x7f000000:
pkgname="app";
break;
case 0x01000000:
pkgname="android";
break;
default:
pkgname = r.getResourcePackageName(id);
break;
}
String typename = r.getResourceTypeName(id);
String entryname = r.getResourceEntryName(id);
out.append(" ");
out.append(pkgname);
out.append(":");
out.append(typename);
out.append("/");
out.append(entryname);
} catch (Resources.NotFoundException e) {
}
}
}
the entryname string is what you're looking for.
Simple.
EditText et=(EditText)FindViewById(R.id.etCustomerNo);
EditText edittext = (EditText) this.findViewById(R.id.etCustomerNo);
If you already have the editText, then try calling getId(). If you need to do anything further you'd like need to put together a switch statement formed of the various options:
private String getIdAsString(EditText editText) {
String value = null;
int id = editText.getId();
switch (id) {
case R.id.etCustomerNo:
value = "etCustomerNo";
break;
case R.id.edit_text_two:
value = "edit_text_two";
break;
}
return value;
}

Programmatically set R.ID

I downloaded a class from Catch The Cows, it is akin to a Google Map object or at least that is what I am using it for.
It parses an XML file which lists the areas of the screen that should be touchable, and then creates them with this method.
This is here for context, I have commented out some parts of code, and added my own to try and resolve my issue
private Area addShape( String shape, String name, String coords, String id) {
Log.v("IDS:", "id was "+id);
Area a = null;
String rid = id.replace("#+id/", "");
Log.v("IDS:", "rid was "+rid);
// Generate a new ID for the area.
int _id = 1;
View vi = findViewById(_id);
while (vi!=null) {
_id++;
vi = findViewById(_id);
}
//View.generateViewId(); //=0;
Log.v("IDS:", "After conversion final time "+_id);
/*
try {
Class<R.id> res = R.id.class;
Field field = res.getField(rid); // eg. rid = area10
_id = field.getInt(null);
Log.v("IDS:", "After conversion "+_id);
}
catch (Exception e) {
_id = 0;
Log.e("Exception ",e.getMessage());
} finally {
Log.v("IDS:", "After conversion final time "+_id);
}
*/
if (_id != 0) {
if (shape.equalsIgnoreCase("rect")) {
String[] v = coords.split(",");
if (v.length == 4) {
a = new RectArea(_id, name, Float.parseFloat(v[0]),
Float.parseFloat(v[1]),
Float.parseFloat(v[2]),
Float.parseFloat(v[3]));
}
}
if (shape.equalsIgnoreCase("circle")) {
String[] v = coords.split(",");
if (v.length == 3) {
a = new CircleArea(_id,name, Float.parseFloat(v[0]),
Float.parseFloat(v[1]),
Float.parseFloat(v[2])
);
}
}
if (shape.equalsIgnoreCase("poly")) {
a = new PolyArea(_id,name, coords);
}
if (a != null) {
addArea(a);
}
} else {
Log.v("Loading ID: ","_id was 0");
}
return a;
}
Unfortunately nothing was rendering on the screen, and this was because _id = 0. This should be changed with this bit of code:
try {
Class<R.id> res = R.id.class;
Field field = res.getField(rid); // eg. rid = area10
_id = field.getInt(null);
}
How ever I am not sure what it does to try and debug it, can anyone explain what this snippet is doing?
R is a Read-Only class. It is generate at compile time and You should not use reflection to modify its field. Also you should avoid reflection to access the fields values. You should use the official API.
The comment at the first row of the class is
/* AUTO-GENERATED FILE. DO NOT MODIFY. */

Android: If/Else statement makes app crash

I'm trying to tell if an android int is null by using If/Else
public void onClick(View v) {
EditText min = (EditText) findViewById(R.id.EditText01);
EditText max = (EditText) findViewById(R.id.maxnum);
EditText res = (EditText) findViewById(R.id.res);
int myMin = Integer.parseInt(min.getText().toString());
int myMax = Integer.parseInt(max.getText().toString());
String minString = String.valueOf(myMin);
String maxString = String.valueOf(myMax);
int f = (int) ((Math.random()*(myMax-myMin+1))+myMin);
if (minString.equals(""))
{
// Do Nothing
}
if (maxString.equals(""))
{
// Do Nothing
}
res.setText(String.valueOf(f));
There are no any errors, but when I'm running the app its crashing when im pressing the button.
I'm also trying to use null instead of "":
if (minString.equals(null))
{
// Do Nothing
}
if (maxString.equals(null))
{
// Do Nothing
}
And i have a crash.
Please help me!!!
public boolean equals (Object object)
Compares the specified object to this string and returns true if they are equal. The object must be an instance of string with the same characters in the same order.
So its returning error so if you want to check if its null then use == operator on the object.
if (maxString == null )
Use
int myMin = 0;
int myMax = 0;
if(min.getText().toString()!="")
myMin = Integer.parseInt(min.getText().toString());
if(max.getText().toString()!="")
myMax = Integer.parseInt(max.getText().toString());
String minString = String.valueOf(myMin);
String maxString = String.valueOf(myMax);
int f = (int) ((Math.random()*(myMax-myMin+1))+myMin);
if (minString.equals(""))
{
// Do Nothing
}
if (maxString.equals(""))
{
// Do Nothing
}
do if (maxString == null )
{
// do something
}
int variables can't be null
If a null is to be converted to int, then it is the converter which decides whether to set 0, throw exception, or set another value (like Integer.MIN_VALUE)
So if you convert int to string again you cannot get null value.
check = input.getText().toString();
try {
if (!check.equals("null")) {
int max = Integer.parseInt(input.getText().toString());
int constant1 = 1;
int constant2 = 1;
int nextNumber = 0;
int count = 0;
String fibResult = "";
for (int i = 0; i <= max; i++) {
fibResult += "F" + count + "=" + nextNumber + "\n";
constant1 = constant2;
constant2 = nextNumber;
nextNumber = constant1 + constant2;
count++;
}
dspResults.setText("\n" + fibResult);
} else {
dspResults.setVisibility(View.VISIBLE);
dspResults.setText("Invalid");
dspResults.setText(Gravity.CENTER);
dspResults.setTextColor(Color.DKGRAY);
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
public void onClick(View v) {
EditText min = (EditText) findViewById(R.id.EditText01);
EditText max = (EditText) findViewById(R.id.maxnum);
EditText res = (EditText) findViewById(R.id.res);
int myMin = Integer.parseInt(min.getText().toString());
int myMax = Integer.parseInt(max.getText().toString());
String minString = String.valueOf(myMin);
String maxString = String.valueOf(myMax);
int f = (int) ((Math.random()*(myMax-myMin+1))+myMin);
{
if (minString.equals(""))
{
// Do Nothing
res.setText(String.valueOf(f));
return false;
}
else if (maxString.equals(""))
{
// Do Nothing
res.setText(String.valueOf(f));
return false;
}
else
res.setText(String.valueOf(f));
return true ;
}

Avoid exception when there is no integer number filled in the edit text

I'm working with Android app, I have 5 edit text, and 1 button to sum the integer number from those edit text. Sometime user can let several edit text blanks. The problem is when the user let it blank, the exception will arise and I don't have any idea to handle it. These are my code
try
{
if (qty1 != null)
{
int jml1 = Integer.parseInt(qty1.getText().toString());
item1 = hrg1 * jml1;
}
else
{
qty1.setText("0");
}
if (qty2 != null)
{
int jml2 = Integer.parseInt(qty2.getText().toString());
item2 = hrg2 * jml2;
}
else
{
qty2.setText("0");
}
if (qty3 != null)
{
int jml3 = Integer.parseInt(qty3.getText().toString());
item3 = hrg3 * jml3;
}
else
{
qty3.setText("0");
}
if (qty4 != null)
{
int jml4 = Integer.parseInt(qty4.getText().toString());
item4 = hrg4 * jml4;
}
else
{
qty4.setText("0");
}
if (qty5 != null)
{
int jml5 = Integer.parseInt(qty5.getText().toString());
item5 = hrg5 * jml5;
}
else
{
qty5.setText("0");
}
int hasil = item1 + item2 + item3 + item4 + item5;
Toast.makeText(getApplicationContext(), "Berhasil", Toast.LENGTH_LONG).show();
total.setText(String.valueOf(hasil));
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), "Quantity can't be empty. Please type item quantity", Toast.LENGTH_LONG).show();
}
I have try to put condition with if but it doesn't help much. Thanks.
Try this,
if (qty1.getText().toString() != null && !(qty1.getText().toString().equals("")))
{
int jml1 = Integer.parseInt(qty1.getText().toString());
item1 = hrg1 * jml1;
}
instead of,
if (qty1 != null)
{
int jml1 = Integer.parseInt(qty1.getText().toString());
item1 = hrg1 * jml1;
}
This condition if (qty1 != null) checks if your editText is null but it doesn't check the data contained in it.
Repeat the same for all the other editText values.
put this condition
String s1= qty5.getText().toString().trim();
if(TextUtils.isEmpty(s1)) ///// isEmpty() <-----
{
// error message
}
else
{
// your code
}
If qty1 is yout edittext then you need to get the string from your edittext to check whether it is null or not.
So Change your all edittexts code as like this
if (qty1.getText().toString() != null && qty1.getText().toString().equals(""))
{
int jml1 = Integer.parseInt(qty1.getText().toString());
item1 = hrg1 * jml1;
}
else
{
qty1.setText("0");
}

Problem when creating an object and setting its variables

I'm making an app which for now, parses an url and takes some info from it. I want to use this values to create objects, put them into an arraylist, and show them on screen with a ListView layout.
Problem comes when i want to assign drawables values from the object. I want, depending on its values, assign a drawable or another. Here is the code:
Retransmision retransmision = new Retransmision();
retransmision.setIdioma(idioma);
retransmision.setTipo(tipo);
retransmision.setCalidad(calidad);
retransmision.setLink(link);
retransmision.setImagenLogo(tipo);
retransmision.setImagenCalidad(calidad);
retransmisionesDescargadas.add(retransmision);
I just create the object and assign some values with its methods. And heres the method wich is throwing nullPointerException:
public void setImagenCalidad(int calidad) {
if (calidad == 0) {
imagenCalidad = context.getResources().getDrawable(R.drawable.desconocida);
} else if(calidad <= 250) {
imagenCalidad = context.getResources().getDrawable(R.drawable.baja);
} else if(calidad <= 500) {
imagenCalidad = context.getResources().getDrawable(R.drawable.media);
} else if(calidad <= 750) {
imagenCalidad = context.getResources().getDrawable(R.drawable.alta);
} else if(calidad <= 1000) {
imagenCalidad = context.getResources().getDrawable(R.drawable.muy_alta);
} else {
imagenCalidad = context.getResources().getDrawable(R.drawable.excelente);
}
}
Weird since i use a similar code for method setImagenLogo that seems to work well. And only difference is one gets a String parameter. And the other an int.
Ps: If it might help, this is the constructor of the retransmision object and its variables:
Context context;
private String idioma;
private String tipo;
private int calidad;
private String link;
private Drawable imagenLogo;
private Drawable imagenIdioma;
private Drawable imagenCalidad;
public Retransmision() {
idioma = "";
tipo = "";
calidad = 0;
link = "";
imagenLogo = null;
imagenIdioma = null;
imagenCalidad = null;
}
The only thing that could be null there is the context... and I see you didn't initialize it in your constructor. Maybe this is what you want:
public Retransmision(Context ctx) {
idioma = "";
tipo = "";
calidad = 0;
link = "";
imagenLogo = null;
imagenIdioma = null;
imagenCalidad = null;
context = ctx;
}

Categories

Resources