Concatenating Two Values From Shared Preferences - android

Having a little trouble figuring this one out. I have two values stored in my Config class as shared preferences, an email address and a URL. This will parse JSON to a ListView from my server. I'm trying to concatenate them together but it is not working.
Config.java
public class Config {
//URL to JSON API
public static final String GET_ORDERS_URL = "http://192.568.8.245/android/json3.php?user_email=";
//Storing current user
public static final String EMAIL_SHARED_PREF = "user_email";
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
// Concatenated URL to JSON API
private static final String baseurl = Config.GET_ORDERS_URL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Fetching email from shared preferences
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
String user_email = sharedPreferences.getString(Config.EMAIL_SHARED_PREF,"Not Available");
//Concatenated JSON API URL
String url = baseurl + user_email;
//Initializing Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.ic_back);
toolbar.setTitle(user_email);
}
I know user_email is being stored because I am calling it within MainActivity and setting the title of my toolbar with it. Replacing user_email with an actual email results in success, obviously I don't want to do that. Any idea what I need to do?

use android UrlEncoder class to make correct url
this is the best way. Using manual concatenate can result in malformed requests.
and also you can build URI like this
String uri = Uri.parse("http://...")
.buildUpon()
.appendQueryParameter("key", "val")
.build().toString();

Get the values and call concatStrings(str1,str2);
Use something like this
String concatStrings(String string1,String string2){
StringBuilder strBuilder=new StringBuilder();
strBuilder.append(string1);
strBuilder.append(string2);
return strBuilder.toString();
}

Note: the OP has applied this answer already to the code in it's question. It was meant for version 1 of the question.
The concatenation is working and results in the string:
"http://192.568.8.245/android/json3.php?user_email=user_email"
because you concatenate with the shared preferences key, not the value.
You want to concatenate with the value retrieved from shared preferences instead
String user_email = sharedPreferences.getString(Config.EMAIL_SHARED_PREF);
String url = Config.GET_ORDERS_URL + user_email;

Related

populating recyclerview from nested table Firebase database

