I am building an android app which displaying a specific pdf through https://github.com/barteksc/AndroidPdfViewer with lots of pages, and now i was just implementing a method to re-open the pdf from the last opened page of the user.
I am using SharedPreferences to store the current page, and then after reloading the app, the app will re-open the pdf where user left.
Here is my Shared Preferences method to store and retrieve the data
private void storepreferences () {
PDFView pdfView = findViewById(R.id.pdfView);
savedpage=pdfView.getCurrentPage();
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("key_name2", savedpage);
editor.apply();
}
private void getpreferences () {
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
pageNumber = pref.getInt("key_name2", 0); // getting Integer
}
And then i am using onCreate
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
storepreferences();
getpreferences();
Also for a test i am displaying the
TextView txt = findViewById(R.id.textView2);
txt.setText(String.valueOf(pageNumber));
But Still i am getting the default value, What i am doing wrong can anyone tell me?
Finally I achieved this, I was using (storepreferences) on OnCreate before but now On I am using at BackPressed
@Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
storepreferences();
super.onBackPressed();
}
}
After that I am retrieving saved data on OnCreate
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getpreferences();
}
I am using the above technique because I thought It is actually not storing my data, because When i use Toast to display the current Page, it was showing exactly the page number where user is
public void pagestorebutton (){
PDFView pdfView = findViewById(R.id.pdfView);
savedpage = pdfView.getCurrentPage();
Toast myToast = Toast.makeText(this,(String.valueOf(savedpage) ), Toast.LENGTH_SHORT);
myToast.show();
storepreferences();
}
And in onCreate i am using above function after clicking a Floating Button
FloatingActionButton fab4 = findViewById(R.id.fab4);
fab4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
pagestorebutton();
}
});
Is my Method is achieving my Goal through right path, or is there something more to do??