How to retrieve SharedPreferences string? - android-studio

While working on an android app, I discovered, that I would have to use SharedPreferences to store login data (url, port, name), but since I am new to this, I am not sure, how to access the data for MQTT to use those inputs and login.
in tab3_fragment.java, the SharedPreferences get set this way:
public void saveData(){
SharedPreferences userDetails = (SharedPreferences) getContext().getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = userDetails.edit();
editor.putString(url, input_url.getText().toString());
editor.putString(port, input_port.getText().toString());
editor.apply();
Toast.makeText(getActivity(), "Einstellungen gespeichert", Toast.LENGTH_SHORT).show();
}
public void loadData(){
SharedPreferences userDetails = getContext().getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE);
text_url = userDetails.getString(url, " ");
text_port = userDetails.getString(port, " ");
}
This is how I try to access the SharedPreferences:
public MqttHelper(Context context){
SharedPreferences userDetails = getContext().getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE);
final String url = userDetails.getString(tab3_fragment.url, " ");
final String port = userDetails.getString(tab3_fragment.port, " ");
String strArray2[] = {url, port};
String serverUri = TextUtils.join(":", strArray2);
Toast.makeText(getActivity(), serverUri, Toast.LENGTH_SHORT).show();
When running the above code from within another fragments onCreateView, it runs fine, but when I add the code to the MqttHelper.java, so that it can load the settings, it returns error
cannot resolve method `getContext()`.
How can I make the MqttHelper access the SharedPreferences?

When running the above code from within another fragments onCreateView, it runs fine, but when I add the code to the MqttHelper.java, so that it can load the settings, it returns error
cannot resolve method getContext().
As I can see in your code you are passing the context already by parameter, so I don't see any need to use getContext() there, you can easy use context
Bad
public MqttHelper(Context context){
SharedPreferences userDetails = getContext().getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE);
Good
public MqttHelper(Context context){
SharedPreferences userDetails = context.getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE);
Also I'm seeing that you are displaying a Toast using getActivity() you can use also getActivity() to get the context as an alternative.

Related

Shared Preference Empty On Next run

I have A SharedPreference That I want to save an array list for the next time I open the app. But The next time I start the app it comes up as empty. I execute the save onDestroy because I dont want to push a button. I dont know whats going on. Any help would be appreciated.
I run LoadData() Method inside onCreate() Method.
public void LoadData(){
SharedPreferences sp = getSharedPreferences("SavedArrayList",MODE_PRIVATE);
Gson gson = new Gson();
String json = sp.getString("Arraylist", null);
Type type = new TypeToken<ArrayList<ListItems>>() {}.getType();
if (json != null)items = gson.fromJson(json, type);
}
#Override
protected void onDestroy() {
SharedPreferences sp = getSharedPreferences("SavedArrayList",MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
Gson gson = new Gson();
String json = gson.toJson(items);
editor.putString("Arraylist", json);
editor.apply();
super.onDestroy();
}
All I did was moved it to onPause and onResume now it works fine.

Why I cant Select element in DockablePane when i use IExternalEventHandler

i want select element when i click button.i use IExternalEventHandler ,but i cant use
method: pickobject/pickobjects ,i change the method to pickPoint the hander run success.
event
public class ExecuteEvent : IExternalEventHandler
{
public string ElementId { get; set; }
public void Execute(UIApplication app)
{
UIDocument uidoc = app.ActiveUIDocument;
Autodesk.Revit.DB.Document doc = uidoc.Document;
Autodesk.Revit.UI.Selection.Selection sel = uidoc.Selection;
Autodesk.Revit.DB.Reference re = sel.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Element);
Autodesk.Revit.DB.XYZ point = sel.PickPoint("select");
ElementId = re.GetType().Name;
}
public string GetName()
{
return "ExecuteEvent";
}
}
hander
Exc = new ExecuteEvent();
ExternalHander = ExternalEvent.Create(Exc);
button click
private void Button_Click(object sender, RoutedEventArgs e)
{
ExternalHander.Raise();
SetLabelText(Exc.ElementId);
}
Apparently, the external event handler does not provide you with a valid user interface context. To get such a context, you might want to subscribe to the Idling event instead. That event is called when Revit has nothing else to do and hence is free to interact with the user.

Android studio, why does progressbar disappear before asynctasks are complete?

