android text view give runtime error in eclipse - android

In the code below I get runtime error in eclipse. Why this error is not displayed at compile time?
public class AndroidUIActivity extends Activity implements OnClickListener {
private static final int PROGRESS = 0x1;
private ProgressBar mProgress;
private int mProgressStatus = 0;
private int maxtime=0;
private Handler mHandler = new Handler();
int fileSize=0;
private MediaPlayer mp3player;
private TextView txt_Currenttime;
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
txt_Currenttime.setText(12); /* line with error */
}
}

First identify the Textview id
Text view txt_Currenttime = (TextView)findViewById(R.id.textviewid);
then set the value
txt_Currenttime.setText(String.valueOf(12));

You should have something like:
txt_Currenttime = (TextView)findViewById(R.id.textviewid);
txt_Currenttime.setText(String.valueOf(12));
before setting the text.

The Run time error is coming because you are setting integer value as a text of textview but textview is not take integer value, Change below line of your code
txt_Currenttime.setText(12);
to
txt_Currenttime.setText(String.valueOf(12)); or txt_Currenttime.setText("12");
And add below line after setContentView(R.layout.main);
txt_Currenttime = (TextView)findViewById(R.id.mTxtView1);
it will solve your problem.

You should have to first find the id of that textview after that you can apply any operation on that textview. you are not initializing the textview but you are using it so first use the below code then set text. and you have to set the text in double quotes.
txt_Currenttime = (TextView)findViewById(R.id.textviewid);
txt_Currenttime.setText("12");

txt_Currenttime.setText(12);
In this line ?
The textView needs to be set using a String
txt_Currenttime.setText("12");

In java private TextView txt_Currenttime means that you just have a reference, so you need to build an object (with a new) before using txt_Currenttime.

Related

Got Null String while get data From EditText in android

I got null data while fetch data from text Box.
My Code is:
EditText msg=(EditText)findViewById(R.id.Et_Msg);
String setMsg=msg.getText().toString();
Log.v("Messge","Message::"+setMsg);
Please tell me where I am wrong ?
This is your code,
EditText msg=(EditText)findViewById(R.id.Et_Msg);
String setMsg=msg.getText().toString();
Log.v("Messge","Message::"+setMsg);
The first line is initializing the EditText. When it does by default there is no value ( string ) in the edittext.
In the second line you are trying to fetch a string from a blank edittext, that's why it is giving you NullPointerException.
Solution : I suggest you to move your line String setMsg=msg.getText().toString(); to somewhere else where you are actually going to use the value of EditText.
While getting your data from EditText, you must create a listener orelse you get the value as null for an example button click listener..
For an example:
public class A extends Activity implements OnClickListener{
Button btn;
EditText edt;
#Override
public void onCreate(Bundle saved){
super.onCreate(saved);
edt = (EditText) findViewById(R.id.your_id);
btn = (Button) findViewById(R.id.your_id);
btn.setOnClickListener(this);
}
#Override
public void onClick(View v){
if(v == btn){
String setMsg=edt.getText().toString();
Log.v("Messge","Message::"+setMsg);
}
}
}
see.. what you are doing.. immediately after obtaining and EditText's object you are calling getText() on it.. think logically.. obviously there is nothing (it should return blank though not sure why it is returing null) in the EditText unless you have it from the xml.. something like this;
<EditText
...
android:text="Hey there"
...
/>
try this.. or move getText() call under some button click..
Please replace your below line
String setMsg=msg.getText().toString();
with
String setMsg = String.valueOf(msg.getText());
Please try above line. Your problem will be solved.

android working with Views

