How do I update my static context value saved from shared preferences? - android

I am planning to implement an easter egg to change my API through an alertdialog, but currently after I change my url endpoint and submit it it saves it in shared preferences, but next time i save it, it does save it in shared preferences ,but doesn't reflect in the app. How do I make it such that every single time i change it ,it applies to my apiendpoint as expected:
Alertdialog which triggers on 5 taps:
myimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
long time= System.currentTimeMillis();
//if it is the first time, or if it has been more than 3 seconds since the first tap ( so it is like a new try), we reset everything
if (startMillis==0 || (time-startMillis> 3000) ) {
startMillis=time;
count=1;
}
//it is not the first, and it has been less than 3 seconds since the first
else{ // time-startMillis< 3000
count++;
}
if (count==5) {
final AlertDialog dialogBuilder = new AlertDialog.Builder(LoginActivity.this).create();
LayoutInflater inflater = LoginActivity.this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.custom_dialog, null);
final EditText editText = (EditText) dialogView.findViewById(R.id.edt_comment);
Button submitButton = (Button) dialogView.findViewById(R.id.buttonSubmit);
Button cancelButton = (Button) dialogView.findViewById(R.id.buttonCancel);
Button resetButton = (Button) dialogView.findViewById(R.id.buttonReset);
editText.setTextColor(getResources().getColor(R.color.black,null));
if(SharedPreferencesHelper.getSomeStringValue(getApplicationContext()) != null) {
editText.setText( SharedPreferencesHelper.getSomeStringValue(getApplicationContext()));
}
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialogBuilder.dismiss();
}
});
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//save the endpoint value in shared preferences
SharedPreferencesHelper.setSomeStringValue(getApplicationContext(),editText.getText().toString());
dialogBuilder.dismiss();
}
});
resetButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferencesHelper.setSomeStringValue(getApplicationContext(),BuildConfig.BASE_URL);
dialogBuilder.dismiss();
}
});
dialogBuilder.setView(dialogView);
dialogBuilder.setCanceledOnTouchOutside(false);
dialogBuilder.show();
}
}
});
Here's my sharedpreferenceshelper:
public class SharedPreferencesHelper {
private static final String APP_SETTINGS = "APP_SETTINGS";
// properties
private static final String SOME_STRING_VALUE = "SOME_STRING_VALUE";
// other properties...
private SharedPreferencesHelper() {}
private static SharedPreferences getSharedPreferences(Context context) {
return context.getSharedPreferences(APP_SETTINGS, Context.MODE_PRIVATE);
}
public static String getSomeStringValue(Context context) {
return getSharedPreferences(context).getString(SOME_STRING_VALUE , null);
}
public static void setSomeStringValue(Context context, String newValue) {
final SharedPreferences.Editor editor = getSharedPreferences(context).edit();
editor.putString(SOME_STRING_VALUE , newValue);
editor.apply();
}
}
Finally, here's my Apiendpoint class:
final class ApiEndPoint {
private static String NEW_URL = SharedPreferencesHelper.getSomeStringValue(MyApp.getAppContext());
static final String ENDPOINT_SERVER_LOGIN = NEW_URL
+ "/service-myverification-link/v1/link/verify";
private ApiEndPoint() {
// This class is not publicly instantiable
}
}
For the code above, I was wondering how do i make the NEW_URL link more dynamic, seems like its sticking to the value saved first time and does not change after. I need to keep this link static due to :
#Override
public Single<LoginResponse> doServerLoginApiCall(LoginRequest request) {
return Rx2AndroidNetworking.post(ApiEndPoint.ENDPOINT_SERVER_LOGIN)
.doNotCacheResponse()
.addBodyParameter(request)
.build()
.getObjectSingle(LoginResponse.class);
}
Any idea, how I can fix this so I can update the link in NEW_URL every single time that it sticks to the new value instead of the value stored the first time?

You will need to use the onSharedPreferenceChangeListener
SharedPreferencesHelper.getSharedPreferences(context).registerOnSharedPreferenceChangeListener(
new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if(key.equals("SOME_STRING_VALUE")){
NEW_URL = prefs.getString("SOME_STRING_VALUE" , null);
}
}
});