I have the following Asyntask in Android Studio.
I'm battling to get the progressbar to work though, the progressbar pops up but then immediately disappears.
I want to know:
Why is it not waiting for the tasks in the DoInBackground to complete before it disappears?
Any advice would be appreciated. I am a beginner so please excuse the silly question if it is indeed a silly question.
The tasks within DoInBackground are calls to a volley requests, which copy data from a remote sql database into the devices sqlite database.
Thanks.
public class AsyncTask extends android.os.AsyncTask<Integer, Integer, String> {
ProgressBar pb;
int status = 0;
public void setProgressBar(ProgressBar progressBar) {
this.pb = progressBar;
}
#Override
protected void onPreExecute() {
Log.d(TAG, "zzzzz2: " + "Pre");
pb.setVisibility(View.VISIBLE);
super.onPreExecute();
}
#Override
protected String doInBackground(Integer[] objects) {
Log.d(TAG, "zzzzz2: " + "DoIn");
// if user doesnt exist in db add to server db
String strUser = mFirebaseUser.getUid();
String strDisplayName = mFirebaseUser.getDisplayName();
String strEmail = mFirebaseUser.getEmail();
clsServerClass.addUserToServer(strUser, strDisplayName, strEmail, context);
// load 12 tables into sqlite database
clsServerClass.copyTblVersions(context);
clsServerClass.copyAnimalClassTable(context);
clsServerClass.copyAnimalGroupTable(context);
clsServerClass.copyAnimalTable(context);
clsServerClass.copyTblSeasons(context);
clsServerClass.copyRegions(context);
clsServerClass.copyCountries(context);
clsServerClass.copyProvinces(context);
clsServerClass.copyHotspots(context);
clsServerClass.copyHabitats(context);
clsServerClass.getMyPlaces(strUser, context);
clsServerClass.getSightingsUser(strUser, context);
Cursor cntry = getCsr("animal_unique_key", "tbl_lookup_animals");
Log.d(TAG, "yyyya: " + cntry.getCount());
JSONArray arrayList1 = createListArray("animal_class_key", 1);
createListSharedPref("List1_name", "List 1: All birds", "List1_where", arrayList1);
JSONArray arrayList2 = createListArray("animal_class_key", 2);
createListSharedPref("List2_name", "List 2: All Mammals", "List2_where", arrayList2);
JSONArray arrayList3 = createListArray("animal_class_key", -99);
createListSharedPref("List3_name", "List 3: All Animals", "List3_where", arrayList3);
JSONArray arrayList4 = createListArray("animal_class_key", 3);
createListSharedPref("List4_name", "List 4: All Reptiles", "List4_where", arrayList4);
JSONArray arrayList5 = createListArray("animal_class_key", 4);
createListSharedPref("List5_name", "List 5: All Amphibians", "List5_where", arrayList5);
return null;
}
#Override
protected void onProgressUpdate(Integer[] values) {
Log.d(TAG, "zzzzz3: " + "Update");
pb.setProgress(values[0]);
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String s) {
Log.d(TAG, "zzzzz2: " + "post");
pb.setVisibility(View.GONE);
super.onPostExecute(s);
}
}
Problem lies in onProgressUpdate method.
Docs
onProgressUpdate() : This method receives progress updates from
doInBackground method, which is published via publishProgress method,
and this method can use this progress update to update the UI thread
Since you are not passing any value to your onProgressUpdate, your progress bar disappears immediately.
In doInBackground method after Log.d(TAG, "zzzzz2: " + "DoIn");
Add
publishProgress(5); // Calls onProgressUpdate()
//5 is just an example integer
Now, it should work fine.
To learn more about how to better make use of onProgressUpdate(), consult https://www.tanelikorri.com/tutorial/android/asynctask-tutorial/

'this' is not available in variables android studio

I have a class to take data from a database and every time I create a variable in the debug mode the name of the variable appears with the message 'this' is not available and I cannot save any type of data in it.
public class DatosPerfilUsuario {
RequestQueue requestQueue;
SharedPreferencias sharedPreferencias = new SharedPreferencias();
String[] StringSplit;
public void RetirarPerfilUsuario(final Context context, final ImageView imageView, final EditText nombre, final EditText nombreusuario, final EditText sexo, final EditText edad, final EditText email, final EditText bio){
StringRequest getRequest = new StringRequest(Request.Method.POST, DatosBase.CONEXION_DB_RETIRAR_PERFILUSUARIO, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(response.equals("0")){
}else {
StringSplit = response.split("/");
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
protected Map<String,String> getParams(){
Map<String, String> params = new HashMap<String, String>();
params.put("NombreUsuario",sharedPreferencias.obtenerValorString(context,"Usuario").toLowerCase());
return params;
}
};
requestQueue = Volley.newRequestQueue(context);
requestQueue.add(getRequest);
}
Code
This situation happens to me with each type of variable that I create int, string, bool ...
I have different classes that do the same, but the problem only arises in this.
I have looked for a solution to the problem in google but there is very little information about this problem, if someone has the solution or understands why this problem is due I would appreciate your help.
UPDATED
It looks like this is not preventing you from compiling and running the code, only that you can't view the variable's contents in the debug window. Sorry. This is not uncommon. The debugger can't determine the this in the current context.
It looks like you may be using Android Studio? If so, check this: https://stackoverflow.com/a/37273436/12431728
OLD / WRONG
Your Response.Listener<String> is an anonymous class, so this refers to the anonymous class. Since StringSplit is a field of the outer class, you should be able to access it as:
OuterClassName.this.StringSplit = ...
Where OuterClassName is the name of the class that contains this code (and StringSplit).

Activity that runs for once is not coming again when user close that app

i have my app's signup type page which is use for getting details of user and i have made it to run for one time only using sharedpreferences method but i got one problem that if user close that app during filling of details than that activity is not coming again.
setContentView(R.layout.register_data);
getSharedPreferences("PREFERENCE", MODE_PRIVATE)
boolean isFirstRun = getSharedPreferences("PREFERENCE",MODE_PRIVATE).getBoolean("isFirstRun", true);
if (isFirstRun){
startActivity(new Intent(MainActivity.this, RegisterDetail.class));
.edit()
.putBoolean("isFirstRun", false)
.apply();
}
Check this link
May be it is helpful to you
Some ref
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean previouslyStarted = prefs.getBoolean(getString(R.string.pref_previously_started), false);
if(!previouslyStarted) {
SharedPreferences.Editor edit = prefs.edit();
edit.putBoolean(getString(R.string.pref_previously_started), Boolean.TRUE);
edit.commit();
showHelp();
}

Resources