In my activity I have the following views
TextView player1;
TextView player2;
TextView player3;
TextView player4;
EditText player1name;
EditText player2name;
EditText player3name;
EditText player4name;
Each of the TextView's has the onclick listener applied to it. and so fires the OnClick function.
When we get to the onClick this is what i am currently doing:
#Override
public void onClick(View v) {
//the v variable is the clicked textview, in this case "player1"
//hide the textview and show the resultant edittext
v.setVisibility(View.GONE);
player1name.setVisibility(View.VISIBLE);
//set focus on edit text and when focus is lost hide it and set the textview text
player1name.requestFocus();
imm.showSoftInput(player1name, InputMethodManager.SHOW_FORCED);
player1name.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View y, boolean x) {
v.setVisibility(View.VISIBLE);
player1name.setVisibility(View.GONE);
imm.hideSoftInputFromWindow(player1name.getWindowToken(), 0);
String name = player1name.getText().toString();
if (name.equals("")) {
v.setText("Player Name1");
} else {
v.setText(name);
}
}
});
}
However with this solution I will need to duplicate this code and change the view names for player2 - player2name, player3 - player3name etc
i can obviously grab the clicked TextView via v, however what i cant seem to do is grab its corresponding EditText.
i had thought of doing this:
View test = v + "name";
//then i replace all references to player1name with the test variable
but it doesnt work it wants me to convert View test; into a string
any suggestions?
EDIT: made it easier to understand my question
View test = v + "name";
will give a compile error. Because "v" is not a string type. and also even if it was String, test is not. This line is pretty wrong.
There a few options to achieve what you want,
You can use hashmap
Declare a global field for hashmap
private final HashMap<Integer,EditText> map = new HashMap<Integer,EditText>();
and in onCreate method put your textview id as key, and put your edittext variables in value.
player1name = (EditText) findViewById(R.id.player1name);
map.put(R.id.textView1, player1name);
// for the rest
in onClick method
EditText e = map.get(v.getId());
Then replace them with "e"
e.requestFocus(); //example
Will you please state your problem clearly? Currently, your language is very ambiguous and I can not figure out, exactly what are you looking for. It will help us to know your problem and in turn solve it.

How do I add a custom propperty on a button and retrieve it when clicked in android?

I have a couple buttons that are hard coded that will need to store some specific data and provide that attribute when clicked such as, one button is "non-fiction" and the other "fiction". I need to use an attribute and not the button text since the button text may change down the line but the attribute is need for database calls.
That is, "non-fiction" could become "true stories" but "non-fiction" will still need to be returned.
I've done something similar programmatically with btn.setTag(...) and btn.getTag(...) but those buttons are generated based on the database not hard coded into the app.
How do I set a custom attribute to a button then retrieve it?
something like:
<Button
android:id="#+id/fictionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:layout_weight="1"
android:onClick="showTools"
android:text="#string/fiction_button"
custom:bookType="fiction" />
<Button
android:id="#+id/nonfictionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:layout_weight="1"
android:onClick="showTools"
android:text="#string/non_fiction_button"
custom:bookType="nonfiction" />
----- edit -----
I've changed my approach based on the answer so far.
I've set before the onCreate:
Button fictionButton;
Button nonfictionButton;
Inside the onCreate I've placed:
fictionButton = (Button) findViewById(R.id.fictionButton);
nonfictionButton = (Button) findViewById(R.id.nonfictionButton);
fictionButton.setTag("bookType","Fiction");
nonfictionButton.setTag("bookType", "Non Fiction");
when the button is clicked I'm getting the tag and storing to a SharedPreference
However now I'm getting an error at fictionButton.setType("bookType","Fiction"); ADT doesn't like the key and wants to remove it.
----- edit -----
The set tag is working but now the getTag is throwing the NullPointerException. I'm using Button b to target all buttons and attempting to get the tag when any button is clicked inside the onClick event. buttonID is initialized before the onCreate and declared as R.id.fictionButton in the onCreate:
b = (Button) view;
String buttonText = b.getTag(buttonID).toString();
----- edit -----
my java file before and with the onCreate:
public class Crossroads extends baseActivity {
FlyOutContainer root;
Button b;
Button fictionButton;
Button nonfictionButton;
Integer buttonID;
public static final String PREFS_NAME = "myPrefs";
SharedPreferences storedInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.root = (FlyOutContainer) this.getLayoutInflater().inflate(
R.layout.activity_crossroads, null);
setContentView(R.layout.activity_crossroads);
buttonID = R.id.fictionButton;
fictionButton = (Button) findViewById(R.id.fictionButton);
nonfictionButton = (Button) findViewById(R.id.nonfictionButton);
fictionButton.setTag(buttonID,"Fiction");
nonfictionButton.setTag(buttonID,"Non Ficiton");
this.setContentView(root);
}
...
}
----- edit -----
Fixed the final piece by comparing ids and setting the string accordingly:
Integer viewId = view.getId();
String buttonText;
// setContentView(R.layout.activity_crossroads);
if(viewId == R.id.fictionButton )
buttonText = fictionButton.getTag(buttonID).toString();
else
buttonText = nonfictionButton.getTag(buttonID).toString();
i think your main problem is that you app won't compile
because you have written:
setTag(String, String);
but the setTag(..) function doesn't take an String as key but an int
so you could do like this:
public static int KEY_BOOK_TYPE = 0; //some int
fictionButton = (Button)findViewById(R.id.fictionButton);
nonfictionButton = (Button)findViewById(R.id.nonfictionButton);
fictionButton.setTag(KEY_BOOK_TYPE, "Fiction");
nonfictionButton.setTag(KEY_BOOK_TYPE, "Non Fiction");
setType(String, String) doesn't exist in Button and so ADT wants to remove that line
--- edit ---
be careful and call:
setContentView(R.layout.your_layout);
before calling any findViewById(R.id.something) else it returns null
--- edit ---
if you call setTag(...) with the button id too, thats really good idea!
but you cannot simply cast any view to the button you want
you have to save the button you got from findViewById like this:
class MainActivity extends Activity
{
int non_fiction_id;
int fiction_id;
Button button_non_fiction;
Button button_fiction;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
non_fiction_id = R.id.button_non_fiction;
fiction_id = R.id.button_fiction;
button_non_fiction = (Button)findViewById(non_fiction_id);
button_fiction = (Button)findViewById(fiction_id);
}
void SomeOtherPlace()
{
String non_ficiton_tag = button_non_fiction.getTag(non_fiction_id);
}
}

