How to import and export SharedPreferences file? - android

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

Related

Parsing json with AsyncTaskLoader

I'm trying to use AsyncTaskLoader to retrieve data then parse the resulting json file, however, I can't figure out why I keep getting a
return null;
instead of returning
return gameList;
DailyScheduleFragment.java
Method calling the Loader:
public void loadGameScheduleList() {
getLoaderManager().initLoader(LOADER_ID_DAILY_SCHEDULE, null, new LoaderCallbacks<ArrayList<Game>>() {
public Loader<ArrayList<Game>> onCreateLoader(int id, Bundle args) {
return new DailyScheduleLoader(DailyScheduleFragment.this.getContext());
}
public void onLoadFinished(Loader<ArrayList<Game>> loader, ArrayList<Game> data) {
if (data == null) {
Exception exception = ((DailyScheduleLoader) loader).getException();
if (exception == null) {
return;
}
if (exception instanceof NoNetworkException) {
DailyScheduleFragment.this._btnMessage.setText(R.string.general_msg_no_network_connection_turn_on);
DailyScheduleFragment.this._btnMessage.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intents.networkSettings(DailyScheduleFragment.this.getContext());
}
});
DailyScheduleFragment.this._progressBar.setVisibility(View.GONE);
DailyScheduleFragment.this._btnMessage.setVisibility(View.GONE);
return;
}
DailyScheduleFragment.this._btnMessage.setText(R.string.general_msg_something_went_wrong);
DailyScheduleFragment.this._btnMessage.setOnClickListener(null);
DailyScheduleFragment.this._progressBar.setVisibility(View.GONE);
DailyScheduleFragment.this._btnMessage.setVisibility(View.GONE);
return;
}
DailyScheduleFragment.this._games.clear();
Iterator it = data.iterator();
while (it.hasNext()) {
DailyScheduleFragment.this._games.add((Game) it.next());
}
DailyScheduleFragment.this._adapter.notifyDataSetChanged();
DailyScheduleFragment.this.displayListState();
}
public void onLoaderReset(Loader<ArrayList<Game>> loader) {
}
}).forceLoad();
}
DailyScheduleLoader.java
public class DailyScheduleLoader extends AsyncTaskLoader<ArrayList<Game>> {
private Context _context;
private Exception _exception;
public DailyScheduleLoader(Context context) {
super(context);
this._context = context;
}
public ArrayList<Game> loadInBackground() {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this._context);
try {
ArrayList<Game> gameList = Parse.gameList(Networking.sendHttpRequest("http://api.sportradar.us/nhl/trial/v5/en/games/2018/01/01/schedule.json?api_key=xxx", this._context));
return gameList;
} catch (Exception e) {
this._exception = e;
return null;
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return null;
}
public Exception getException() {
return this._exception;
}
Network class:
public static final class Networking {
public static String sendHttpRequest(String urlString, Context context) throws Throwable {
NoNetworkException e;
Exception ex;
Throwable th;
if (urlString == null || urlString.trim().equals(BuildConfig.FLAVOR)) {
throw new NullPointerException("urlString");
}
HttpURLConnection httpCon = null;
InputStream input_stream = null;
InputStreamReader input_stream_reader = null;
BufferedReader input = null;
StringBuilder response = new StringBuilder();
try {
if (isNetworkAvailable(context)) {
httpCon = (HttpURLConnection) new URL(urlString).openConnection();
if (httpCon.getResponseCode() != 200) {
Log.e("TAG", "Cannot Connect to : " + urlString);
if (input == null) {
return null;
}
try {
input_stream_reader.close();
input_stream.close();
input.close();
} catch (IOException e2) {
e2.printStackTrace();
}
if (httpCon == null) {
return null;
}
httpCon.disconnect();
return null;
}
input_stream = httpCon.getInputStream();
InputStreamReader input_stream_reader2 = new InputStreamReader(input_stream);
try {
BufferedReader input2 = new BufferedReader(input_stream_reader2);
while (true) {
try {
String line = input2.readLine();
if (line == null) {
break;
}
response.append(line).append("\n");
} catch (Exception e4) {
ex = e4;
input = input2;
input_stream_reader = input_stream_reader2;
} catch (Throwable th2) {
th = th2;
input = input2;
input_stream_reader = input_stream_reader2;
}
}
if (input2 != null) {
try {
input_stream_reader2.close();
input_stream.close();
input2.close();
} catch (IOException e22) {
e22.printStackTrace();
}
if (httpCon != null) {
httpCon.disconnect();
input = input2;
input_stream_reader = input_stream_reader2;
return response.toString();
}
}
input_stream_reader = input_stream_reader2;
} catch (Exception e6) {
ex = e6;
input_stream_reader = input_stream_reader2;
ex.printStackTrace();
if (input != null) {
try {
input_stream_reader.close();
input_stream.close();
input.close();
} catch (IOException e222) {
e222.printStackTrace();
}
if (httpCon != null) {
httpCon.disconnect();
}
}
return response.toString();
} catch (Throwable th4) {
th = th4;
input_stream_reader = input_stream_reader2;
if (input != null) {
try {
input_stream_reader.close();
input_stream.close();
input.close();
} catch (IOException e2222) {
e2222.printStackTrace();
}
if (httpCon != null) {
httpCon.disconnect();
}
}
throw th;
}
return response.toString();
}
throw new NoNetworkException();
} catch (NoNetworkException e7) {
e = e7;
throw e;
} catch (Exception e8) {
ex = e8;
ex.printStackTrace();
if (input != null) {
input_stream_reader.close();
input_stream.close();
input.close();
if (httpCon != null) {
httpCon.disconnect();
}
}
return response.toString();
}
}
public static boolean isNetworkAvailable(#NonNull Context context) {
#SuppressLint("WrongConstant") NetworkInfo activeNetworkInfo = ((ConnectivityManager) context.getSystemService("connectivity")).getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
Parse class:
public static class Parse {
public static ArrayList<Game> gameList(String json) throws JSONException {
ArrayList<Game> games = new ArrayList();
JSONArray results = new JSONObject(json).getJSONArray("games");
// looping through All Games
for (int i = 0; i < results.length(); i++) {
JSONObject gameJSON = results.getJSONObject(i);
Game game = new Game();
game.setId(gameJSON.getString(Responses.Games.VALUE_ID));
game.setStatus(gameJSON.getString(Responses.Games.VALUE_STATUS));
games.add(game);
}
return games;
}
}
I found the code on a website and trying to modify it to suit my needs. For the most part, it works well, except I can't figure out where I'm going wrong with this.
If it helps, here's the json file that's returned in the request (sorry about the formatting):
{"date":"2018-01-01","league":{"id":"fd560107-a85b-4388-ab0d-655ad022aff7","name":"NHL","alias":"NHL"},"games":[{"id":"6d20bdbd-b5e0-46ab-8b98-45ea01ab0e2b","status":"scheduled","coverage":"full","scheduled":"2018-01-01T18:00:00+00:00","reference":"20601","venue":{"id":"faebd24e-ccfb-4e7c-aa58-1dee9e82bb0f","name":"Citi Field","capacity":45000,"address":"123 Roosevelt Ave","city":"Queens","state":"NY","zip":"11368","country":"USA","time_zone":"US/Eastern"},"broadcast":{"network":"NBC"},"home":{"id":"4416d559-0f24-11e2-8525-18a905767e44","name":"Buffalo Sabres","alias":"BUF"},"away":{"id":"441781b9-0f24-11e2-8525-18a905767e44","name":"New York Rangers","alias":"NYR"}}]}
Go here if you want it formatted.
I've added break points and stepped through the code to check the variables. All seems right, up until the
return gameList;

Android - How to clear sharepreference by position recyclerview

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();
}
}

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
}
}
}

