Unable to modify values in ListView - java

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

Related

android - MediaRecorder.stop() crashes the app

Everybody,
I'm trying to record audio.
The audio is record perfectly when record button is clicked.
I try to stop the record and the app crashing immediately after the stop button is clicked.
Can you please help me on fixing this code so i could continue building my project.
Here's part of the code:
public class window2 extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
Spinner spinner;//choice between record and Speech-2-text.
Button play,stop,record;//record, stop and replay buttons.
String outputFile;//the record file.
MediaRecorder myAudioRecorder;//the record method.
int reRecord = 0;//reRecord value.
int pathVal = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_window2);
spinner = findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);//upon change between record and S2T.
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor edit = sharedPreferences.edit();
if( sharedPreferences.getInt("pathVal",0) == 0)
edit.putInt("pathVal",1);
else {
pathVal = sharedPreferences.getInt("pathVal", pathVal);
edit.putInt("pathVal",pathVal+1);
}
pathVal = sharedPreferences.getInt("pathVal", 0);
edit.commit();
//3 buttons for record,stop and replay.
play = findViewById(R.id.button14);
stop = findViewById(R.id.button13);
record = findViewById(R.id.button11);
//to immune issues that may start if the buttons are enabled.
stop.setEnabled(false);
play.setEnabled(false);
//the file of recording.
outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/"+pathVal+".3gp";
//record settings.
myAudioRecorder = new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
myAudioRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
//record button click.
record.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
play.setEnabled(false);
try{
//if we want to re record.
if(reRecord == 1)
{
//we build the settings again.
myAudioRecorder = new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
}
//prepare and start methods.
myAudioRecorder.prepare();
myAudioRecorder.start();
}catch (IllegalStateException ise) {
//something
}catch (IOException ioe){
//something
}
record.setEnabled(false);
stop.setEnabled(true);
Toast.makeText(window2.this, "Recording...", Toast.LENGTH_SHORT).show();
}
});
//stop button click.
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myAudioRecorder.stop();
myAudioRecorder.reset();
reRecord = 1;
myAudioRecorder = null;
record.setEnabled(true);
stop.setEnabled(false);
play.setEnabled(true);
Toast.makeText(window2.this, "Recorded!", Toast.LENGTH_SHORT).show();
}
});
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MediaPlayer mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(outputFile);
mediaPlayer.prepare();
mediaPlayer.start();
Toast.makeText(window2.this, "Playing.", Toast.LENGTH_SHORT).show();
} catch (Exception e){
//something
}
}
});
}
public void OpenWindow4(View view)
{
Spinner spinner = findViewById(R.id.spinner3);
String SpinTxt = spinner.getSelectedItem().toString();
EditText edit2 = findViewById(R.id.editText);
String editTextTxt = edit2.getText().toString();
Intent intent = new Intent(this,window4.class);
intent.putExtra("THE_TEXT",editTextTxt);
intent.putExtra("SPIN_CHOICE",SpinTxt);
startActivity(intent);
}
public void OpenWindow4Speech(View view)
{
Spinner spinner = findViewById(R.id.spinner4);
String SpinTxt = spinner.getSelectedItem().toString();
EditText edit2 = findViewById(R.id.editText2);
String editTextTxt = edit2.getText().toString();
Intent intent = new Intent(this,window4.class);
intent.putExtra("THE_RECORD",outputFile);
intent.putExtra("SPIN_CHOICE",SpinTxt);
intent.putExtra("THE_TEXT",editTextTxt);
startActivity(intent);
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String item = adapterView.getItemAtPosition(i).toString();
if (item.equals("S2T"))
{
Intent intent = new Intent(this,windows2B.class);
startActivity(intent);
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
and here is the logcat:
01-13 08:42:27.105 1031-1031/com.example.simplenigal.prealphabuilt V/MediaRecorder: prepare
01-13 08:42:27.105 1031-1031/com.example.simplenigal.prealphabuilt V/MediaRecorder: start
01-13 08:42:27.105 1031-1031/com.example.simplenigal.prealphabuilt E/MediaRecorder: start failed: -38
01-13 08:42:27.757 1031-1038/com.example.simplenigal.prealphabuilt I/art: Do partial code cache collection, code=115KB, data=106KB
01-13 08:42:27.757 1031-1038/com.example.simplenigal.prealphabuilt I/art: After code cache collection, code=115KB, data=106KB
01-13 08:42:27.757 1031-1038/com.example.simplenigal.prealphabuilt I/art: Increasing code cache capacity to 512KB
01-13 08:42:27.759 1031-1038/com.example.simplenigal.prealphabuilt I/art: Compiler allocated 6MB to compile void android.view.ViewRootImpl.performTraversals()
01-13 08:42:31.382 1031-1031/com.example.simplenigal.prealphabuilt I/ViewRootImpl: ViewRoot's Touch Event : ACTION_DOWN
01-13 08:42:31.452 1031-1031/com.example.simplenigal.prealphabuilt I/ViewRootImpl: ViewRoot's Touch Event : ACTION_UP
01-13 08:42:31.462 1031-1031/com.example.simplenigal.prealphabuilt V/MediaRecorder: stop
01-13 08:42:31.462 1031-1031/com.example.simplenigal.prealphabuilt E/MediaRecorder: stop called in an invalid state: 0
01-13 08:42:31.463 1031-1031/com.example.simplenigal.prealphabuilt D/AndroidRuntime: Shutting down VM
01-13 08:42:31.468 1031-1031/com.example.simplenigal.prealphabuilt E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.simplenigal.prealphabuilt, PID: 1031
java.lang.IllegalStateException
at android.media.MediaRecorder.native_stop(Native Method)
at android.media.MediaRecorder.stop(MediaRecorder.java:896)
at com.example.simplenigal.prealphabuilt.window2$2.onClick(window2.java:102)
at android.view.View.performClick(View.java:5624)
at android.view.View$PerformClick.run(View.java:22441)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6316)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
thanks to every one who paying attention and helping.
Still looking for help

Android app crashes on click : NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I am working on an android project and ran into problems. I have an activity which has a "Write a Review" button which opens a dialog, which in turn has two buttons "Done" and "No Thanks". The "Done" button executes an AsyncTask which stores data to server but it causes the app to crash with a NullPointerException error. Here's the code:
writeReviewBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
// Create custom dialog object
final Dialog dialog = new Dialog(GetReviewActivity.this);
// Include dialog.xml file
dialog.setContentView(R.layout.write_review_activity);
// Set dialog title
dialog.setTitle("Your review is valuable");
// set values for custom dialog components - text, image and button
TextView text = (TextView) dialog.findViewById(R.id.tvWR);
//text.setText("Custom dialog Android example.");
ImageView image = (ImageView) dialog.findViewById(R.id.smiley);
dialog.show();
Button writeButton = (Button) dialog.findViewById(R.id.buttonWR);
writeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new WriteReviewAsyncTask().execute();
}
});
Button declineButton = (Button) dialog.findViewById(R.id.buttonNoThanks);
// if decline button is clicked, close the custom dialog
declineButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Close dialog
dialog.dismiss();
}
});
}catch (Exception e){
e.printStackTrace();
}
}
});
The writeButton is the "Done" button.
Here's the AsyncTask implementation:
public class WriteReviewAsyncTask extends AsyncTask<Void,Void,Void>{
final EditText etWR = (EditText)findViewById(R.id.etWR);
String Review = etWR.getText().toString();
#Override
protected Void doInBackground(Void... params) {
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
try {
Log.i("HAPPENED: ","Working");
userLocalStore = new UserLocalStore(GetReviewActivity.this);
User user = userLocalStore.getLoggedInUser();
dataToSend.add(new BasicNameValuePair("reviewer_name",user.username));
dataToSend.add(new BasicNameValuePair("item_name",ItemName));
dataToSend.add(new BasicNameValuePair("review",Review));
HttpParams httpParams = getHttpRequestParams();
HttpClient httpClient = new DefaultHttpClient(httpParams);
HttpPost httpPost = new HttpPost(SERVER_ADDRESS+"StoreReview.php");
httpPost.setEntity(new UrlEncodedFormEntity(dataToSend));
httpClient.execute(httpPost);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
UpdateRecyclerView();
}
private HttpParams getHttpRequestParams() {
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams,
CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams,
CONNECTION_TIMEOUT);
return httpRequestParams;
}
}
And the LogCat error:
09-23 22:12:22.110 30716-30716/app.usrete.jayant.delvemitt E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at app.usrete.jayant.delvemitt.childscreen.getreviews.getreview.GetReviewActivity$WriteReviewAsyncTask.<init>(GetReviewActivity.java:330)
at app.usrete.jayant.delvemitt.childscreen.getreviews.getreview.GetReviewActivity$2$1.onClick(GetReviewActivity.java:133)
at android.view.View.performClick(View.java:4475)
at android.view.View$PerformClick.run(View.java:18786)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
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:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)
Please help me out guys!
Why are you passing return null in protected Void doInBackground(Void... params)
That passes that arguement to onPostExecute(Void params) which wont take any Argument,its type Void,so avoid writing return null,just remove that line

Converting String to int from intent

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

not able to get vaule from RadioButtons

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.

My Android App crashes when i run a DialogBox for the second time

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.

Categories