TextView not showing up in other activity

I have been able to pass data to other activities except this one. Can anyone see what I'm doing wrong. The only error i'm getting is that my TextView showmsg is NOT showing up in the new activity. Does anyone know why?
public class MyScanActivity extends Activity
{
private static final String MY_CARDIO_APP_TOKEN = "NOT THE PROBLEM";
final String TAG = getClass().getName();
private Button scanButton;
private TextView resultTextView;
private Button buttonBack;
private TextView showmsg;
private int MY_SCAN_REQUEST_CODE = 100; // arbitrary int
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.myscan);
Intent in = getIntent();
if (in.getCharSequenceExtra("usr") != null) {
final TextView setmsg = (TextView)findViewById(R.id.showmsg);
setmsg.setText(in.getCharSequenceExtra("usr"));
}
resultTextView = (TextView)findViewById(R.id.resultTextView);
scanButton = (Button)findViewById(R.id.scanButton);
buttonBack = (Button)findViewById(R.id.buttonBack);
showmsg = (TextView) findViewById(R.id.showmsg);
There are not too many options for how your text can be not shown.
You have the view itself messed up: Check this by putting some sample text in the XML file using android:text="TEST" in the TextView showmsg. Your text should appear, unless your text is the wrong color or size, or something else happens to be above it.
You aren't actually finding it with findViewById() (I hope you've double checked that in a debugger) I agree with alex that you might not want R.id.showmsg. Did you mean to put R.id.resultTextView there instead?
Your passed text is not actually coming through. You should do a log statement, like Log.v(TAG, "Passed text is " + in.getCharSequenceExtra("urs")); and make sure the text is actually coming through.
I haven't test it. but i think that is the reason.
change here:
if (in.getCharSequenceExtra("usr") != null) {
final TextView setmsg = (TextView)findViewById(R.id.showmsg);
setmsg.setText(in.getCharSequenceExtra("usr"));
}
with this:
showmsg = (TextView) findViewById(R.id.showmsg);
if (in.getCharSequenceExtra("usr") != null) {
showmsg.setText(in.getCharSequenceExtra("usr"));
}

Android: random and textView

I have just started learning Android and got some misunderstanding. I'm trying to create an application which displays a textView and a button. Every button click generates a new random number which should be displayed in the textView.
But unfortunately my code causes a list of errors. Here it is:
public class FirstAndroidProjectActivity extends Activity {
public OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView tv = (TextView) findViewById(R.id.display);
Random r = new Random();
int i = r.nextInt(101);
tv.setText(i);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(listener);
}
}
If I just don't use random and use some string except of i
(for example tv.setText("99");) everything is ok, but it doesn't work with a variable as a parameter of setText().
Where is a mistake?
Hope for your help.
You need to convert your random number to a string before setting the text on your TextView
Try
tv.setText(i +"");
Try:
tv.setText(String.valueOf(i));
Java doesn't auto convert types. The + operator is overloaded to transform the parameters passed to it into a String when one or more of those paramaters is a String. So, when you pass i + "" to setText() you are passing a String, however if you just pass i then the compiler sees you passing an int to a method that expects a String and lets you know that that can't be done.
i is an int, try tv.setText("" + i);
Convert your integer to a String before setting it to the textView. You should also move Random r = new Random(); outside of the method, or else your numbers may not really be random :
Random r = new Random();
#Override
public void onClick(View v) {
TextView tv = (TextView) findViewById(R.id.display);
int i = r.nextInt(101);
tv.setText(Integer.toString(i));
}
From the documentation :
If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers
If you create two Random objects too quickly (for example the user clicks two times on the button very quickly), they will share the same seed (the system clock is used to generate it) and as a result you will get the same number two times.
By creating only one Random instance in a global variable, you avoid this issue.
use
tv.setText(new Integer(i).toString()) ;

Categories

Resources