Android - How to clear sharepreference by position recyclerview - android

Here is my code that I got share preference
private void getAllSharePreference() {
SharedPreferences sharedPreferences = getContext().getSharedPreferences(SharePreferenceKey.SONG_LIST, Context.MODE_PRIVATE);
getSongJson = sharedPreferences.getString(SharePreferenceKey.SONG_LIST, "N/A");
if (!getSongJson.equals("N/A")) {
Type type = new TypeToken<List<SongRespones.Songs>>() {}.getType();
songSharePreference = new Gson().fromJson(getSongJson, type);
adapter.addMoreItem(songSharePreference);
rvFavorite.setAdapter(adapter);
}
}
This is my code that I want to clear list in share preference by position recyclerview.
#Override
public void onClickView(final int position, View view) {
final PopupMenu popupMenu = new PopupMenu(getContext(), view);
popupMenu.inflate(R.menu.remove_favorite);
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.popup_remove_favorite:
songSharePreference.remove(position);
adapter.notifyItemChanged(position);
break;
}
return false;
}
});
popupMenu.show();
}
But I cannot clear share preference.
Please help me:

If u want to clear all data from SharedPreferences, this is the way to clear all data of this "SharePreferenceKey.SONG_LIST".
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.popup_remove_favorite:
songSharePreference.remove(position);
adapter.notifyItemChanged(position);
SharedPreferences sharedPreferences =
getContext().getSharedPreferences(
SharePreferenceKey.SONG_LIST, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
constants.editor.clear();
constants.editor.commit();
break;
}
return false;
}
i suggest u to use file to save and retrieve an object. It's easy to use and handle.
private void saveDataToFile() {
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = getContext().openFileOutput("fileName", Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NullPointerException e) {
}
ObjectOutputStream objectOutputStream = null;
try {
objectOutputStream = new ObjectOutputStream(fileOutputStream);
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
}
try {
if (objectOutputStream != null) {
objectOutputStream.writeObject(yourObject); //which data u want to save
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (objectOutputStream != null) {
objectOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Retrieve data from file
private void getDataFromFile() {
FileInputStream fileInputStream = null;
try {
fileInputStream = getContext().openFileInput("fileName");
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
ObjectInputStream objectInputStream = null;
try {
objectInputStream = new ObjectInputStream(fileInputStream);
} catch (IOException |NullPointerException e) {
e.printStackTrace();
}
try {
yourObject = (ObjectClass) objectInputStream.readObject(); //if arraylist then cast to arrylist ( (ArrayList<ObjectClass>) objectInputStream.readObject();)
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
objectInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}

Related

Can not resolve getAssets() method from inside a java file: Android

I have created a file
inside assests folder and now I want to read the file from a java class and pass it to another function in the same class but for some reason i am unable to use getAssest() method. Please help!
public void configuration()
{
String text = "";
try {
InputStream is = getAssets().open("config.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
text = new String(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
public IExtraFeeCalculator getExtraFeeCalculator()
{
if(efCalculator==null)
{
if(configuration(Context context) == "extrafeeCalculaotor")
{
String className = System.getProperty("extraFeeCalculator.class.name");
try {
efCalculator = (IExtraFeeCalculator)Class.forName(className).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
return efCalculator;
}
You should try
getResources().getAssets().open("config.txt")
instead of
context.getAssets().open("config.txt");
Change your Method with Single Parameter Context ....
Pass Context from where you Call this Method..
public void configuration(Context context)
{
String text = "";
try {
InputStream is = context.getAssets().open("config.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
text = new String(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
Yes now as per i think you are not aware from java structure...
Suppose you have this YOUR_CLASS_NAME.java
public void YOUR_CLASS_NAME{
Context context;
YOUR_CLASS_NAME(Context context){
this.context=context;
}
public void configuration(Context context)
{
String text = "";
try {
InputStream is = getAssets().open("config.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
text = new String(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
public IExtraFeeCalculator getExtraFeeCalculator()
{
if(efCalculator==null)
{
if(configuration(context) == "extrafeeCalculaotor")
{
String className = System.getProperty("extraFeeCalculator.class.name");
try {
efCalculator = (IExtraFeeCalculator)Class.forName(className).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
return efCalculator;
}
}
Use this Code
BufferedReader reader = null;
try {
StringBuilder returnString = new StringBuilder();
reader = new BufferedReader(
new InputStreamReader(getAssets().open("filename.txt")));
String mLine;
while ((mLine = reader.readLine()) != null) {
//process line
returnString.append(mLine );
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}

Saving data in file onStop and reading it in onCreate

I'm creating and saving data in a file in the onPause of the Base Activity but I'm reading the information in the onCreate of other activities. The thing is, the onPause saving has been called and no errors seem to appear in the logcat. However if I try to read the info in the onCreate I'm receiving the old content I had there, instead of the new one I saved.
public String parseToJsonString(Object object){
String json = gson.toJson(object);
return json;
}
public static boolean save(Context ctx, String filename, String content){
boolean wasSaved = false;
FileOutputStream fos = null;
try {
fos = ctx.openFileOutput(filename, Context.MODE_PRIVATE);
fos.write(content.getBytes());
fos.flush();
wasSaved = true;
Log.d(TAG, content);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(fos != null)
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return wasSaved;
}
#Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause");
String jsonSettings = APP().parseToJsonString(settings);
FileUtil.save(this, getString(R.string.file_settings_preferences), jsonSettings);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(getResources().getBoolean(R.bool.phone_size))
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.att_base_activity);
preferences = APP().getSecuredPreferences();
workflow = APP().createWorkflow();
settings = getAttendanceSettings();
Log.d(TAG, settings.toString());
toolbar = (Toolbar) findViewById(R.id.ab_tool_bar);
setSupportActionBar(toolbar);
}
public AttSettings getAttendanceSettings() {
AttSettings settings = null;
try {
JSONObject jsonSettings = FileUtil.getJSONContentFromFile(this,
getString(R.string.file_settings_preferences));
if (jsonSettings != null)
settings = new AttSettings(jsonSettings);
else
settings = new AttSettings();
} catch (IOException e) {
e.printStackTrace();
}
return settings;
}
I really don't know what I'm doing wrong, help would be appreciated.

How to import and export SharedPreferences file?

I'm trying to export and import the SharedPreferences file from my device i asked here the question before and i saw a example code of someone but i have problem with the"Entry" :
it given me:
The type DropBoxManager.Entry is not generic; it cannot be
parameterized with arguments <String, ?>
private boolean saveSharedPreferencesToFile(File dst) {
boolean res = false;
ObjectOutputStream output = null;
try {
output = new ObjectOutputStream(new FileOutputStream(dst));
SharedPreferences pref = context.getSharedPreferences(MySharedPreferences.MY_TEMP, 1);
output.writeObject(pref.getAll());
res = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (output != null) {
output.flush();
output.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return res;
}
#SuppressWarnings({ "unchecked" })
private boolean loadSharedPreferencesFromFile(File src) {
boolean res = false;
ObjectInputStream input = null;
try {
input = new ObjectInputStream(new FileInputStream(src));
Editor prefEdit = context.getSharedPreferences(MySharedPreferences.MY_TEMP, 1).edit();
prefEdit.clear();
Map<String, ?> entries = (Map<String, ?>) input.readObject();
for (Entry<String, ?> entry : entries.entrySet()) {
Object v = entry.getValue();
String key = entry.getKey();
if (v instanceof Boolean)
prefEdit.putBoolean(key, ((Boolean) v).booleanValue());
else if (v instanceof Float)
prefEdit.putFloat(key, ((Float) v).floatValue());
else if (v instanceof Integer)
prefEdit.putInt(key, ((Integer) v).intValue());
else if (v instanceof Long)
prefEdit.putLong(key, ((Long) v).longValue());
else if (v instanceof String)
prefEdit.putString(key, ((String) v));
}
prefEdit.commit();
res = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally {
try {
if (input != null) {
input.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return res;
}
Wrong Entry object.
You want Map.Entry<K, V>
http://docs.oracle.com/javase/7/docs/api/java/util/Map.Entry.html

Android getOnTouchListener with API version >= 15

I need to know if there has been set an OnTouchListener to a view.
Following code works fine below api level 15.
public static boolean isSetOnTouchListener_v8(View v) {
try {
Class<View> clazz = (Class<View>) Class.forName("android.view.View");
Field f = clazz.getDeclaredField("mOnTouchListener");
f.setAccessible(true);
if (f.get(v) == null) {
return false;
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return true;
}
Now I need the same method for api level 15 and above.
I tried the following code, but it's not working. Does anyone have any suggestions?
public static boolean isSetOnTouchListener_v15(View v) {
try {
Object listenerInfo = getListenerInfo(v);
if (listenerInfo != null) {
Class<? extends Object> clazz = listenerInfo.getClass();
Field f = clazz.getDeclaredField("mOnTouchListener");
f.setAccessible(true);
if (f.get(listenerInfo) == null) return false;
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
return true;
}
private static Object getListenerInfo(View v) {
Field f = null;
try {
f = View.class.getDeclaredField("mListenerInfo");
f.setAccessible(true);
return (Object) f.get(v);
} catch (Exception e) {
return null;
}
}

Store and read KeyPair with Android SharedPreferences

I'm looking for a kind of Serialization for the java.security.KeyPair to store and read from the Shared Preferences.
Storing the .toString() is now quite sinful cause there is no Constructor for the KeyPair.
Suggestions?
I'm afraid there is no way of storing a Serializable object in SharedPreferences. I recommend looking into saving it as a private file, see Android Storage Options, FileOutputStream and ObjectOutputStream for more information.
public static void write(Context context, Object obj, String filename) {
ObjectOutputStream oos = null;
try {
FileOutputStream file = context.openFileOutput(filename, Activity.MODE_PRIVATE);
oos = new ObjectOutputStream(file);
oos.writeObject(obj);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (oos != null) {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static Object read(Context context, String filename) {
ObjectInputStream ois = null;
Object obj = null;
try {
FileInputStream file = context.getApplicationContext().openFileInput(filename);
ois = new ObjectInputStream(file);
obj = ois.readObject();
} catch (FileNotFoundException e) {
// Just let it return null.
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (ois != null) {
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return obj;
}
I actually solved in it this way:
I first create a String by using Base64, which I store and then recreate from the Shared Proferences:
SharedPreferences prefs = this.getSharedPreferences(
PATH, Context.MODE_PRIVATE);
String key = prefs.getString(KEYPATH, "");
if (key.equals("")) {
// generate KeyPair
KeyPair kp = Encrypter.generateKeyPair();
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutputStream o;
try {
o = new ObjectOutputStream(b);
o.writeObject(kp);
} catch (IOException e) {
e.printStackTrace();
}
byte[] res = b.toByteArray();
String encodedKey = Base64.encodeToString(res, Base64.DEFAULT);
prefs.edit().putString(KEYPATH, encodedKey).commit();
} else {
// read the KeyPair from internal storage
byte[] res = Base64.decode(key, Base64.DEFAULT);
ByteArrayInputStream bi = new ByteArrayInputStream(res);
ObjectInputStream oi;
try {
oi = new ObjectInputStream(bi);
Object obj = oi.readObject();
Encrypter.setMyKeyPair((KeyPair) obj);
Log.w(TAG, ((KeyPair) obj).toString());
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}

Categories

Resources