Why don't you send the Url as a parameter every time:
#Override
public Single<LoginResponse> doServerLoginApiCall(LoginRequest request, String url) {
return Rx2AndroidNetworking.post(url)
.doNotCacheResponse()
.addBodyParameter(request)
.build()
.getObjectSingle(LoginResponse.class);
}
Method call:
doServerLoginApiCall(request, SharedPreferencesHelper.getSomeStringValue(getApplicationContext()) + ENDPOINT);

Related

How to update Activity's textview when returning from another Activity's RecyclerView?

Hello (First of all excuse my English if something is wrong, it's not my first language), I'm developing an app with the IMDB API to keep up to date with your favorite series (no links or anything illegal).
I'm gonna focus on the two activities in which the problem is: The first Activity, ActivitySerieJson contains a recycled view filled with all the seasons in card view. Each card view contains season thumbnail, season number and the users completed view percentage:
ActivitySerieJson.
The second activity, ActivityTemporadaJSON contains another recyclerview, this one is filled with chapters name, thumbnail and an eye-shaped button that, when pressed, marks the chapter as seen on DB. The problem is that when I go back to previous activity the completed view percentage TextView is not being refreshed.
ActivityTemporadaJSon
This is my code:
RecyclerAdapterTemporada
public void bindPhoto(Temporada mtemporada, String idSerie, String tipo) {
temporada = mtemporada;
String Nombre = temporada.getNombreTemporada();
if(Nombre.length() >= 25)
{
Nombre = Nombre.substring(0,22);
Nombre = Nombre + "...";
}
AQuery androidAQuery=new AQuery(mItemImage.getContext());
androidAQuery.id(mItemImage).image(temporada.getPoster(), true, true, 150,0);
//Picasso.with(mItemImage.getContext()).load(mserie.getPoster()).into(mItemImage);
mItemDate.setText(Nombre);
mItemidTMDB.setText(idSerie);
mItemNumTemp.setText(Integer.toString(temporada.getNumeroTemporada()));
mItemNumEps.setText(Integer.toString(temporada.getNumeroEpisodios()));
//THIS CODE SECTION CALCULATES PERCENTAGE
if(tipo.equalsIgnoreCase("SQL"))
{
int porcen=1;
int numEps = temporada.getNumeroEpisodios();
if(numEps == 0){
numEps = 1;
}
porcen = (temporada.getEpisodiosVsitos() * 100) / numEps;
mNumEpsVistoVal.setText(Integer.toString(porcen) + "%");
}
else
{
mNumEpsVisto.setVisibility(View.INVISIBLE);
mNumEpsVistoVal.setVisibility(View.INVISIBLE);
}
}
}
}
RecyclerAdapterEpisodio
public class RecyclerAdapterEpisodio extends
RecyclerView.Adapter<RecyclerAdapterEpisodio.EpisodioHolder> {
private ArrayList<Episodio> mEpisodio;
private int IdSerie;
private RecyclerAdapterEpisodio miAdaptador;
private String Tipo;
private View v;
//5
#Override
public void onClick(View v) {
/*Context context = itemView.getContext();
Intent showPhotoIntent = new Intent(context, Pelicula.class);
showPhotoIntent.putExtra(PHOTO_KEY, peli);
context.startActivity(showPhotoIntent);*/
}
public void bindPhoto(final Episodio mEpisodio, final int mIdSerie, String tipo) {
episodio = mEpisodio;
if (tipo.equalsIgnoreCase("SQL")) {
if(episodio.isVisto()){
mBoton.setBackgroundResource(R.drawable.ojoabierto);
}else{
mBoton.setBackgroundResource(R.drawable.ojocerrado);
}
mBoton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (episodio.isVisto()) {
//mBoton.setBackgroundResource(R.drawable.ojoabierto);
DBHelper mydb = new DBHelper(v.getContext());
mydb.CancelVerEpisodio(episodio.getIdEpisodio());
v.setBackgroundResource(R.drawable.ojocerrado);
episodio.setVisto(false);
} else//else
{
//mBoton.setBackgroundResource(R.drawable.ojocerrado);
DBHelper mydb = new DBHelper(v.getContext());
mydb.VerEpisodio(episodio.getIdEpisodio());
mBoton.setBackgroundResource(R.drawable.ojoabierto);
episodio.setVisto(true);
}
}
});
}
else
{
mBoton.setVisibility(View.INVISIBLE);
}
in your fist activity do the loading inside OnResume(). so that when you comeback to the activity . onResume() method will be first called and you will get the updated data. This is when you have all your other block codes functioning well but you have problem with refreshing your page.
move your loading method from onCreate() to onResume() in the first activity

