I have a listener that simply changes a button's text and clocks the time for the user. I also have a textview that is supposed to change to the new total amount of time worked when the user clocks out. I double checked the xml to make sure I was grabbing the right R.Id and the button in the listener is being found just not the TextView. Here is the code:
public class HoursListener implements OnClickListener{
GlobalApp appState;
Button startStopHoursButton;
TextView hoursTotalTextView;
public boolean clockedIn;
public HoursListener(Context ctx){
appState = ((GlobalApp)ctx.getApplicationContext());
}
public void onClick(View v) {
startStopHoursButton = (Button) v.findViewById(R.id.hourstogglebutton);
hoursTotalTextView = (TextView) v.findViewById(R.id.totalWorktimeTextView);
if(!clockedIn){
startStopHoursButton.setText(R.string.clockout);
appState.getCurrentCompany().getCurrentNewWeeklyTimestamp().CreateFinishTimeStamp();
clockedIn = true;
}else{
startStopHoursButton.setText(R.string.clockin);
appState.getCurrentCompany().getCurrentNewWeeklyTimestamp().CreateFinishTimeStamp();
clockedIn = false;
hoursTotalTextView.setText(appState.getCurrentCompany().getCurrentNewWeeklyTimestamp().totalTimeDoneThisWeekToString());
}
}
}
Heres the xml for the textView:
<TextView
android:id="#+id/totalWorktimeTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView2"
android:text=""
android:textAppearance="?android:attr/textAppearanceSmall"/>
The error is with this line:
hoursTotalTextView.setText(appState.getCurrentCompany().getCurrentNewWeeklyTimestamp().totalTimeDoneThisWeekToString());
I was thinking about just putting the code in the activity itself but I feel like I can do it this way. I want something I can call like a listener so I reduce the redundancy in my code. I have double checked that it is the hoursTotalTextView that is null. Yet the button isn't. Any ideas?
Screenshot of Eclipse (linked to full-size version) showing that the relevant values aren't null:
Presumably the onClickListener whose click you are listening to is the button? The onClick passes the View v that was clicked - i.e. the button - and the textbox is not a child of the button, so you can't find it.
If HoursListener is declared inside your activity, just do findViewById instead of v.findViewById i.e.
hoursTotalTextView = (TextView) findViewById(R.id.totalWorktimeTextView);
If not, pass the textview into the HoursListener constructor and set hoursTotalTextView there (bearing in mind this feels like it might cause memory leaks).
what is GlobalApp appState; and why you are typecasting context to GlobalApp from below line.
I think appstate will be null here.
appState = ((GlobalApp)ctx.getApplicationContext());
if GlobalApp is a class then create a object for it and then use getter and setter methods.
you need to use
startStopHoursButton = (Button) v.findViewById(R.id.hourstogglebutton);
hoursTotalTextView = (TextView) v.findViewById(R.id.totalWorktimeTextView);
some where before,can be constructor cause your setText is working on null TextView object.
Check each object in that line
if(appState.getCurrentCompany()==null)
Log.d("","getCurrentCompany is null");
if(appState.getCurrentCompany().getCurrentNewWeeklyTimestamp()==null)
Log.d("","getCurrentNewWeeklyTimestamp is null");
if(appState.getCurrentCompany().getCurrentNewWeeklyTimestamp().totalTimeDoneThisWeekToString()==null)
Log.d("","totalTimeDoneThisWeekToString is null");
Related
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.
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_alignParentTop="true"
android:text="#string/button1"
android:onClick="onClickButton"/>
public void onClickButton(View view){
TextView textview = (TextView) findViewById(R.id.textView1);
textview.setVisibility(View.VISIBLE);
}
That is the code that makes the text appear in the main activity interface when the button is pressed. What is the point of passing in an View object when you don't use it in the "onClickButton" method block? I am asking this because the app crashes if I leave out the parameter even when I am not using the view object in the code block.
You might have several buttons in your layout, and only one method in your activity's code. In such a situation, it becomes necessary to differentiate between different buttons.
That's where this can be used.
public void onClickButton(View view){
if(view.getId() == R.id.buttonSave){
// Do something
} else if(view.getId() == R.id.buttonCancel){
// Do something else
}
}
Although, you can bind different methods to different views, by having a method for each view type.
Yet another use case could be:
After clicking on the button, you want to modify the button itself, say, hide it, or change the label, then you obviously need a reference to the button.
what is the point of passing in an object view of type View when you don't use it in the "onClickButton" method block?
First of all, the Button Docs tell you to. Secondly, it can get used in the function. Since Buttons aren't the only Views which are clickable, having the View parameter allows you to check that View type to see what has been pressed and to perform other operations with it.
public void onClickButton(View view){
TextView textview = (TextView)view;
textview.setVisibility(View.VISIBLE);
}
This should work if you are passing a view directly to the method.
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.
with this code, my program just force close(error)
***public View x = findViewById(R.string.nfoname);***
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.information);
//edittext
***final EditText infoname=(EditText)findViewById(R.id.infoname);***
//clear,confirm
Button clear = (Button)findViewById(R.id.buttonclear);
Button confirm = (Button)findViewById(R.id.buttonconfirm);
//clear button
clear.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
infoname.setText("");
}
});
//confirm button
confirm.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
***x=(View) infoname.getText();***
}
});
}
the one with the * are the source of error
program function:
if the user clicks confirm, his name will be set to R.string.nfoname
which will then be used in another layout through TextView x = setText(R.string.nfoname);
I am not sure that you can save text to the R.string. This is a generated class that the compiler creates for you. It gets packaged with your apk. Think of the resources as a means of translation and to present text to the screen.
I think what you would want to do is save the user input as a SharedPreference or in a database.
See:SharedPreferences on the android docs for an example usage.
At least in the case of your variable infoname scoping is most likely causing your application to throw an error. infoname is a local variable to the function onCreate(), not an instance variable for your class, so it can't be accessed by your onClick() methods because they are part of an anonymous class.
Another thing I'd question is why you marked infoname as final? It goes out of scope when onCreate() exits so if it gets changed, you can see who changed it since it only exists while the method is executing.
You cannot set values to R.string.xxx because all these values will be constants much like a read only stuff. If you want to use the value of edit text to another layout use class variables or intent.putextra()
Coming to ur source code i see this
public View x = findViewById(R.string.nfoname);
How can a view be found by R.String? This should be R.id.
final EditText infoname=(EditText)findViewById(R.id.infoname);
Why this editText has to be final?
***x=(View) infoname.getText();***
You just use infoname.getText().toString() you will get the string value of the Edittext's current text.
Dude you can do stuff simply.
public View x = findViewById(R.string.nfoname);
This can't work as not only are you trying to find a View using a R.string resource id, you are doing it before setContenView(...) is called in your onCreate(...) method. Even if you used a valid View resource id such as R.id.infoname then x will be null because the content view hasn't been inflated yet.
final EditText infoname=(EditText)findViewById(R.id.infoname);
Apart from the pointless use of final this should'nt cause problems as long as R.id.infoname is actually the resource id of an EditText.
x=(View) infoname.getText();
Not only will x be null but calling getText() on an EditText returns an Editable which is not a View nor is it possible to cast it to View. Even if you used getText().toString() which is the correct way to get the text from an EditText it still wouldn't be possible to cast a String to a View.
Also, as for this...
TextView x = setText(R.string.nfoname);
It would have to be...
TextView x = (TextView) findViewById(<some id>);
x.setText(getString(R.string.nfoname));
Hi im new to android and I have a program that has a global variable define and it works, so I can set it and get it in every activity, BUT it dosnt like to be changed in an on click listener. I made it so on the screen there is an edittext and when someone presses a button I want the edittext text to be put into the global variable. here is my code:
Button SiteButton = (Button) findViewById(R.id.SiteButton);
SiteButton.setOnClickListener(new View.OnClickListener() {
TextView textviewS = (TextView) findViewById(R.id.SiteIdT);
EditText edittextS = (EditText) findViewById(R.id.SiteIdE);
TextView textviewB = (TextView) findViewById(R.id.BusIdT);
EditText edittextB = (EditText) findViewById(R.id.BusIdE);
public void onClick(View v) {
textviewS.setText(edittextS.getText());
((Global) this.getApplication()).setgSiteId(textviewS.getText().toString());
textviewB.setText(edittextB.getText());
((Global) this.getApplication()).setgVehicleId(textviewB.getText().toString());
}
});
but the getApplication() part is showing an error. can anyone help?
You should refer to your activity this, since View.OnClickListener doesn't have such a method:
// Bad code! read below
((Global) MyActivityClassName.this.getApplication()).setgSiteId(textviewS.getText().toString());
textviewB.setText(edittextB.getText());
((Global) MyActivityClassName.this.getApplication()).setgVehicleId(textviewB.getText().toString());
By the way, how do you cast the return from getApplication() to Global? You will get a class cast exception there.