get android element Id in Activity - android

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

Related

User Input of int won't be null

I made a code where user put value between some range and my code generate random number for them. Randomization working properly but when fields are blank my app is crash how should I fix it.
randNum.java
Button generateNum = findViewById(R.id.generate_number);
generateNum.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText et = findViewById(R.id.fromNum);
String sTextFromET = et.getText().toString();
int fNum = Integer.valueOf(sTextFromET);
EditText et1 = findViewById(R.id.toNum);
String sTextFromET1 = et1.getText().toString();
int sNum = Integer.valueOf(sTextFromET1);
TextView ans = findViewById(R.id.ans);
// if(sNum == null || fNum == null){
//
// ans.setText(getString(R.string.enterNumError));
//
// }
// else
if(sNum < fNum){
ans.setText(getString(R.string.max_min_error));
}else {
final int random = new Random().nextInt((sNum - fNum) + 1) + fNum;
String ras = Integer.toString(random);
ans.setText(ras);
}
}
});
I try to use null but it is not working.
You need to put validation first on button click. (For checking if user has entered nothing or just spaces in any of edittexts).
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
strNum1 = edtl.getText().toString().trim();
strNum2 = edt2.getText().toString().trim();
if (strNum1.length() == 0)
{
showAlert("Please enter Num 1");
}
else if (strNum2.length() == 0)
{
showAlert("Please enter Num 2");
}
else
{
int numvalue1 = Integer.parseInt(strNum1);
int numvalue2 = Integer.parseInt(strNum2);
generateNum (numvalue1, numvalue2); //Call your function for generation of random number here
//do your stuff here
}
}
});
Hope this helps you understand the validation of forms for empty input fields.
P.S: I would recommend you put inputType attribute for your EditTexts if you have not added it already in xml file like:
android:inputType="number"
So you can avoid exception at Integer.parseInt if user enters any alphabet or symbol.
You need to handle NumberFormatException thrown by Integer.valueOf() function
try {
EditText et = findViewById(R.id.fromNum);
String sTextFromET = et.getText().toString();
int fNum = Integer.valueOf(sTextFromET);
EditText et1 = findViewById(R.id.toNum);
String sTextFromET1 = et1.getText().toString();
int sNum = Integer.valueOf(sTextFromET1);
TextView ans = findViewById(R.id.ans);
if(sNum < fNum){
ans.setText(getString(R.string.max_min_error));
}else {
final int random = new Random().nextInt((sNum - fNum) + 1) + fNum;
String ras = Integer.toString(random);
ans.setText(ras);
}
}catch(NumberFormatException e){
Toast.makeText(this, "Invalid Input", Toast.LENGTH_SHORT).show();
}

Button Print Toast When Clicked without answer Given

I have this button which calls two methods. See Code; Now i have tried to add a method on my onPictureSubmit(v) method which will print a Toast message (Please Submit Answer) if someone clicked the button without submitting an answer. Problem is it keeps crushing. Any help on how i can detect someone clicked the button without submitting answer will be appreciated.
My Button Code;
#Override
public void onClick(View v) {
switch (pass) {
case 0:
onDefinitionSubmit(v);
break;
case 1:
onPictureSubmit(v);
break;
case 2
break;
}
}
My Code :
private void onPictureSubmit(View v) {
if (v.getId() == R.id.picture_submit) {
final int answerGiven = Integer.parseInt("" + ((EditText) findViewById(R.id.picture_answer)).getText());
final int answerKey = com.madonasystematixnote.mathhelper.lessons.PictureFragment.answer;
final int x = Integer.parseInt("" + ((TextView) findViewById(R.id.picture_x)).getText());
final int y = Integer.parseInt("" + ((TextView) findViewById(R.id.picture_y)).getText());
}
}
If I were you I'd declare the TextView, EditText, Button as a global variable, and then in your onCreate() I'd use the findViewById() to avoid NullPointerException.
Second, I'd check if the answerGiven (I guess is the answer) it's empty, so I'd create a method that returns me if it's empty or not the EditText.
public boolean isEtEmpty(String str){
if(str.isEmpty() || str.length() == 0 || str.equals("") || str == null){
return true;
}
else{
return false;
}
}
Then at the time you call onPictureSubmit() call this method doing this :
if (v.getId() == R.id.picture_submit) {
if (isEtEmpty(picture_answer.getText())){ //picture_answer is the EditText that you want to know if it's empty or not
Toast.makeText(v.getContext(), "Please Submit Answer",Toast.LENGTH_LONG).show();
}
else{
final int answerGiven = Integer.parseInt("" + ((EditText) findViewById(R.id.picture_answer)).getText());
final int answerKey = com.madonasystematixnote.mathhelper.lessons.PictureFragment.answer;
final int x = Integer.parseInt("" + ((TextView) findViewById(R.id.picture_x)).getText());
final int y = Integer.parseInt("" + ((TextView) findViewById(R.id.picture_y)).getText());
}
}

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

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