How to save an application's data?

I have written a Web View app, which logs you into 12 different sites (sign in) which works pretty fine. However, i am trying to figure out a way to backup my web view's data (so that all the login credentials are saved) to SD card. the only way i have found is to copy the root/data/data/com.example/your app folder.
How do i copy this folder somewhere to my SD card using root command on the click of a button?
this is how i access and delete the data folder
private void clear() {
String cmd = "pm clear com.wagtailapp";
ProcessBuilder pb = new ProcessBuilder().redirectErrorStream(true)
.command("su");
Process p = null;
try {
p = pb.start();
} catch (IOException e) {
e.printStackTrace();
}
StreamReader stdoutReader = new StreamReader(p.getInputStream(),
CHARSET_NAME);
stdoutReader.start();
out = p.getOutputStream();
try {
out.write((cmd + "\n").getBytes(CHARSET_NAME));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
out.write(("exit" + "\n").getBytes(CHARSET_NAME));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
p.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
String result = stdoutReader.getResult();
}
}
streamreader.java
class StreamReader extends Thread {
private InputStream is;
private StringBuffer mBuffer;
private String mCharset;
private CountDownLatch mCountDownLatch;
StreamReader(InputStream is, String charset) {
this.is = is;
mCharset = charset;
mBuffer = new StringBuffer("");
mCountDownLatch = new CountDownLatch(1);
}
String getResult() {
try {
mCountDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
return mBuffer.toString();
}
#Override
public void run() {
InputStreamReader isr = null;
try {
isr = new InputStreamReader(is, mCharset);
int c = -1;
while ((c = isr.read()) != -1) {
mBuffer.append((char) c);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (isr != null)
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
mCountDownLatch.countDown();
}
}
}

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