Two shared preferences in the same app

My app has got two activities. In both activities there's an EditText and a Button. You write a number inside and then, after pressing the button, the number is displayed via TextView. But the number in the activity A is different from the number in the activity B, and I want the two numbers to be saved.
In order to do that, I'm using getSharedPreferences, specifying a string name for each one:
Activity A:
EditText mark1;
public static final String Mark1 = "mark1Key";
TextView marksem1;
public static final String MarkSem1 = "marksem1Key";
Button calcsem1;
double mark1calc=0;
public static final String MyPREFERENCES = "MyPrefsA" ;
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.etsam_gfa_layout);
initControls();
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
mark1 = (EditText) findViewById(R.id.mark1);
if (sharedpreferences.contains(Mark1))
{
mark1.setText(sharedpreferences.getString(Mark1, ""));
}
marksem1 = (TextView) findViewById(R.id.total1calc);
if (sharedpreferences.contains(MarkSem1))
{
marksem1.setText(sharedpreferences.getString(MarkSem1, ""));
}
public static Double safeParse(String input) {
try {
return Double.parseDouble(input);
} catch (NumberFormatException e) {
return 0d;
}
}
private void initControls() {
mark1=(EditText)findViewById(R.id.mark1);
marksem1=(TextView)findViewById(R.id.total1calc);
calcsem1=(Button)findViewById(R.id.total1);
calcsem1.setOnClickListener(new Button.OnClickListener()
{public void onClick
(View v) {calcsem1();}
private void calcsem1() {
mark1calc=safeParse(mark1.getText().toString());
totalsem1=(6*mark1calc);
marksem1.setText(Double.toString(totalsem1));
marksem1.setText(String.format("%.2f", totalsem1));
}});
public void run1(View view){
Editor editor = sharedpreferences.edit();
String mark1string = mark1.getText().toString();
String marksem1string = marksem1.getText().toString();
editor.putString(Mark1, mark1string);
editor.putString(MarkSem1, marksem1string);
editor.commit();
}
}
And the same thing with the activity B, but using public static final String MyPREFERENCES = "MyPrefsB";
The result is that Activity A does de work fine, but activity B, when I exit the app and enter again, has the EditText empty (it has not save anything).
Any ideas about this? Thank you so much!

How to extract text from pdf document using MuPDF in Android

I am trying to extract text from a PDF file using MuPDF library in Android platform.
Is it possible to extract text within a rectangle specified by coordinates (left, top, right, bottom)?
Note: I didn't compile the library from source. I am using compiled libraries which is distributed in https://github.com/libreliodev/android.
yeah sure
here is the way you can do.
1.GeneratedText activity
public class GeneratedText extends Activity {
private Button close;
private Button clear;
private TextView tv;
private String data;
String text = "";
Intent i;
Context mContext;
// MuPDFPageView pdfview = new MuPDFPageView(mContext, null, null);
private EditText edit;
private Button undo;
public static GeneratedText screen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_generated_text);
close = (Button)findViewById(R.id.close);
clear = (Button)findViewById(R.id.clear);
tv = (TextView)findViewById(R.id.text1);
edit = (EditText)findViewById(R.id.edit);
undo = (Button)findViewById(R.id.undo);
undo.setEnabled(false);
i = getIntent();
data = i.getStringExtra("data");
tv.setText(data);
String mypattern = "Name and address of the Employee \n";
Pattern p = Pattern.compile(mypattern,Pattern.DOTALL);
if(data.matches(mypattern))
{
System.out.println("Start Printing name");
}
else
//do nothing
edit.setText(data);
System.out.println("hello user "+"/n"+"user1"+ "\n"+ "user2");
SharedPreferences pref = getSharedPreferences("key", 0);
SharedPreferences.Editor editor = pref.edit();
editor.putString("text", data);
editor.commit();
clear.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
tv.setText("");
edit.setText("");
undo.setEnabled(true);
}
});
close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
undo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String value = "";
SharedPreferences pref = getSharedPreferences("key", 0);
value = pref.getString("text", value);
edit.setText(value);
tv.setText(value);
undo.setEnabled(false);
}
});
}
}
1. now in mupdfactivity write this
public void Showtext( )
{
destroyAlertWaiter();
core.stopAlerts();
MuPDFPageView pdfview = new MuPDFPageView(MuPDFActivity.this, core, null);
String data = "";
pdfview.setFocusable(true);
data = pdfview.getSelectedText();
Intent i = new Intent(getApplicationContext(),GeneratedText.class);
i.putExtra("data",data);
startActivity(i);
}
call Showtext in OnAcceptButtonClick
and you will get your text.
Yes it is possible to extract text from PDF document with the help of MuPDF library. There is method called text() in mupdf.c which is defined in MuPDFCore.java which returns the text of the page. You need to call that method by page wise.
Steps:
1. gotopage(pagenumber)
2. text()