parse an XML to a Stringarray

I'm looking for help to get an XML to an arraylist.
here is the XML :
<campagne>
<sms><texte>
Vente a Drouot
</texte>
<list>
<id> 1 </id>
<nom> TOTO </nom>
<id> 2 </id>
<nom> TATA </nom>
<id> 3 </id>
<nom> Mr.Gerard </nom>
</list>
</sms>
</campagne>
I want to have TOTO,TATA,Mr.Gerard to a StringArray[] exactly like if I put manually : String[] Customers = {"TOTO","TATA","Mr.Gerard"}
for now my XMlPullParser (I have written " ArrayList clientslist = null; " before and I want to put the difference name in this Array )
:
public void parseXMLAndStoreIt(XmlPullParser myParser) {
int event;
String text = null;
ArrayList<Client> clientslist = null;
try {
event = myParser.getEventType();
while (event != XmlPullParser.END_DOCUMENT) {
String name = myParser.getName();
switch (event) {
case XmlPullParser.START_TAG:
break;
case XmlPullParser.TEXT:
text = myParser.getText();
break;
case XmlPullParser.END_TAG:
if (name.equals("texte"))
message = text.trim();
else if (name.equals("nom"))
clientslist = text.trim(); // error is here
else
break;
}
event = myParser.next();
}
parsingComplete = false;
} catch (Exception e) {
e.printStackTrace();
}
}
With this code I have Mr.Gerard ONLY...
I suppose clients is a String - it should be a List<String> instead and clients = text.trim(); should be replaced with clients.add(text.trim());
Then you can call clients.toArray(new String[clients.size()]) to get a String array you wanted.
What is the clients member variable? Without seeing the rest of the code it appears that you are simply over-writing it with whatever happens to be the last <nom> element.
Use a List and add each <nom> to that and then convert the list to a string array.
Use index for the string array to update the values.
public void parseXMLAndStoreIt(XmlPullParser myParser) {
int event;
int counter = 0;
String text = null;
String[] clients = {};
try {
event = myParser.getEventType();
while (event != XmlPullParser.END_DOCUMENT) {
String name = myParser.getName();
switch (event) {
case XmlPullParser.START_TAG:
break;
case XmlPullParser.TEXT:
text = myParser.getText();
break;
case XmlPullParser.END_TAG:
if (name.equals("texte"))
message = text.trim();
else if (name.equals("nom"))
clients[counter++] = text.trim();
else
break;
}
event = myParser.next();
}
parsingComplete = false;
} catch (Exception e) {
e.printStackTrace();
}
}
public ArrayList<String> parseXMLAndStoreIt(XmlPullParser myParser) {
ArrayList<String> clientslist = new ArrayList<String>; // 1
...
else if (name.equals("nom")){
clients = text.trim();
clientslist.add(text.trim()); //2
}
...
return clientslist; //3
}
at the end , you can get the list

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. */

Categories

Resources