I have this structure in my Database inside the UserID I have this random ID which I declared when adding data to database I don't know how to call that to display the info inside to recycler view. Actually I can display the info in Recyclerview if the declared pushid is not there but I need that push ID to work on other modules. I am still learning so I get easily confused with this kind of thing. Any help would be so much appreciated.
This is the line which is calling the table.
mToolsDatabase = FirebaseDatabase.getInstance().getReference().child("toolHistory");
mToolsDatabase.child(list_user_id).child(mCurrentUser.getUid()).addValueEventListener(new ValueEventListener(){
public void onDataChange(DataSnapshot dataSnapshot) {
final String toolName = dataSnapshot.child("name").getValue().toString();
final String toolUser = dataSnapshot.child("user").getValue().toString();
final String toolBorrow = dataSnapshot.child("dateTimeBorrowed").getValue().toString();
final String toolReturn = dataSnapshot.child("dateTimeReturn").getValue().toString();
final String toolStatus = dataSnapshot.child("status").getValue().toString();
final String toolId = dataSnapshot.child("logId").getValue().toString();
viewHolder.setName(toolName);
viewHolder.setUser(toolUser);
viewHolder.setDateTimeBorrowed(toolBorrow);
viewHolder.setDateTimeReturn(toolReturn);
viewHolder.setStatus(toolStatus);
viewHolder.setLogId(toolId);
}
Firebase has its inbuilt method FirebaseRecyclerAdapter for display items in RecyclerView
Also, you can follow this link for more info
https://grokonez.com/android/firebase-realtime-database-display-list-of-data-firebaserecycleradapter-android-development

All keys in SharedPreferences return same value

I am using Shared preferences for the first time and getting errors.
my code is like this :
public class MainActivity extends Activity {
static final String ONE = "";
static final String TWO = "";
private static SharedPreferences mSharedPreferences;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences.Editor edi = mSharedPreferences.edit();
edi.putString(ONE, "1");
edi.putString(TWO, "2");
edi.commit();
String one = mSharedPreferences.getString(ONE,"1");
String two = mSharedPreferences.getString(TWO,"2");
System.out.println("Your Numbers: "one+ " " + two);
}
}
Expected Output:
Your Numbers: 1 2
Console Output:
Your Numbers: 2 2
I can't figure out what i am doing wrong in it. Share your views.
You need to add some string to the names/keys. Currently both key names are blank and hence your code is overwriting the same preference value
.
Change the static strings as follows and it should work fine.
static final String ONE = "one";
static final String TWO = "two";
Also try using a helper class to make things simpler with shared preferences. Here is one that i wrote: Android-SharedPreferences-Helper
Because of this:
static final String ONE = "";
static final String TWO = "";
change it to:
static final String ONE = "One";
static final String TWO = "Two";
U need unique values for every preference.
In your case the ONE gets overridden by the TWO.
Extra info
If u look in the android docs here you will see that putString requires two parameters:
key : String: The name of the preference to modify.
value : String: The new value for the preference.
and if u than look at getString here you will notice that it also has two parameters, both the same as putString:
key : String: The name of the preference to retrieve. -- important
defValue : String: Value to return if this preference does not exist.
The name/key is the part that let the get part know from which preference it needs to get the value.
Hope this will make things a bit clearer for u!
Both the strings are empty
static final String ONE = "";
static final String TWO = "";
It should be like :
static final String ONE = "one";
static final String TWO = "two";

Call Email intent by getting data from sub strings?

I am making QR code scan app. When i scan the QR Code for Email, I get the result i.e. given below,
String data = MATMSG:TO:abc#hotmail.com;SUB:email subject;BODY:email body;;
For getting code type i.e. MATMSG in string above i am doing this,
String[] parts = scanData.split(":");
qrCodeType = parts[0];
I want to make 3 strings from the data string like,
String to = abc#hotmail.com;
String subject = email subject;
String body = email body;
How can i use string functions to do this? Notice colons and semicolons in String data
Try the following:
String[] items = data.split(";");
String to = items[0].split(":")[2];
String subject = items[1].split(":")[1];
String body = items[2].split(":")[1];
Hope it helps

Saving non-generic type objects persistently in Android without setting up a database

Basically I have an app that fetches some information from Facebook, and that info can be regularly updated. I want to save that information in the phone so that when the user does not have an internet connection he can still see the latest fetch.
The information is saved in a
ArrayList<HashMap<String, String>>
What should I use?
The amount of information to save is small. 7 entries in the HashMap and at most 15 in the ArrayList. I use this datatype because I display it in a ListView.
Again that info must be saved even is the app is closed.
Regards
you can write it to a json or xml file , and load that file when app started
I think the best way is to save it to SharedPreferences. An easy way is to convert this object to JSON String and store that String in the SharedPreferences, and then when needed, get JSON string back and convert it back to your object. The library that does it nicely is Google's gson library. If you are using Gradle, import it like this:
dependencies {
...
compile 'com.google.code.gson:gson:2.2.+'
...
}
then, you can use this simple class to convert objects to/from String
public class JsonHelper {
public static Gson gson = new GsonBuilder()
.setPrettyPrinting().create();
public static Object getObject(String jsonString, Type classType){
return gson.fromJson(jsonString, classType);
}
public static String getJsonString(Object object){
return gson.toJson(object);
}
}
then, you can do this:
//to get JSON string from your object
ArrayList<HashMap<String, String>> yourList = ...;
String JSONString = JsonHelper.getJsonString(yourList);
//save string to shared preference
//to get your object from JSON string
//get JSON string from shared prefs
String yourJsonString = ...;
Type t = new TypeToken<ArrayList<HashMap<String, String>>>() { }.getType();
ArrayList<HashMap<String, String>> yourList = (ArrayList<HashMap<String, String>>)JsonHelper.getObject(yourJsonString, t);
here is some info about SharedPreferences and some info on how to use SharedPreferences, its really easy.
Then, you can add these methods to your Activity
public class YourActivity extends Activity{
public static final String KEY_PREFS = "com.your_app_name";
public static final String KEY_DATA = "your_data";
...
public static void saveDataToPrefs(String json){
getSharedPreferences(KEY_PREFS, Context.MODE_PRIVATE).edit().putString(KEY_DATA, json).commit();
}
public ArrayList<HashMap<String, String>> getDataFromPrefs(){
Type t = new TypeToken<ArrayList<HashMap<String, String>>>() { }.getType();
return (ArrayList<HashMap<String, String>>)JsonHelper
.getObject(getSharedPreferences(KEY_PREFS, Context.MODE_PRIVATE)
.getString(KEY_DATA, ""), t);
}
}
Please note this is not the best way to save the info in the app persistantly, as this method can produce unexpected bugs, like in case the final JSON string needs to be larger then the String object in the Android system. The best way is to have a database.
Have you looked at serialisation before? I find it very useful for this type of thing.
What is object serialization?
You can serialise out your data into an arbitrary file on the device SD card for example, then just read it back in on startup. I've used it for storing data in games, e.g. a save file.

Android livesdk how to getharedPreferences after LiveAuthClient

I am using following source https://github.com/liveservices/LiveSDK-for-Android.
Do someone know how to get shared preferences after the LiveAuthClient process. I have to get
REFRESH_TOKEN_KEY and COOKIE_DELIMITER from the sharedprefences file and clear it after saving it in a database. The aim is to save this to values in a database to login with multiple skydrive accounts.
Any ideas would be helpful. Thank you.
If Someone wants to know use:
/** Name of the preference file */
public static final String FILE_NAME = "com.microsoft.live";
public static final String COOKIES_KEY = "cookies";
public static final String REFRESH_TOKEN_KEY = "refresh_token";
SharedPreferences preferences = getSharedPreferences(SDriveConstants.FILE_NAME, Context.MODE_PRIVATE);
String refresh_tkn_key = preferences.getString(SDriveConstants.REFRESH_TOKEN_KEY, "");
String cookies_key = preferences.getString(SDriveConstants.COOKIES_KEY, "");

Categories

Resources