I have an issue in my Android app saying "Unhandled IOException: java.io.exception" when I'm trying to getBitmap from URI. below is the code.
I do not want to catch all exception using a catch (exception e) as it's too wide.
private void getBitmapFromURI(Uri uri) {
try {
mSnapShot = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
int PreviewSizeWidth = CameraApplication.Instance().getResources().getInteger(R.integer.FilterPreviewWidth);
int PreviewSizeHeight = CameraApplication.Instance().getResources().getInteger(R.integer.FilterPreviewHeight);
mPreviewBitmap = Bitmap.createScaledBitmap(mSnapShot, PreviewSizeWidth, PreviewSizeHeight, false);
FiltersPreview();
}
catch (FileNotFoundException e) {
e.printStackTrace();
Log.e(TAG, "File not found");
finish();
}
}
any idea how to catch exception in case getbitmap not working ?
thx
Try...
try {
mSnapShot = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
int PreviewSizeWidth = CameraApplication.Instance().getResources().getInteger(R.integer.FilterPreviewWidth);
int PreviewSizeHeight = CameraApplication.Instance().getResources().getInteger(R.integer.FilterPreviewHeight);
mPreviewBitmap = Bitmap.createScaledBitmap(mSnapShot, PreviewSizeWidth, PreviewSizeHeight, false);
FiltersPreview();
}
catch (FileNotFoundException e) {
e.printStackTrace();
Log.e(TAG, "File not found");
finish();
}catch(IOException e){
//do something
}
Use the multi catch and make sure to log your exception in logcat. Something like this.
catch (FileNotFoundException | IOException e) {
Log.e(TAG, e.getMessage(), e);
finish();
}
You should also catch the IOException
private void getBitmapFromURI(Uri uri) {
try {
mSnapShot = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
int PreviewSizeWidth = CameraApplication.Instance().getResources().getInteger(R.integer.FilterPreviewWidth);
int PreviewSizeHeight = CameraApplication.Instance().getResources().getInteger(R.integer.FilterPreviewHeight);
mPreviewBitmap = Bitmap.createScaledBitmap(mSnapShot, PreviewSizeWidth, PreviewSizeHeight, false);
FiltersPreview();
}
catch (FileNotFoundException e) {
e.printStackTrace();
Log.e(TAG, "File not found");
finish();
}
catch (IOException e) {
e.printStackTrace();
Log.e(TAG, "IO error");
finish();
}
}
or you have to change you method signature to
private void getBitmapFromURI(Uri uri) throws IOException
and handle this on an other place.
Related
I have encrypted my preferences like this
public void setFile(){
String masterKeyAlias = null;
try {
masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC);
} catch (GeneralSecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
encryptedSharedPreferences = EncryptedSharedPreferences.create(
"secret_shared_prefs",
masterKeyAlias,
this,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
);
} catch (GeneralSecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
and I'm setting and getting values like this
prefEditor.putString(SettingsActivity.KEY_NICKNAME,nickName.getText().toString()).apply();
nickname = encryptedSharedPreferences.getString(SettingsActivity.KEY_NICKNAME, "");
Everything is okay,but it doesn't set up values in preferences when I'm opening settings, because it uses standart SharedPreferences xml file.
So, the main question is : How to set up values from Encrypted SharedPreferences instead of sharedpreferences xml file ?
I trying to develop the mediaplayer apps, i using listview to display and play the song,
I have problem with play automatically the next sound (item) using setOnCompletionListener
My code :
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
mButtonPause.setEnabled(true);
mButtonResume.setEnabled(false);
if (position == 0){
sound.setAudioStreamType(AudioManager.STREAM_MUSIC);
String audioUrl1 = "https://embeye.tech/ummi/speaker/0001.mp3";
try {
halaman.setText("Doa Pembuka");
playSound(audioUrl1);
Toast.makeText(mContext,"Playing",Toast.LENGTH_SHORT).show();
mButtonNext.setEnabled(true);
mButtonPrev.setEnabled(false);
initializeSeekBar();
} catch (IllegalArgumentException e){
e.printStackTrace();
}catch (SecurityException e){
e.printStackTrace();
}catch (IllegalStateException e){
e.printStackTrace();
}
}
else if (position == 1) {
sound.setAudioStreamType(AudioManager.STREAM_MUSIC);
String audioUrl1 = "https://embeye.tech/ummi/speaker/jilidsatu/0101.mp3";
try {
halaman.setText("Halaman Satu");
playSound(audioUrl1);
Toast.makeText(mContext,"Playing",Toast.LENGTH_SHORT).show();
initializeSeekBar();
mButtonNext.setEnabled(true);
mButtonPrev.setEnabled(true);
}catch (IllegalArgumentException e){
e.printStackTrace();
}catch (SecurityException e){
e.printStackTrace();
}catch (IllegalStateException e){
e.printStackTrace();
}
}
else if (position == 2){
sound.setAudioStreamType(AudioManager.STREAM_MUSIC);
String audioUrl1 = "https://embeye.tech/ummi/speaker/jilidsatu/0102.mp3";
try {
halaman.setText("Halaman Dua");
playSound(audioUrl1);
Toast.makeText(mContext,"Playing",Toast.LENGTH_SHORT).show();
initializeSeekBar();
mButtonNext.setEnabled(true);
mButtonPrev.setEnabled(true);
}catch (IllegalArgumentException e){
e.printStackTrace();
}catch (SecurityException e){
e.printStackTrace();
}catch (IllegalStateException e){
e.printStackTrace();
}
}
else if (position == 3){
sound.setAudioStreamType(AudioManager.STREAM_MUSIC);
String audioUrl1 = "https://embeye.tech/ummi/speaker/jilidsatu/0103.mp3";
try {
halaman.setText("Halaman Tiga");
playSound(audioUrl1);
Toast.makeText(mContext,"Playing",Toast.LENGTH_SHORT).show();
initializeSeekBar();
mButtonNext.setEnabled(true);
mButtonPrev.setEnabled(true);
}catch (IllegalArgumentException e){
e.printStackTrace();
}catch (SecurityException e){
e.printStackTrace();
}catch (IllegalStateException e){
e.printStackTrace();
}
}
sound.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
Toast.makeText(mContext,"End",Toast.LENGTH_SHORT).show();
mButtonResume.setEnabled(true);
sound.isPlaying();
sound.reset();
songNumber = String.valueOf(position + 1);
sound.setAudioStreamType(AudioManager.STREAM_MUSIC);
String audioUrl1 = songNumber;
playSound(audioUrl1);
}
});
}
});
the error i got from logcat :
java.lang.NullPointerException: Attempt to read from null array
but actually i have define that on the songNumber :
sound.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
Toast.makeText(mContext,"End",Toast.LENGTH_SHORT).show();
mButtonResume.setEnabled(true);
sound.isPlaying();
sound.reset();
songNumber = String.valueOf(position + 1);
sound.setAudioStreamType(AudioManager.STREAM_MUSIC);
String audioUrl1 = songNumber;
playSound(audioUrl1);
}
});
What actually i want to do is i would like to play the next song when the current song completed, based on my code above, i would like to activate "postion == 1" when "position == 0" complete
songNumber = String.valueOf(position + 1); means that songNumber will be "2", and as you're setting the audioUrls to be "2".
I'd suggest you to make an Array of audioUrls, and then set songNumber = audioUrls.get(++position);
If that doesn't help you, you could post the full stacktrace so we could see the actual error.
i call below php webservice and get xml response and parse resonse and set it to hashmap.now i want save server response in offline mode .can i save data in offline mode.how plz give me answer.
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
try {
if (response.length() > 0) {
int code = Integer.parseInt(XMLManualParser.getTagValue(Constant.TAG_CODE, response));
if (code == 1) {
spinner.clear();
ArrayList<String> eventlist = XMLManualParser.getMultipleTagList(Constant.TAG_LIST, response);
for (int i = 0; i < eventlist.size(); ++i) {
String responseContent = eventlist.get(i);
HashMap<String, String> hashMap = new HashMap<String, String>();
String title = XMLManualParser.getTagValue(Constant.title, responseContent);
hashMap.put("title", title);
hashMap.put("id", XMLManualParser.getTagValue(Constant.id, responseContent));
hashMap.put("url", XMLManualParser.getTagValue(Constant.url, responseContent));
hashMap.put("balanceurl", XMLManualParser.getTagValue(Constant.balanceurl, responseContent));
spinner.add(hashMap);
}
} else {
Toast.makeText(SettingsEditActivity.this, "no data found", Toast.LENGTH_SHORT).show();
}
CustomSpinnerAdapter customSpinnerAdapter = new CustomSpinnerAdapter(SettingsEditActivity.this, spinner);
settingsBinding.splist.setAdapter(customSpinnerAdapter);
settingsBinding.splist.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
item = parent.getItemAtPosition(position).toString();
// Toast.makeText(parent.getContext(), "Android Custom Spinner Example Output..." + item, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
You can save your response into a file and get in offline
public static void saveDataSingleItemDetails(Context context,String file, MainListModel data) {
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = context.openFileOutput(file, MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NullPointerException e) {
return;
}
ObjectOutputStream objectOutputStream = null;
try {
objectOutputStream = new ObjectOutputStream(fileOutputStream);
} catch (IOException | NullPointerException e) {
e.printStackTrace();
}
try {
if (objectOutputStream != null) {
objectOutputStream.writeObject(data);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (objectOutputStream != null) {
objectOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static MainListModel getSinglItemDetails(Context context,String file) {
MainListModel items = null;
FileInputStream fileInputStream = null;
try {
fileInputStream = context.openFileInput(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
return items;
} catch (NullPointerException e) {
return items;
}
ObjectInputStream objectInputStream = null;
try {
objectInputStream = new ObjectInputStream(fileInputStream);
} catch (IOException | NullPointerException e) {
e.printStackTrace();
return items;
}
try {
items = (MainListModel) objectInputStream.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
objectInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return items;
}
When i try to stream an audio without wifi connection my app crash: "Couldn't open file on client side, trying server side". And I want to catch the error to advice the user.This is my code that doesn't work.
Uri myUri = Uri.parse("http://ip/music/song.mp3");
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(this, myUri);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.prepare();
seekbar.setClickable(false);
pauseButton.setEnabled(false);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I have write code for get GPS data and print it in Toast message. GPS Data printed as Toast message. but not write in CSV file that time the app get closed.
Here is my code,
public class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location loc)
{
if(root1.canWrite())
{
dir1 = new File (root1.getAbsolutePath() + "/TrackingData");
if(!dir1.exists())
{
Toast.makeText(getBaseContext(), "Directory creation", Toast.LENGTH_LONG).show();
dir1.mkdirs();
file1 = new File(dir1, "Data.csv");
}
}
try {
out = new FileOutputStream (file1,append);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
mlongitude = loc.getLongitude();
mlatitude = loc.getLatitude();
// location = loc;
if (mlatitude != 0 && mlongitude !=0)
{
Toast.makeText( getApplicationContext(),"Lat "+mlatitude+" Long "+mlongitude,Toast.LENGTH_SHORT).show();
//Writing in CSV file on device
//String SDcardpath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/TrackData/Data.csv";
strlat = String.valueOf(mlatitude);
strlong = String.valueOf(mlongitude );
String strspeed = String.valueOf(speed);
locationManager.removeUpdates(this);
locationManager.removeUpdates( mlocListener);
//send location to server
if(file1.exists())
{
sb1.append("Time");
sb1.append(",");
sb1.append("Latitude");
sb1.append(",");
sb1.append("Longitude");
sb1.append(",");
sb1.append("Speed");
if (root1.canWrite()){
try {
out.write(sb1.toString().getBytes());
out.write('\n');
} catch (IOException e) {
e.printStackTrace();
}
sb1.delete(0, sb1.length());
}
sb1.append("\""+sdate+"\"");
sb1.append(",");
sb1.append("\""+strlat+"\"");
sb1.append(",");
sb1.append("\""+strlong+"\"");
sb1.append(",");
sb1.append("\""+strspeed+"\"");
if (root1.canWrite()){
try {
out.write(sb1.toString().getBytes());
out.write('\n');
}
catch (IOException e)
{
Toast.makeText(getBaseContext(), "Can't write in file", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
sb1.delete(0, sb1.length());
}
}
else
{
try {
file1.createNewFile();
sb1.append("Time");
sb1.append(",");
sb1.append("Latitude");
sb1.append(",");
sb1.append("Longitude");
sb1.append(",");
sb1.append("Speed");
if (root1.canWrite()){
try {
out.write(sb1.toString().getBytes());
out.write('\n');
} catch (IOException e) {
e.printStackTrace();
}
sb1.delete(0, sb1.length());
}
sb1.append("\""+sdate+"\"");
sb1.append(",");
sb1.append("\""+strlat+"\"");
sb1.append(",");
sb1.append("\""+strlong+"\"");
sb1.append(",");
sb1.append("\""+strspeed+"\"");
if (root1.canWrite()){
try {
out.write(sb1.toString().getBytes());
out.write('\n');
} catch (IOException e) {
e.printStackTrace();
}
sb1.delete(0, sb1.length());
}
} catch (IOException e) {
Toast.makeText(getBaseContext(), "Can;t create new file", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
}
}
I have declared this in AndroidManifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Now working fine