So I'm making an Android soundboard app and get this exception and my app crashes when I click the last button of the soundboard app.
[THE CODE]
public class newBoard extends Activity {
int selectedSoundId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer player = new MediaPlayer();
final Resources res = getResources();
// just keep them in the same order, e.g. button01 is tied to backtoyou
final int[] buttonIds = { R.id.button1, R.id.button2, R.id.button3,
R.id.button4, R.id.button5, R.id.button6, R.id.button7,
R.id.button8, R.id.button9, R.id.button10, R.id.button11,
R.id.button12, R.id.button13, R.id.button14, R.id.button15,
R.id.button16, R.id.button16, R.id.button17, R.id.button18,
R.id.button19, R.id.button20, R.id.button21, R.id.button22,
R.id.button23, R.id.button24, R.id.button25, R.id.button26,
R.id.button27, R.id.button28, R.id.button29, R.id.button30,
R.id.button31, R.id.button32 };
final int[] soundIds = { R.raw.bengalka, R.raw.cista_psihologija,
R.raw.da_ne, R.raw.dejo_narkomane, R.raw.dizi_se,
R.raw.fejslifting, R.raw.fotomale, R.raw.gladan_sam,
R.raw.jasna_pero, R.raw.jeben_vam_mater, R.raw.kae_ivanisevic,
R.raw.kae_to_fora, R.raw.kaj_gledas, R.raw.kaj_vi_gledate,
R.raw.kineza_crnaca, R.raw.kozo_nepodojena, R.raw.marino,
R.raw.mater_zbrgljavu, R.raw.muha, R.raw.nema_papira,
R.raw.nered, R.raw.ne_spominji_majku, R.raw.nisam_se_uroko,
R.raw.odfurati_doktoru, R.raw.pljacka, R.raw.pusi_ke,
R.raw.sava_sava, R.raw.tebe_i_magazin, R.raw.tog_vani_nema,
R.raw.za_dom_spremni, R.raw.zrigati };
View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
// find the index that matches the button's ID, and then reset
// the MediaPlayer instance, set the data source to the
// corresponding
// sound effect, prepare it, and start it playing.
for (int i = 0; i < buttonIds.length; i++) {
if (v.getId() == buttonIds[i]) {
selectedSoundId = soundIds[i];
AssetFileDescriptor afd = res
.openRawResourceFd(soundIds[i]);
player.reset();
try {
player.setDataSource(afd.getFileDescriptor(),
afd.getStartOffset(), afd.getLength());
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
player.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
player.start();
break;
}
}
}
};
// set the same listener for every button ID, no need
// to keep a reference to every button
for (int i = 0; i < buttonIds.length; i++) {
Button soundButton = (Button) findViewById(buttonIds[i]);
registerForContextMenu(soundButton);
soundButton.setOnClickListener(listener);
}
}
}
The exception shows on this line:
selectedSoundId = soundIds[i];
selectedSoundId = soundIds[i];
final int[] buttonIds = 33 Value - you have two R.id.button16 in your buttonIds
final int[] soundIds = 31 Value
So it is crash.
Off-by-two: There are 33 button ids and 31 sound ids. Button 16 is duplicated.
For mapping resource ids and other integers, consider a map, such as SparseIntArray.
Related
I am trying to play audio in my app from parse.com. I'm able to start and play the Media file but cant pause and stop it. Here is the code:
ParseQuery<ParseObject> query = ParseQuery.getQuery("Table");
query.getInBackground(ObjId, new GetCallback<ParseObject>() {
public void done(ParseObject recording, com.parse.ParseException e) {
if (e != null) {
//do nothing
}
else {
ParseFile audioFile = recording.getParseFile("Audio");
String audioFileURL = audioFile.getUrl();
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(audioFileURL);
mediaPlayer.prepare();
//mediaPlayer.start();
mediaPlayer.start();
finalTime = mediaPlayer.getDuration();
startTime = mediaPlayer.getCurrentPosition();
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
});
You're not playing a live stream, the file plays after the object is downloaded as you're setting up the action inside the
public void done(ParseObject recording, com.parse.ParseException e)
and this method is executed in another thread which complicates the situation a a lot, you should get the file first with:
ParseQuery<ParseObject> query = ParseQuery.getQuery("Table");
ParseObject obj = query.getFirst()
ParseFile audioFile = obj.getParseFile("Audio");
String audioFileURL = audioFile.getUrl();
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
And then implement your other features.
In the system when I select msg that msg by default display on spinner.I require this project those select item display only spinner.If I change item not show previous select item display on spinner.
list.java
Spinner sp1;
TextView entry;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
sp1=(Spinner) findViewById(R.id.spinner1);
entry = (TextView)findViewById(R.id.TextView123);
getFilesnames();
}
private void getFilesnames() {
// TODO Auto-generated method stub
String[] filenames=getApplicationContext().fileList();
List<String> list=new ArrayList<String>();
for(int i=0;i<filenames.length;i++){
list.add(filenames[i]);
}
ArrayAdapter<String> filenameAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,list);
sp1.setAdapter(filenameAdapter);
}
public void onClick(View v) {
// TODO Auto-generated method stub
String selectFile = String.valueOf(sp1.getSelectedItem());
openFile(selectFile);
}
private void openFile(String selectFile) {
// TODO Auto-generated method stub
String value = "";
FileInputStream fis;
try {
fis = openFileInput(selectFile);
byte[] input = new byte[fis.available()];
while(fis.read(input) != -1){
value += new String(input);
}
fis.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
entry.setText(value);
}
Check whether list has value after binding like following code:
private void getFilesnames() {
// TODO Auto-generated method stub
String[] filenames=getApplicationContext().fileList();
List<String> list=new ArrayList<String>();
for(int i=0;i<filenames.length;i++){
list.add(filenames[i]);
}
/***
check here list has value or not
***/
if(list.size() <= 0) {
list.add("You string.....");
}
ArrayAdapter<String> filenameAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,list);
sp1.setAdapter(filenameAdapter);
}
Good morning guys!
Quick question, I am using file Input/Output in Java to save data into a String when the "Save" Button in my program is pressed. But whenever I hit the "Save" button, the program stops working.
I am also new to Java and Android, so I can't really tell yet if the problem is very specific to my code or a more general one which is why I am posting this question even if there are many others that are similar.
Using comment-outs "//, /*, /" I was able to locate the line in my code that causes the program to stop working, I have emphasised this line by placing "" at the beginning and at the end of it so you won't have trouble looking for it. I just want to know why this line is causing my app to stop and if possible, how it can be fixed.
Thanks guys. Your assistance will be very much appreciated.
Please take a look at my code snippet:
public class MainActivity extends ActionBarActivity {
EditText sharedData;
FileOutputStream fos;
String FILENAME = "InternalString";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
Button save = (Button) findViewById(R.id.btn_save);
save.setOnClickListener(onSave);
ListView list = (ListView) findViewById(R.id.restaurants);
adapter = new RestaurantAdapter();
list.setAdapter(adapter);
}
public View.OnClickListener onSave = new View.OnClickListener (){
#Override
public void onClick(View v) {
Info r = new Info();
EditText name = (EditText) findViewById(R.id.field_name);
EditText address = (EditText) findViewById(R.id.field_address);
TextView total= (TextView)findViewById(R.id.total);
RadioGroup types = (RadioGroup) findViewById(R.id.rgrp_types);
switch (types.getCheckedRadioButtonId()) {
case R.id.rbtn_sit_down:
r.setType("sit_down");
break;
case R.id.rbtn_take_out:
r.setType("take_out");
break;
}
r.setName(name.getText().toString());
r.setAddress(address.getText().toString());
r.setTotal(total.getText().toString());
String data = sharedData.getText().toString();*** <----- This line causes it to stop running
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(data.getBytes());
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String collected = null;
FileInputStream fis = null;
try {
fis = openFileInput(FILENAME);
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1){
collected = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
fis.close();
total.setText("Balance Total: " + collected +"Php");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Log.d("FoodTripActivity", "Name: " + r.getName() + "Address: " + r.getAddress() + "Type: " + r.getType());
adapter.add(r);
}
};
}
sharedData is not initialized. You need to initialize it before calling getText.
You have only declared it EditText sharedData;
sharedData =(EditText) findViewById(R.id.idforshareddata);
String data = sharedData.getText().toString();
I am trying to approach a problem in which I have to disable and then enable mobile data with some delay in between (reset mobile data 2G).
step 1: disable mobile data
step 2: wait till mobile data gets disabled
step 3: some delay say 2 seconds
step 4: enable mobile data
step 5: wait till mobile data gets enabled
step 6: continue with the program.....
doing some research I came up with this...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button start = (Button)findViewById(R.id.button1);
start.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(!mobileDataEnabled(getApplicationContext())){
setMobileDataEnabled(getApplicationContext(),true);
Toast.makeText(getApplicationContext(), "ENABLED", Toast.LENGTH_SHORT).show();
}else{
setMobileDataEnabled(getApplicationContext(),false);
Toast.makeText(getApplicationContext(), "DISABLED", Toast.LENGTH_SHORT).show();
}
}
});
}
//the method below enables/disables mobile data depending on the Boolean 'enabled' parameter.
private void setMobileDataEnabled(Context context, boolean enabled) {
final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
Class conmanClass = null;
try {
conmanClass = Class.forName(conman.getClass().getName());
final Field iConnectivityManagerField = conmanClass.getDeclaredField("mService");
iConnectivityManagerField.setAccessible(true);
final Object iConnectivityManager = iConnectivityManagerField.get(conman);
final Class iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
setMobileDataEnabledMethod.setAccessible(true);
setMobileDataEnabledMethod.invoke(iConnectivityManager, enabled);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// below method returns true if mobile data is on and vice versa
private boolean mobileDataEnabled(Context context){
boolean mobileDataEnabled = false; // Assume disabled
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
Class cmClass = Class.forName(cm.getClass().getName());
Method method = cmClass.getDeclaredMethod("getMobileDataEnabled");
method.setAccessible(true); // Make the method callable
// get the setting for "mobile data"
mobileDataEnabled = (Boolean)method.invoke(cm);
} catch (Exception e) {
// Some problem accessible private API
// TODO do whatever error handling you want here
}
return mobileDataEnabled;
}
The above code will turn on/off mobile data but it happens really quick. this quick that the mobile data doesn't even turn off actually. how do I add a delay in between and achieve the steps I mentioned above? any help would be appreciated.
thanks!
Just put
Thread.sleep(1000);
in between the code statements (before setMobileData APIs) to achieve delay. The delay parameter is in milliseconds. So change it according to your requirement.
EDIT: Try putting the delay into a handler, using this code:
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//Whatever you want to do
}
}, 1000);
Try this may work. Use your code for turning off/on your packet data.
You should use a broadcast receiver for getting the events of connectivity.
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
registerReceiver(broadcastReceiver, intentFilter);
Check the below link for details
Get notified on connectivity change
public void mobiledataenable(boolean enabled) {
try {
final ConnectivityManager conman = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
final Class<?> conmanClass = Class.forName(conman.getClass().getName());
final Field iConnectivityManagerField = conmanClass.getDeclaredField("mService");
iConnectivityManagerField.setAccessible(true);
final Object iConnectivityManager = iConnectivityManagerField.get(conman);
final Class<?> iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
setMobileDataEnabledMethod.setAccessible(true);
setMobileDataEnabledMethod.invoke(iConnectivityManager, enabled);
}
catch (Exception e)
{
e.printStackTrace();
}
}
Try (this will turn the data off then wait till it's off then on again):
setMobileDataEnabled(getApplicationContext(),false);
while(mobileDataEnabled(getApplicationContext()){
//Just wait, don't do anything
}
//Turn it on here
setMobileDataEnabled(getApplicationContext(),true);
Lemme know if i couldn't get you properly!
// first check whether it is on\off...
public void setMobileDataEnabled(Context context, boolean status) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException
{
final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final Class conmanClass = Class.forName(conman.getClass().getName());
final Field connectivityManagerField = conmanClass.getDeclaredField("mService");
connectivityManagerField.setAccessible(true);
final Object connectivityManager = connectivityManagerField.get(conman);
final Class connectivityManagerClass = Class.forName(connectivityManager.getClass().getName());
final Method setMobileDataEnabledMethod = connectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
setMobileDataEnabledMethod.setAccessible(true);
setMobileDataEnabledMethod.invoke(connectivityManager, status);
}
I want show a progress dialog (with a progressbar or circle this is indifferent to me) when i click the button. Actually i can show it but i don't know how hide it after finish the operations inside at onclick. This is the code:
copy.setOnClickListener(new OnClickListener() {
public void onClick(View v){
ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setProgressStyle(R.style.NewDialog);
progressDialog.setMessage("Loading...");
progressDialog.show();
String datafolder = Environment.getDataDirectory().getAbsolutePath()+File.separator+"app";
File customfolder=new File(Environment.getExternalStorageDirectory().getAbsolutePath().toString()+File.separator+"BackupApps");
String comando = "cp -r /data/app /sdcard/BackupApps";
Process suProcess = null;
try {
suProcess = Runtime.getRuntime().exec("su");
} catch (IOException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
DataOutputStream os = new DataOutputStream(suProcess.getOutputStream());
try {
os.writeBytes(comando + "\n");
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
os.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
os.writeBytes("exit\n");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
os.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
How can i do it?
First define inner class like this in your class
class SaveTask extends AsyncTask<Void, Void, Void> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(getActivity());
progressDialog.setProgressStyle(R.style.NewDialog);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
String datafolder = Environment.getDataDirectory()
.getAbsolutePath() + File.separator + "app";
File customfolder = new File(Environment
.getExternalStorageDirectory().getAbsolutePath().toString()
+ File.separator + "BackupApps");
String comando = "cp -r /data/app /sdcard/BackupApps";
Process suProcess = null;
try {
suProcess = Runtime.getRuntime().exec("su");
} catch (IOException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
DataOutputStream os = new DataOutputStream(
suProcess.getOutputStream());
try {
os.writeBytes(comando + "\n");
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
os.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
os.writeBytes("exit\n");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
os.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (progressDialog != null) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
}
call this in your onClick() like this..
here we haven't passing any data to AsynchTask so here i am passing null
copy.setOnClickListener(new OnClickListener() {
public void onClick(View v){
SaveTask task = new SaveTask();
task.execute(null, null, null);
}
Start a AsyncTask on onClick method like this:
public void onClick(View v){
YourAsyncTask asyncTask = new AsyncTask(context);
asyncTask.execute();
}
And in your AsyncTask create a ProgressDialog on onPreExecute(), do your stuff in doInBackground() and dismiss the ProgressDialog on onPostExecute():
public class YourAsyncTask extends AsyncTask<Void, Void, Void> {
private Context ctx;
private ProgressDialog progressDialog;
public YourAsyncTask(Context ctx) {
this.ctx = ctx;
}
#Override
protected void onPreExecute() {
ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setProgressStyle(R.style.NewDialog);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
String datafolder = Environment.getDataDirectory().getAbsolutePath()+File.separator+"app";
File customfolder=new File(Environment.getExternalStorageDirectory().getAbsolutePath().toString()+File.separator+"BackupApps");
String comando = "cp -r /data/app /sdcard/BackupApps";
Process suProcess = null;
try {
suProcess = Runtime.getRuntime().exec("su");
} catch (IOException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
DataOutputStream os = new DataOutputStream(suProcess.getOutputStream());
try {
os.writeBytes(comando + "\n");
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
os.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
os.writeBytes("exit\n");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
os.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
protected void onPostExecute(Void res) {
progressDialog.hide();
progressDialog.dismiss();
}
don't foget to declare the progressDialog global variable
#Override
public void onClick(View v) {
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setProgressStyle(R.style.NewDialog);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
String datafolder = Environment.getDataDirectory().getAbsolutePath()+File.separator+"app";
File customfolder=new File(Environment.getExternalStorageDirectory().getAbsolutePath().toString()+File.separator+"BackupApps");
String comando = "cp -r /data/app /sdcard/BackupApps";
Process suProcess = null;
try {
suProcess = Runtime.getRuntime().exec("su");
} catch (IOException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
DataOutputStream os = new DataOutputStream(suProcess.getOutputStream());
try {
os.writeBytes(comando + "\n");
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
os.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
os.writeBytes("exit\n");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
os.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (progressDialog!=null) {
progressDialog.dismiss();
}
}
};
task.execute((Void[])null);
}
Add progressDialog.dismiss(); in the last line on onClick and in all the catch so that it will disappear even if an Exception is thrown