i m trying to get the Value from RadioButton that is Created by String of Array
i m using OClickListener() to get the Value from RadioButton but Error is showing
" java.lang.ClassCastException: android.widget.Button cannot be cast to android.widget.RadioButton
"
Here is my Code,Please check
for(int i =0; i<ab.length;i++)
{
RadioButton radioButtonView = new RadioButton(this);
radioButtonView.setText(ab[i]);
radioGroup.addView(radioButtonView, p);
}
Button btnDisplay = (Button) findViewById(R.id.button1);
btnDisplay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
// get selected radio button from radioGroup
int selectedId = radioGroup.getCheckedRadioButtonId();
// find the radiobutton by returned id
String s = ((RadioButton) v ).getText().toString();
Toast.makeText(Radio_Button.this, "This is: " + s,Toast.LENGTH_LONG).show();
}
and LogCat is
FATAL EXCEPTION: main
Process: com.example.radiobuttondynamic, PID: 4741
java.lang.ClassCastException: android.widget.Button cannot be cast to android.widget.RadioButton
at com.example.radiobuttondynamic.Radio_Button$1.onClick(Radio_Button.java:64)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Please Give Suggestion to Correct it
thanks
thanks
v is a Button and you cast it to RadioButton in this line:
String s = ((RadioButton) v ).getText().toString();
try this:
if you added radioButton programmatically you can setID to radioButtons:
for(int i =0; i<ab.length;i++)
{
RadioButton radioButtonView = new RadioButton(this);
radioButtonView.setText(ab[i]);
radioButtonView.setID(i);
radioGroup.addView(radioButtonView, p);
}
and then
String s = ((RadioButton) findViewById(yourRadioButtonID) ).getText().toString();
Why are you trying to cast the button to radio button??
anyway if you want to get the text of selected radio button do the following
btnDisplay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
RadioButton selectedButton= (RadioButton)findViewById(radioGroup.getCheckedRadioButtonId()); //you will get the selected radiobutton here
String s=selectedButton..getText().toString();
Toast.makeText(Radio_Button.this, "This is: " + s,Toast.LENGTH_LONG).show();
}
Use this:
String s = radioButtonView.getText().toString();
Instead of:
String s = ((RadioButton) v ).getText().toString();
I am writing the onclick functionality.
public void onClick(View v)
{
int selectedId = radioGroup.getCheckedRadioButtonId();
if(selectedId !=-1)
{
View radioButton = radioGroup.findViewById(selectedId );
int radioId = radioGroup.indexOfChild(radioButton);
RadioButton btn = (RadioButton) radioGroup.getChildAt(radioId);
String selection = (String) btn.getText();
Toast.makeText(Radio_Button.this, "This is: " + s,Toast.LENGTH_LONG).show();
}
}
Try this, If you have any problem then please comment.
Related
I am trying to update intdelay by taking the value from an edittext and converting it into an integer as shown below, and I am using a toast to check the updated value of intdelay.
public static int intdelay=1000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
delayedttxt=(EditText)findViewById(R.id.delayedttxt);
String delay=delayedttxt.getText().toString(); //this will get a string
try{
int intdelay = Integer.parseInt(delay);
}catch(NumberFormatException ex){ // handle your exception
}
Button btn=(Button)findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
flashLight.switchFlash();
Toast.makeText(MainActivity.this,"your integer is " + intdelay , Toast.LENGTH_LONG).show();
}
});
but the intdelay value is not getting updated.
How I can solve that?
Note: I have to use the try-catch structure because otherwise the app crashes.
When I remove the try-catch,
the code becomes as following:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
delayedttxt=(EditText)findViewById(R.id.delayedttxt);
String delay=delayedttxt.getText().toString();
final int intdelay = Integer.parseInt(delay);
Button btn=(Button)findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
flashLight.switchFlash();
Toast.makeText(MainActivity.this,"your integer is " + intdelay ,Toast.LENGTH_LONG).show();
}
});
and the logcat after crash as following:
08-22 16:13:05.866 17636-17636/de.nocnoc.clean.cleanlight I/RequestQueue: Repeating capture request set.
08-22 16:13:05.876 17636-17790/de.nocnoc.clean.cleanlight W/LegacyRequestMapper: convertRequestMetadata - control.awbRegions setting is not supported, ignoring value
08-22 16:13:05.876 17636-17790/de.nocnoc.clean.cleanlight W/LegacyRequestMapper: Only received metering rectangles with weight 0.
08-22 16:13:06.866 17636-17636/de.nocnoc.clean.cleanlight I/RequestQueue: Repeating capture request cancelled.
08-22 16:13:06.866 17636-17636/de.nocnoc.clean.cleanlight I/RequestQueue: Repeating capture request set.
08-22 16:13:06.894 17636-17790/de.nocnoc.clean.cleanlight W/LegacyRequestMapper: convertRequestMetadata - control.awbRegions setting is not supported, ignoring value
08-22 16:13:06.894 17636-17790/de.nocnoc.clean.cleanlight W/LegacyRequestMapper: Only received metering rectangles with weight 0.
08-22 16:19:51.367 19348-19348/de.nocnoc.clean.cleanlight W/System: ClassLoader referenced unknown path: /data/app/de.nocnoc.clean.cleanlight-2/lib/arm
08-22 16:19:51.404 19348-19348/de.nocnoc.clean.cleanlight D/AndroidRuntime: Shutting down VM
08-22 16:19:51.414 19348-19348/de.nocnoc.clean.cleanlight E/AndroidRuntime: FATAL EXCEPTION: main
Process: de.nocnoc.clean.cleanlight, PID: 19348
java.lang.RuntimeException: Unable to start activity ComponentInfo{de.nocnoc.clean.cleanlight/de.nocnoc.clean.flashlight.MainActivity}: java.lang.NumberFormatException: Invalid int: ""
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2464)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2524)
at android.app.ActivityThread.access$900(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1391)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:234)
at android.app.ActivityThread.main(ActivityThread.java:5526)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NumberFormatException: Invalid int: ""
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parseInt(Integer.java:358)
at java.lang.Integer.parseInt(Integer.java:334)
at de.nocnoc.clean.flashlight.MainActivity.onCreate(MainActivity.java:32)
at android.app.Activity.performCreate(Activity.java:6285)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2417)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2524)
at android.app.ActivityThread.access$900(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1391)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:234)
at android.app.ActivityThread.main(ActivityThread.java:5526)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
08-22 16:19:53.050 19348-19348/de.nocnoc.clean.cleanlight I/Process: Sending signal. PID: 19348 SIG: 9
You are getting intdelay only in onCreate, you should read the value of edit text every time before displaying the toast. In other way inside onClickListener. Initially the edit text will not have any value in it and so Integer.parseInt call will throw NumberFormatException.
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String delay = delayedttxt.getText().toString();
int intdelay = 0;
try{
intdelay = Integer.parseInt(delay);
} catch(NumberFormatException ex){
e.printStackTrace();// Never swallow exception
}
flashLight.switchFlash();
Toast.makeText("Initial Delay : " + intdelay , Toast.LENGTH_LONG).show();
}
});
It is happening because before you set any value in edittext , delay gets initialized. Move this line
String delay=delayedttxt.getText().toString();
inside the onclick method , like this -
Button btn=(Button)findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String delay=delayedttxt.getText().toString();
flashLight.switchFlash();
Toast.makeText(MainActivity.this,"your integer is " + intdelay , Toast.LENGTH_LONG).show();
}
});
Then try again
You should put
String delay=delayedttxt.getText().toString(); //this will get a string
try{
int intdelay = Integer.parseInt(delay);
}catch(NumberFormatException ex){ // handle your exception
}
Inside the onclicklistener
It is throwing NumberFormatException because you are parsing a empty string returned by getText method and
It won't require try catch after doing that
this is my first activity, i want to pass the value to second activity to do calculation and show the result in the textview.But I dont know why when i key in all the detail at activity 1, and click the custom button it jump out from the app
public void onClick(View v){
switch (v.getId())
{
case R.id.customMarco:
if(gender.getText().toString().equals("") || age.getText().toString().equals("")||
height.getText().toString().equals("")||weight.getText().toString().equals("")||
activity.getText().toString().equals("")||goal.getText().toString().equals(""))
{
Toast.makeText(getApplicationContext(), "Please key in all your detail above !", Toast.LENGTH_LONG).show();
}
else {
String cal = finalCal_result.getText().toString();
String carb = carb_result.getText().toString();
String protein = protein_result.getText().toString();
String fat = fat_result.getText().toString();
Intent intent = new Intent(this, CustomMarco.class);
intent.putExtra("Cal", cal);
intent.putExtra("Carb", carb);
intent.putExtra("Protein", protein);
intent.putExtra("Fat", fat);
startActivity(intent);
}
break;
}
This is my second activity, to get the valur from activity 1 and do calculation and show the result in textview cp. But I dont know why when i key in all the detail at activity 1, and click the custom button it jump out from the app
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom__marco);
cal = (EditText) findViewById(R.id.field_cal);
String calNum =getIntent().getStringExtra("Cal");
cal.setText ( calNum );
cal.setOnClickListener(this);
carb = (EditText) findViewById(R.id.field_carb);
String carbNum =getIntent().getStringExtra("Carb");
carb.setText ( carbNum );
carb.setOnClickListener(this);
Button setButton = (Button) findViewById(R.id.setButton);
setButton.setOnClickListener(this);
TextView cp = (TextView) findViewById(R.id.cp);
float cal_n = Float.parseFloat(calNum);
float carb_n = Float.parseFloat(carbNum);
int carbPValue = calculateCP(cal_n,carb_n);
cp.setText(String.valueOf(carbPValue) + " %");
}
private int calculateCP(float cal_n, float carb_n){
return (int) ((carb_n/cal_n)*4*100);
}
here the log cat error
12-03 21:25:39.284
28640-28640/com.example.sam.iifym E/AndroidRuntime:
FATAL EXCEPTION: main java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sam.iifym/com.example.sam.iifym.CustomMarco}: java.lang.NumberFormatException: Invalid int: "3809 cal"
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2383)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2435)
at android.app.ActivityThread.access$600(ActivityThread.java:168)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1379)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5434)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:852)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:619)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NumberFormatException: Invalid int: "3809 cal"
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parse(Integer.java:375)
at java.lang.Integer.parseInt(Integer.java:366)
at java.lang.Integer.parseInt(Integer.java:332)
at com.example.sam.iifym.CustomMarco.onCreate(CustomMarco.java:59)
at android.app.Activity.performCreate(Activity.java:5224)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1151)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2347)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2435)
at android.app.ActivityThread.access$600(ActivityThread.java:168)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1379)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5434)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:852)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:619)
at dalvik.system.NativeStart.main(Native Method)
Bundle extras = getIntent().getExtras();
String carb = extras.getString("Carb");
for more info just check this answer:
https://stackoverflow.com/a/5265952/2074990
There is problem in your string.
LogCat says Invalid int: "3809 cal"
You pass Invalid data in that string.
You can just pass only Integer for convert String to Float
Example :
Valid String is "3809".
Instead of "3809 cal".
Caused by: java.lang.NumberFormatException: Invalid int: "3809 cal"
You're trying to convert the String "3809 cal" to int/float, while "3809 cal" is not a valid format of int/float.
Check your cal String in the first activity, it must be "3809" instead of "3809 cal".
I'm faced with this problem
java.lang.UnsupportedOperationException
What I want to do is easy, I'll show you an example.
MyList
Blue
Red
Green
When I make an OnItemLongClickListener() for example on Green, my list should looks like :
MyList
Green
What I've tried is
final ArrayAdapter < String > adapter = new ArrayAdapter < String > (getActivity(), android.R.layout.simple_list_item_1, FileBackup.getFilesFound());
adapter.setNotifyOnChange(true);
lv.setAdapter(adapter);
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView <? > arg0, View arg1, final int arg2, long arg3) {
String itemValue = (String) lv.getItemAtPosition(arg2);
Log.d("Item clicked --> ", lv.getItemAtPosition(arg2).toString());
FileBackup.setNameFile(itemValue);
final Dialog dialog = new Dialog(getActivity());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.user_file_choose);
Button button = (Button) dialog.findViewById(R.id.btOk);
Button button2 = (Button) dialog.findViewById(R.id.btKo);
TextView tvBackUpFile = (TextView) dialog.findViewById(R.id.textViewContentDialog);
tvBackUpFile.setText("Do you want to backup " + FileBackup.getNameFile() + " ?");
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
//Clear all the ListView
lv.setAdapter(null);
}
});
}
});
It's working fine, if I want to clear the ListView, but in my case I DON'T WANT TO, I tried to add item or remove with :
adapter.addAll("Something");
or
lv.removeViewAt(2);
And then call adapter.notifyDataSetChanged(); but it gives the same error every time I try to.
What I'm doing wrong?
EDIT
Now the code looks like :
final ArrayAdapter < String > adapter = new ArrayAdapter < String > (getActivity(), Arrays.asList(FileBackup.getFilesFound()));
adapter.setNotifyOnChange(true);
lv.setAdapter(adapter);
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView <? > arg0, View arg1, final int arg2, long arg3) {
String itemValue = (String) lv.getItemAtPosition(arg2);
Log.d("Item clicked --> ", lv.getItemAtPosition(arg2).toString());
FileBackup.setNameFile(itemValue);
final Dialog dialog = new Dialog(getActivity());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.user_file_choose);
Button button = (Button) dialog.findViewById(R.id.btOk);
Button button2 = (Button) dialog.findViewById(R.id.btKo);
TextView tvBackUpFile = (TextView) dialog.findViewById(R.id.textViewContentDialog);
tvBackUpFile.setText("Do you want to backup " + FileBackup.getNameFile() + " ?");
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
//Clear all the ListView
lv.setAdapter(null);
//Trying to add that current item clicked
adapter.addAll(FileBackup.getNameFile());
adapter.notifyDataSetChanged();
}
});
}
});
And this is the LogCat error :
06-10 20:14:43.531 8072-8072/info.androidhive.tabsswipe E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: info.androidhive.tabsswipe, PID: 8072
java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:404)
at java.util.AbstractList.add(AbstractList.java:425)
at java.util.Collections.addAll(Collections.java:2583)
at android.widget.ArrayAdapter.addAll(ArrayAdapter.java:211)
at info.androidhive.tabsswipe.BackupWA$1$1.onClick(BackupWA.java:80)
at android.view.View.performClick(View.java:4456)
at android.view.View$PerformClick.run(View.java:18462)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5102)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Where it's pointing this --> adapter.addAll(FileBackup.getNameFile()); but it's not null I also tried to adapter.addAll("RED");
EDIT2
I'm trying to keep the name what I've clicked to FileBackup.getFilesFound() so I can create my adapter again I'm doing it with :
String[] itemvalues = (String[]) lv.getItemAtPosition(arg2);
FileBackup.setFilesFound(itemvalues);
And then I'm doing :
adapter.addAll(Arrays.asList(FileBackup.getFilesFound()));
//Add the name
adapter.notifyDataSetChanged();
On my class is declared as String[] and the error is :
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.String[]
EDIT3
It's giving the same error every time I want to update the list... #Y.S. said that It's better to post all of my code to see what's going on, because somewhere I'm using String[] instead of ArrayList<String>
That's my FileBackup.java
public class FileBackup {
private String path;
private String pathFile;
private File FileToBackUp;
private String SDpath;
private String[] FilesFound;
private String nameFile;
public String getPathFile() {
return pathFile;
}
public void setPathFile(String pathFile) {
this.pathFile = pathFile;
}
public String getNameFile() {
return nameFile;
}
public void setNameFile(String nameFile) {
this.nameFile = nameFile;
}
public FileBackup(String path){
this.path = path;
}
public File getFileToBackUp() {
return FileToBackUp;
}
public void setFileToBackUp(File fileToBackUp) {
FileToBackUp = fileToBackUp;
}
public String[] getFilesFound() {
this.FilesFound = FilesFound();
return FilesFound;
}
public String[] FilesFound() {
File dir = new File(this.path);
File[] filelist = dir.listFiles();
String[] theNamesOfFiles = new String[filelist.length];
for (int i = 0; i < theNamesOfFiles.length; i++) {
theNamesOfFiles[i] = filelist[i].getName();
}
return theNamesOfFiles;
}
And this is how I have the List of the files.
final String itemValue = (String) lv.getItemAtPosition(arg2);
Log.d("Item clicked --> ", lv.getItemAtPosition(arg2).toString());
final Dialog dialog = new Dialog(getActivity());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.user_file_choose);
Button button = (Button) dialog.findViewById(R.id.btOk);
Button button2 = (Button) dialog.findViewById(R.id.btKo);
FileBackup.setNameFile(itemValue);
TextView tvBackUpFile = (TextView) dialog.findViewById(R.id.textViewContentDialog);
tvBackUpFile.setText("Do you want to backup " + FileBackup.getNameFile() + " ?");
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//The complete path of the fail
FileBackup.setPathFile(GlobalConstant.path + "/" + FileBackup.getNameFile());
//Converting the path of the file to a File and putting it to FileToBackUp
FileBackup.setFileToBackUp(PathToFile(FileBackup.getPathFile()));
dialog.dismiss();
//Clear all the ListView
lv.setAdapter(null);
//Add the name
BackUpFile.setEnabled(true);
}
});
I tried to do something like :
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//The complete path of the fail
FileBackup.setPathFile(GlobalConstant.path + "/" + FileBackup.getNameFile());
//Converting the path of the file to a File and putting it to FileToBackUp
FileBackup.setFileToBackUp(PathToFile(FileBackup.getPathFile()));
///// THIS IS NEW ///////////
String itemvalues = (String) lv.getItemAtPosition(arg2);
FileBackup.setFilesFound(new String[] {
itemvalues
});
adapter.addAll(FileBackup.getFilesFound());
//Add the name
adapter.notifyDataSetChanged();
//////////TIL HERE/////////////
dialog.dismiss();
//Clear all the ListView
//Add the name
BackUpFile.setEnabled(true);
}
});
And this is the LogCat
java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:404)
at java.util.AbstractList.add(AbstractList.java:425)
at java.util.AbstractCollection.addAll(AbstractCollection.java:76)
at android.widget.ArrayAdapter.addAll(ArrayAdapter.java:195)
at info.androidhive.tabsswipe.BackupWA$1$1.onClick(BackupWA.java:88)
at android.view.View.performClick(View.java:4456)
at android.view.View$PerformClick.run(View.java:18462)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5102)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Where is pointing
adapter.addAll(Arrays.asList(FileBackup.getFilesFound()));
Also I've tried with
adapter.addAll(FileBackup.getFilesFound());
But it's giving the same error... Maybe is that I'm doing this on a not correct place...
Look this answer:
ArrayAdapter
So basically as in this answer said: "The ArrayAdapter, on being initialized by an array, converts the array into a AbstractList (List) which cannot be modified."
So it easy, create your own ArrayList, in your case of type String, and then assign this to CustomAdapter, then you can just remove items from your ArrayList and notifyDataSetChanged() should works.
Regards
I have 2 activities, and I'm passing edit number editText data to 2nd activity with intent. But in second activity I can't convert data from String to int with any functions. Here is my code:
This is main function:
public class MainActivity extends ActionBarActivity {
public EditText mAge;
public Button mCalculate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAge = (EditText) findViewById(R.id.numberImputEditText);
mCalculate = (Button) findViewById(R.id.calculateButton);
mCalculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String age = mAge.getText().toString();
Intent mIntent = new Intent(getApplicationContext(),FinalActivity.class);
mIntent.putExtra("age", age);
startActivity(mIntent);
}
});
}
}
and this is 2nd activity where is data passed:
public class FinalActivity extends Activity {
public Button mCalculateAgain;
public TextView mMinAge;
public TextView mMaxAge;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_final);
Intent mIntent = getIntent();
String age = mIntent.getStringExtra("age");
mCalculateAgain = (Button) findViewById(R.id.calculateAgainButton);
mMinAge = (TextView) findViewById(R.id.minAgeTextView);
mMaxAge = (TextView) findViewById(R.id.maxAgeTextView);
Integer i = Integer.parseInt(age);
mMinAge.setText((i/2)+7);
mMaxAge.setText((i-7)*2);
Toast.makeText(getApplicationContext(), age, Toast.LENGTH_LONG).show();
mCalculateAgain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mIntent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(mIntent);
}
});
}
}
here's the log:
`java.lang.RuntimeException: Unable to start activity ComponentInfo{com.robigroza.halfyourage/com.robigroza.halfyourage.FinalActivity}: android.content.res.Resources$NotFoundException: String resource ID #0x12
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2114)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2139)
at android.app.ActivityThread.access$700(ActivityThread.java:143)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1241)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4960)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x12
at android.content.res.Resources.getText(Resources.java:1058)
at android.widget.TextView.setText(TextView.java:3857)
at com.robigroza.halfyourage.FinalActivity.onCreate(FinalActivity.java:35)
at android.app.Activity.performCreate(Activity.java:5203)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2078)
There's a few types of TextView.setText(...). One takes a CharSequence, which is probably what you expected to use, and another commonly used variant takes an int. The int form expects the parameter to be a resource ID.
mMinAge.setText((i/2)+7);
mMaxAge.setText((i-7)*2);
Given that (i/2)+7 isn't likely to resolve to a string resource, you could do:
mMinAge.setText("" + (i/2)+7);
mMaxAge.setText("" + (i-7)*2);
or better:
mMinAge.setText(String.valueOf((i/2)+7));
mMaxAge.setText(String.valueOf((i-7)*2));
Use this code in MainActivity.java
int age = Integer.parseInt(mage.getText().toString());
Intent i = new Intent(MainActivity.this,FinalActivity.class);
i.putExtra("age", age);
startActivity(i);
Code for FinalActivity .java
Bundle extras = getIntent().getExtras();
int age = extras.getInt("age");
In this way you can send integer value to other activity.
EnJoY coding :)
Hi I am just trying to make an app that will have a button that will get an input of 4 different player names from a dialog box and assign the input to separate text views.
I want it to be possible to click the button, the dialog pops up, enter name, and it will appear as player1, and then hit the same button again and enter for player2. The problem is that i cannot open the dialogbox the second time.
Code:
package com.example.russianroullette;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class PlayersTab extends FragmentActivity {
int amtPlayers = 0;//number of players currently active
String name = "";//name input from Dialog Box
String player1Name = "";//actual name used for player1
String player2Name = "";//actual name used for player2
String player3Name = "";//actual name used for player3
String player4Name = "";//actual name used for player4
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.players_tab);
final TextView player1 = (TextView) findViewById(R.id.textView2);//Player1 TextView
final TextView player2 = (TextView) findViewById(R.id.textView3);//Player2 TextView
final TextView player3 = (TextView) findViewById(R.id.textView4);//Player3 TextView
final TextView player4 = (TextView) findViewById(R.id.textView5);//player4 TextView
final EditText input = new EditText(this);// Set an EditText view to get user input
final Button addPlayerButton = (Button) findViewById(R.id.add1Button);
player1.setText("P1: ");//updates the TextView with P1 name
player2.setText("P2: ");//updates the TextView with P2 name
player3.setText("P3: ");//updates the TextView with P3 name
player4.setText("P4: ");//updates the TextView with P4 name
//Creates AlertDialog
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Enter Player's Name");//Title of AlertDialog
alert.setView(input);//The EditText
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Editable value = input.getText();//gets the input
name = value.toString();//sets name as the user input from the Dialog Box
playerId = ("Player " + amtPlayers + ": " + name);// puts all of the variables into a simple string to be used by the TextViews
switch(amtPlayers){
case 1: player1Name = (name);
player1.setText(player1Name);
break;
case 2: player2Name = (name);//the actual name used for player2
player2.setText(player2Name);
break;
case 3: player3Name = (name);//the actual name used for player3
player3.setText(player3Name);
break;
case 4: player4Name = (name);//the actual name used for player4
player4.setText(player4Name);
break;
default: //code that asks the user which name to replace
break;
}
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
amtPlayers--;//puts the amtPlayers back 1
}
});
//Ends AlertDialog Creation
addPlayerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Code that adds new Player.
amtPlayers++;
alert.show();
}
});
});
//Code
}
}
LogCat:
01-22 19:48:58.376: E/AndroidRuntime(1284): FATAL EXCEPTION: main
01-22 19:48:58.376: E/AndroidRuntime(1284): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
01-22 19:48:58.376: E/AndroidRuntime(1284): at android.view.ViewGroup.addViewInner(ViewGroup.java:3378)
01-22 19:48:58.376: E/AndroidRuntime(1284): at android.view.ViewGroup.addView(ViewGroup.java:3249)
01-22 19:48:58.376: E/AndroidRuntime(1284): at android.view.ViewGroup.addView(ViewGroup.java:3225)
01-22 19:48:58.376: E/AndroidRuntime(1284): at com.android.internal.app.AlertController.setupView(AlertController.java:401)
01-22 19:48:58.376: E/AndroidRuntime(1284): at com.android.internal.app.AlertController.installContent(AlertController.java:241)
01-22 19:48:58.376: E/AndroidRuntime(1284): at android.app.AlertDialog.onCreate(AlertDialog.java:336)
01-22 19:48:58.376: E/AndroidRuntime(1284): at android.app.Dialog.dispatchOnCreate(Dialog.java:351)
01-22 19:48:58.376: E/AndroidRuntime(1284): at android.app.Dialog.show(Dialog.java:256)
01-22 19:48:58.376: E/AndroidRuntime(1284): at android.app.AlertDialog$Builder.show(AlertDialog.java:932)
01-22 19:48:58.376: E/AndroidRuntime(1284): at com.example.russianroullette.PlayersTab$5.onClick(PlayersTab.java:124)
01-22 19:48:58.376: E/AndroidRuntime(1284): at android.view.View.performClick(View.java:4084)
01-22 19:48:58.376: E/AndroidRuntime(1284): at android.view.View$PerformClick.run(View.java:16966)
01-22 19:48:58.376: E/AndroidRuntime(1284): at android.os.Handler.handleCallback(Handler.java:615)
01-22 19:48:58.376: E/AndroidRuntime(1284): at android.os.Handler.dispatchMessage(Handler.java:92)
01-22 19:48:58.376: E/AndroidRuntime(1284): at android.os.Looper.loop(Looper.java:137)
01-22 19:48:58.376: E/AndroidRuntime(1284): at android.app.ActivityThread.main(ActivityThread.java:4745)
01-22 19:48:58.376: E/AndroidRuntime(1284): at java.lang.reflect.Method.invokeNative(Native Method)
01-22 19:48:58.376: E/AndroidRuntime(1284): at java.lang.reflect.Method.invoke(Method.java:511)
01-22 19:48:58.376: E/AndroidRuntime(1284): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
01-22 19:48:58.376: E/AndroidRuntime(1284): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-22 19:48:58.376: E/AndroidRuntime(1284): at dalvik.system.NativeStart.main(Native Method)
Thank you for any help!
EDIT: I believe i have to restart the DialogBox somehow?
create alertview in function, and make sure when you create alertview that it's a new one.
-(void)showAlert {
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Enter Player's Name");//Title of AlertDialog
alert.setView(input);//The EditText
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Editable value = input.getText();//gets the input
name = value.toString();//sets name as the user input from the Dialog Box
playerId = ("Player " + amtPlayers + ": " + name);// puts all of the variables into a simple string to be used by the TextViews
switch(amtPlayers){
case 1: player1Name = (name);
player1.setText(player1Name);
break;
case 2: player2Name = (name);//the actual name used for player2
player2.setText(player2Name);
break;
case 3: player3Name = (name);//the actual name used for player3
player3.setText(player3Name);
break;
case 4: player4Name = (name);//the actual name used for player4
player4.setText(player4Name);
break;
default: //code that asks the user which name to replace
break;
}
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
amtPlayers--;//puts the amtPlayers back 1
}
});
alert.show();
}
The problem is with your EditText is already bound to the previous dialog.
One quick workaround is:
Define Context and Builder before onCreate()
Context ctx;
AlertDialog.Builder alert;
Initialize them in onCreate():
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(...);
ctx = this.getApplicationContext();
final Button addPlayerButton = (Button) findViewById(...);
alert = new Builder(this);
// Creates AlertDialog
......
}
Change addPlayerButton onClick to this:
addPlayerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Code that adds new Player.
showDialog();
}
});
protected void showDialog() {
input = new EditText(ctx);
alert.setView(input);
alert.show();
}
I modified you code, please try this.
public class PlayersTab extends FragmentActivity {
private AlertDialog.Builder alert = null;
int amtPlayers = 0;//number of players currently active
String name = "";//name input from Dialog Box
private TextView player1 ,player2,player3, player4;
String player1Name = "";//actual name used for player1
String player2Name = "";//actual name used for player2
String player3Name = "";//actual name used for player3
String player4Name = "";//actual name used for player4
private EditText input ;
private Button addPlayerButton;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.players_tab);
player1 = (TextView) findViewById(R.id.textView2);//Player1 TextView
player2 = (TextView) findViewById(R.id.textView3);//Player2 TextView
player3 = (TextView) findViewById(R.id.textView4);//Player3 TextView
player4 = (TextView) findViewById(R.id.textView5);//player4 TextView
input = new EditText(this);// Set an EditText view to get user input
addPlayerButton = (Button) findViewById(R.id.add1Button);
player1.setText("P1: ");//updates the TextView with P1 name
player2.setText("P2: ");//updates the TextView with P2 name
player3.setText("P3: ");//updates the TextView with P3 name
player4.setText("P4: ");//updates the TextView with P4 name
//Ends AlertDialog Creation
addPlayerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Code that adds new Player.
amtPlayers++;
//You should create dialog after you click, in your earlier code, it was always there.
alert = new AlertDialog.Builder(this);
alert.setTitle("Enter Player's Name");//Title of AlertDialog
alert.setView(input);//The EditText
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Editable value = input.getText();//gets the input
name = value.toString();//sets name as the user input from the Dialog Box
playerId = ("Player " + amtPlayers + ": " + name);// puts all of the variables into a simple string to be used by the TextViews
switch(amtPlayers){
case 1: player1Name = (name);
player1.setText(player1Name);
break;
case 2: player2Name = (name);//the actual name used for player2
player2.setText(player2Name);
break;
case 3: player3Name = (name);//the actual name used for player3
player3.setText(player3Name);
break;
case 4: player4Name = (name);//the actual name used for player4
player4.setText(player4Name);
break;
default: //code that asks the user which name to replace
break;
}
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
amtPlayers--;//puts the amtPlayers back 1
}
});
alert.show();
}
});
I would still suggest you to go with DialogFragment, it is the right way to work with all types of Dialogs.
For examples you can refer to this tutorial.