Class variables in OnClickListener

I have a separate class for my OnClickListeners. I would like to add items to an arraylist when i click a button, and remove them when I click a 2nd time. I have the framework here:
public void onClick(View v) {
Button button = (Button)v;
if(isClicked) {
button.setText("Enabled");
Log.v("Spirit: ", v.getTag() + "");
spirits_list.add(v.getTag() + "");
isClicked = false;
} else {
button.setText("Disabled");
spirits_list.remove(v.getId()-1);
isClicked = true;
}
}
I also have an ArrayList initialized at the top, but every time I click a button it reinitializes the ArrayList. How can I get around this? Also, I need to be able to save the ArrayList to SharedPreferences - how can I do this from my OnClickListener?
Since you use your own class, you can pass all the goodness around in class members:
class MyListener implements View.OnClickListener {
private ArrayList<Object> spirits_list;
private Context ctx;
public MyListener( Context ctx, ArrayList<Object> list ) {
super();
this.ctx = ctx;
this.spirits_list = list;
}
public void onClick(View v) {
Button button = (Button)v;
if(isClicked) {
button.setText("Enabled");
Log.v("Spirit: ", v.getTag() + "");
this.spirits_list.add(v.getTag() + "");
isClicked = false;
} else {
button.setText("Disabled");
this.spirits_list.remove(v.getId()-1);
isClicked = true;
}
}
}
The context will allow you to access SharedPrefs as well. You can then invoke this bit as follows:
view.setOnClickListener( new MyListener( this, spirits_list ) );

Trouble converting an editable to a string (username/password test)

I'm trying to create a simple username/password login screen. I have the layout done, and right now, I'm trying to set it so when the username (EditText) == "crete", then it should do something. Here is my code...:
public class Login extends Activity {
public static EditText username, password;
public Button loginbutton;
boolean accessgranted;
public String dbu, dbp, user1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
username = (EditText) this.findViewById(R.id.username);
password = (EditText) this.findViewById(R.id.password);
loginbutton = (Button) this.findViewById(R.id.loginbutton);
user1 = "crete";
loginbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try{
dbu = (username.getText()).toString();
}
finally{
if (dbu == user1){
username.setText("SUCCESS");
}
}
}
});
}
}
this, sadly, doesn't work. It correctly converts it to a string (i think) because when I tested this code out :
loginbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try{
dbu = (username.getText()).toString();
}
finally{
username.setText("done" + dbu);
}
}
}
});
It correctly enters what you entered into the EditText, plus the word "done".
There seems to be a problem with creating if-then statements??
You test for String equality with the method .equals("String").
With == you are testing if the references to the objects are equal.
Try using equalsIgnoreCase(String) instead of the == comparator.
Like this: dbu.equalsIgnoreCase(user1)
dub and user1 are two separate String objects. You're comparing them like this: dbu == user1. This will always return false. Instead, replace it with dbu.equals(user1).

Categories

Resources