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));
Related
The app crashes when the button is selected which uses the values converted from edit texts. Tried multiple ways to move the part edittext = R.ids .. to try and make sure the edittexts picks new values after the oncreate first runs.
Think the calculation part causes the crash because its trying to perform a calculation with stored values from the edit text when the value is false from the first time the edit text gets the R.ids... in the onCreate method.
needed hide/display editText based off a radio button setonCheckedChangeListener in the onCreate method. So edittext = R.ids .. set in this method, the app does not crash at runtime like it would if I moved the edittext = R.ids .. to the testFunction method.
EditText editTextValue;
EditText editTextValue2;
double amount;
protected void onCreate(){...
//Get edittext field parameters
editTextValue = (EditText) findViewById(R.id.editText_weight_kg);
//listener to switch editTexts on which radio button selected in units group
unitsRG.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.imperial) {
editTextValue2.setVisibility(View.VISIBLE);
editTextValue.setVisibility(View.GONE);
}
void testFunction(View view){
String stringValue = editTextValue..getText().toString();
//check value as long as its not empty for the edit text , save it
if (editTextValue.getText().length() > 0) {
amount = Integer.parseInt(stringValue);
Log.e("MainActivity", " " + amount);
}
}
but now when I run the app I get this error in the long cat
enter image description here
E/ClipboardServiceEx﹕ clipEx is android.sec.clipboard.ClipboardExManager#1f70b420
E/ClipboardServiceEx﹕ clipEx has text data : false
here is the xml for one of the edit texts
<EditText
android:id="#+id/editText_weight_lb"
style="#style/EditTextViewStyle"
android:visibility="visible"/>
In the editTextStyle , I set the textCursorDrawable to null to try and have different colors for the pointer and underline colors. Not sure if this could also be affecting the editTextView storing the value
<item name="android:textCursorDrawable">#null</item>
I also tried setting edittext = R.ids in the testfunction and in the onCreate method. See if the editTexts would store the values the user enters rather than keeping the empty values when onCreate initially run.
I still got the same clipEx has text data:false error after trying this.
I searched the logcat error "clipEx has text data: false" and found something regarding samsung memory leaks.
https://github.com/square/leakcanary/issues/133
I am using a samsung galaxy for testing. I feel the issue is more with where I'm setting the edittexts to the R.ids thats causing the issue.
I saw the post for checking to make sure valid value entered for edittext.
Issue with empty EditText
How to Check whether a value is entered in editexts before submitting?
will add the check after finding out why values are not getting stored/ still remaining false.
Thanks
well I tried a different approach to implement the method.
I placed a button in the OnCreate method to define the event handlers against the buttons:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button calculate = (Button)findViewById(R.id.calculate);
calculate.setOnClickListener(new View.OnClickListener(){
String stringValue = editTextValue.getText().toString();
//check value as long as its not empty for the edit text , save it
if (editTextValue.getText().length() > 0) {
amount = Integer.parseInt(stringValue);
Log.e("MainActivity", " " + amount);
}
.....
.....
}
}
By using the button method in the OnCreate, when I ran the app, errors would actually come up on the Integer.parseInt() method call. Turns out that even though the editTexts that I was entering text for did not have text values, the other editTexts still had strings for the text, so this would cause the app to crash.
<EditText...
android:text="kg"/>
I took out the text values. It worked again.
I also took out this line in the style sheet for the editText. This was to change the editText border color, cursor color, or line.
<item name="android:textCursorDrawable">#null</item>
I tried the public void testFunction() approach which I had used before, the app works, but the clipEx has text data : false continues to show up.
But the app works now with either the Button method in onCreate or as a public void testFunction() approach.
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.
I am little confused with following scenario:
I have an add button which I use it to add a number of EditText fields, when I tap on the save button I should get the values from the EditTexts.
How can I get these values from all of the EditText fields?
You could do something like this:
Store all the EditText fields you create programmatically inside a List. So whenever you have viewGroup.add(myEditText); you would also have myList.add(myEditText);
Then when you press 'save' just loop on your list and use getText() to get the data from your EditText fields.
I'm sure there are also other ways to accomplish this ;)
btn_no_of.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String str1=edittext1.gettext.tostring();
String str2=edittext2.gettext.tostring();
}
});
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");
In the /res/values folder of my android project i have a string and that is referenced in a text view in my xml file, i want to change the string in my java file.
As you can see below in the code i have made a string variable and then below that i have set what the string variable is set to, which is where the string is located. where i have "here" posed in the code that's where i want to change to string in the values folder. but i don't know what code to use to set it.
I could just change the text in a text view from my java file, which i know how to do, but that is an old way and it sets of a warning so i would rather use a string which is the best way to do so.
With my knowledge of changing text in a text view i have basically guessed my way to this stage but i don't know how to go any further could any one give me some advice on what to do, thanks.
String string;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
counter = 0;
add = (Button) findViewById(R.id.badd);
sub = (Button) findViewById(R.id.bsub);
reset = (Button) findViewById(R.id.breset);
display = (TextView) findViewById(R.id.tvdisplay);
string = (String) getString(R.string.counter);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
((///////////////here////////////////))
counter++;
}
});
You cannot modify the text assigned to <string> elements of a /res/values/strings.xml file at runtime. They're constants so effectively final.
You also cannot change a layout xml file at runtime. If you've created a layout with a TextView that has its android:text attribute set to some initial resource string, that is basically an 'initial' value and cannot be changed to something else at runtime.
You told us a lot of changing text, but you don't said what the text should be. I need to guess, too:
The strings.xml file should be used for texts that might change for different languages. If you just want to change the text of a counter, you shouldn't do it via strings.xml as the numbers are universal :)
Try to go with that:
display.setText(String.valueOf(counter));
You will want to use the setText() method.
display.setText("text");