Update an object in RecyclerView - java

I have a problem with updating an item in RecycleView.
When i try to edit a dream object and save it then it gets updated in database but not in the list of dream and I don't know why.
This method creates and updates a dream object.
#OnClick({R.id.addTagDream, R.id.saveDreamButton})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.addTagDream:
Intent intent = new Intent(AddEditDreamActivity.this, SelectDreamActivity.class);
startActivityForResult(intent, SELECTED_DREAM);
break;
case R.id.saveDreamButton:
boolean hasError = false;
...
if (!hasError) {
// check if exit dream about id
try {
myDreamList = myDreamDao.queryForEq(MyDream.Columns.MY_DREAM_ID, dreamId);
} catch (SQLException e) {
e.printStackTrace();
}
chcek if dream exist
if (myDreamList != null && !myDreamList.isEmpty()) {
// update dream
UpdateBuilder<MyDream, ?> updateMyDream = myDreamDao.updateBuilder();
// condition update dream about dream id
try {
updateMyDream.where().eq(MyDream.Columns.MY_DREAM_ID, dreamId);
} catch (SQLException e) {
e.printStackTrace();
}
// update column title dream
try {
updateMyDream.updateColumnValue(MyDream.Columns.TITLE_DREAM, dreamTitle);
} catch (SQLException e) {
e.printStackTrace();
}
// update dream description
try {
updateMyDream.updateColumnValue(MyDream.Columns.DESCRIPTION, dreamDescription);
} catch (SQLException e) {
e.printStackTrace();
}
// update dream symbol
try {
updateMyDream.updateColumnValue(MyDream.Columns.SYMBOL_DREAM, selectSymbolDream);
} catch (SQLException e) {
e.printStackTrace();
}
try {
updateMyDream.update();
} catch (SQLException e) {
e.printStackTrace();
}
finish();
}
}
break;
}
}

Use adapter.notifyDataSetChanged() or notifyItemInserted() whenever you are adding values in list
Hope this will help you

Related

Android SharedPreferences and Encrypted SharedPreferences

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 ?

on Android is there any idea how to play next item using setOnCompletionListener

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.

Generic Method to Create Multiple Fragments

I want to write a method that creates multiple fragments for me and I am not sure how to do this. After a few attempts I got more confused.
Here is how I typically and creating two fragments
private void createFragDog(Animals animals) {
DogFragment frag = DogFragment.newInstance(ArrayList<Dogs> animals.getDogs());
...
*frag.(do fragment manager stuff and commit())*
...
}
Second call to create fragment
private void createFragCat(Animals animals) {
CatFragment frag = CatFragment.newInstance(ArrayList<Cats> animals.getCats());
...
*frag.(do fragment manager stuff and commit())*
...
}
Being that the newInstance method is static I can't seem to figure out how to make a generic method and just pass in the class types. Also the object passed into newInstance is not always an array. Here is my attempt:
private <T,E> void animalFragments(Class<T> frag, Class<E> animalType, Object obj){
if (obj == null) return;
if (obj instanceof List<?>) {
if (((List<E>)obj).isEmpty()) return;
}
try {
T fragment = (T) frag.newInstance();
?? Not sure what to do now or how to call up method that is static but specific to both.
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
Did it this way hope this helps.
private <T,E> void animalFragments(Class<T> frag, Object obj){
Method m = null;
try {
m = frag.newInstance().getClass().getDeclaredMethod("newInstance", obj.getClass());
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
if (m != null) {
T fragment = null;
try {
fragment = (T) m.invoke(null, obj);
if (fragment != null) {
FragmentTransaction trans = this.getSupportFragmentManager().beginTransaction();
trans.add(R.id.ll_fragments_container, (Fragment) fragment, fragment.getClass().getSimpleName());
trans.commit();
return true;
}
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}

IO exception is not handle

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.

Stopping MediaPlayer before playing again isn't working

I have a ListView with some items and each item plays a certain sound. This is the code:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
try {
player.setDataSource(externalStoragePath + "/Android/data/com.whizzappseasyvoicenotepad/" + recordedFilesArray.get(arg2) + ".mp3");
player.prepare();
player.start();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException 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();
}
}
});
If I click an item and it starts playing and then click another item before the one I clicked before has finished playing, the MediaPlayer will just play both sounds at the same time. How do I get my MediaPlayer to stop() playing the previous sound and start playing the new sound if I have clicked the item before it stopped playing?
I tried adding player.Stop() before try, so that everytime I click an item, the MediaPlayer stops before setting a new source and starting again, but that just stops the previous sound and won't play the new sound.
I also tried adding IF statement, like this:
if (!player.isPlaying()){
//normally start the player
}
else if (player.isPlaying()){
//stop it before starting it again
}
I'd copy my actual code but I already deleted it since it didn't work. It also just stopped the previous sound and didn't play the new one.
Reset your player after stopping song.
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
try {
if (player!=null && player.isPlaying())
{
player.stop();
player.reset();
}
player.setDataSource(externalStoragePath + "/Android/data/com.whizzappseasyvoicenotepad/" + recordedFilesArray.get(arg2) + ".mp3");
player.prepare();
player.start();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException 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();
}
}
});
You have to call setDataSource() in the idle state. So you have to call reset() before calling setDateSource()
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
try {
player.reset();
player.setDataSource(externalStoragePath + "/Android/data/com.whizzappseasyvoicenotepad/" + recordedFilesArray.get(arg2) + ".mp3");
player.prepare();
player.start();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException 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();
}
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
try {
stopPlaying();
initializeMediaPlayer(externalStoragePath + "/Android/data/com.whizzappseasyvoicenotepad/" + recordedFilesArray.get(arg2) + ".mp3");
startPlaying();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException 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();
}
}
});
private void stopPlaying() {
if (player!=null && player.isPlaying()) {
player.stop();
player.release();
}
}
private void initializeMediaPlayer(String path) {
player = new MediaPlayer();
try {
player.setDataSource(path);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void startPlaying() {
try {
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
if(player!=null)
player.start();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
to reuse MediaPlayer, you must call reset() before setting new dataSource. One more thing, you should not call prepare() in UI thread, it may cause ANR error. You would rather call prepareAsync() function.

Categories