How to read Sharedpreference value from another activity - java

I make two activity first is timer.java activity which is an countdown activity and second activity is SaveRestTime.java in this activity user input number value in edittext and user will save it i use shared preference in this activity now I want which value user save in SaveRestTime.java class is automatically make value of countdown if user not save any value then default value is 30 sec please help me i am confuse how to read value from another activity
here is timer.java code
package com.cinegoes.www.daily10exercise;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import com.cinegoes.www.daily10exercise.SaveRestTime;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.util.concurrent.TimeUnit;
import static com.cinegoes.www.daily10exercise.SaveRestTime.mypreference;
/**
* Created by ever on 7/25/2017.
*/
public class timer extends Activity implements View.OnClickListener {
private CountDownTimer countDownTimer;
private boolean timerStarted = false;
private Button buttonStart;
public TextView textView;
private ProgressBar progressBarCircle;
private final long startTime = 30 * 1000;
private final long interval = 1 * 1000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.timer);
buttonStart = (Button) this.findViewById(R.id.button);
progressBarCircle = (ProgressBar) findViewById(R.id.progressBarCircle);
buttonStart.setOnClickListener(this);
textView = (TextView) this.findViewById(R.id.textView);
countDownTimer = new CountDownTimerActivity(startTime, interval);
textView.setText(textView.getText() + String.valueOf(startTime/1000));
}
#Override
protected void onStart() {
super.onStart();
countDownTimer.start();
timerStarted = true;
setProgressBarValues();
}
#Override
public void onClick(View v) {
finish();
}
public class CountDownTimerActivity extends CountDownTimer {
public CountDownTimerActivity(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
textView.setText(msTimeFormatter(startTime));
textView.setText("Time's up!");
setProgressBarValues();
finish();
}
#Override
public void onTick(long millisUntilFinished) {
textView.setText(msTimeFormatter(millisUntilFinished));
progressBarCircle.setProgress((int) (millisUntilFinished / 1000));
}
}
private void setProgressBarValues() {
progressBarCircle.setMax((int) startTime / 1000);
progressBarCircle.setProgress((int) startTime / 1000);
}
private String msTimeFormatter(long milliSeconds) {
String ms = String.format("%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(milliSeconds) -
TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(milliSeconds)),
TimeUnit.MILLISECONDS.toSeconds(milliSeconds) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(milliSeconds)));
return ms;
}
}
here is my SaveRestTime.java code
package com.cinegoes.www.daily10exercise;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
public class SaveRestTime extends Activity {
SharedPreferences sharedpreferences;
TextView name;
public static final String mypreference = "mypref";
public static final String Name = "nameKey";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.saveresttime);
name = (TextView) findViewById(R.id.etName);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Name)) {
name.setText(sharedpreferences.getString(Name, ""));
}
}
public void Save(View view) {
String n = name.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.commit();
}
public void Get(View view) {
name = (TextView) findViewById(R.id.etName);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Name))
{name.setText(sharedpreferences.getString(Name, ""));
}
}
}

SharedPreferences prefs = this.getSharedPreferences("myPref", Context.MODE_PRIVATE);
String lanSettings = prefs.getString("nameKey", null);

Related

How to save data in SharedPreferences permanently

I have been making an app that will ask a name at the first start of my app and should display it afterwards but whenever I am trying to save either I am Having a NullPointerExceptionor the name
display is empty.
This is my MainActivity
package com.example.sas;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity implements namedialog.ExampleDialogListenerName {
private ImageView imageView;
public static final int IMAGE_PICK_CODE = 1000;
private SharedPreferences prefs;
public static final int PERMISSION_CODE = 1001;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences preferences = getSharedPreferences("preferences",MODE_PRIVATE);
boolean firststart = preferences.getBoolean("firstStart",true);
if (firststart) {
OpenNameDialog();
}else {
savename();
}
TextView dateview = findViewById(R.id.date);
Calendar calendar = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-YYYY");
String date = dateFormat.format(calendar.getTime());
dateview.setText(date);
imageView = findViewById(R.id.selfpicture);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE ) == PackageManager.PERMISSION_DENIED){
String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE};
requestPermissions(permissions,PERMISSION_CODE);
}else {
pickImageFromGallery();
}
}else {
pickImageFromGallery();
}
}
});
}
private void OpenNameDialog(){
namedialog namedialog = new namedialog();
namedialog.show(getSupportFragmentManager(),"name dialog");
SharedPreferences preferences = getSharedPreferences("preferences",MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("firstStart",false);
editor.apply();
}
#Override
public void ApplyNameDialog(String name) {
prefs = getSharedPreferences("prefs",MODE_PRIVATE);
final SharedPreferences.Editor editor = prefs.edit();
editor.putString("susanth",name);
}
public void savename(){
String names = prefs.getString("susanth","");
TextView display = findViewById(R.id.namename);
display.setText(names);
}
public void pickImageFromGallery(){
Intent intent1 = new Intent(Intent.ACTION_PICK);
intent1.setType("image/*");
startActivityForResult(intent1,IMAGE_PICK_CODE);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case PERMISSION_CODE:{
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
pickImageFromGallery();
}else {
Toast.makeText(getApplicationContext(),"Permission Denied",Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == IMAGE_PICK_CODE) {
imageView.setImageURI(data.getData());
}
}
}
This is my namedialog
package com.example.sas;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatDialogFragment;
import java.util.Objects;
public class namedialog extends AppCompatDialogFragment {
private EditText name ;
private ExampleDialogListenerName listener;
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = Objects.requireNonNull(getActivity()).getLayoutInflater();
View view = inflater.inflate(R.layout.namedialog,null);
builder.setView(view)
.setTitle("Welcome Fill your details")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
final String namef = name.getText().toString();
listener.ApplyNameDialog(namef);
}
});
name = view.findViewById(R.id.etname);
return builder.create();
}
#Override
public void onAttach(#NonNull Context context) {
context = getActivity();
super.onAttach(context);
try {
listener = (ExampleDialogListenerName) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()+
"must implement ExampleDialogListenerName");
}
}
public interface ExampleDialogListenerName{
void ApplyNameDialog (String name);
}
}
Can you tell me what should I use for storing the name permanently.
Please Help Me Fast Thank You :)
#Override
public void ApplyNameDialog(String name) {
prefs = getSharedPreferences("prefs",MODE_PRIVATE);
final SharedPreferences.Editor editor = prefs.edit();
editor.putString("susanth",name);
}
It seems like the string is never saved. You should call editor.commit() or editor.apply()

Why does my Database not exist in the Main-Activity, when I return back to MainActivity?

in the Mainclass Im creating a variable called mDatabase. In the Mainclass there is a button called Database. When I click on it, it opens a new Activity. Then it starts the onCreate-Method of the second class databasegrocery.
When the program executes the command:
mAdapter=new GroceryAdapter(this, activity.getAllItems());
(...) it returns back to Main-Activity to call the method getAllItems().
When im returning to this method, mDatabase is null (mDatabase was already declared and initialized, when the app started with the MainActivity), why?
As Im totally new to android programing its possible that Im trying something stupid,
so I appreciate your help.
(I read something about activity-lifecycles and I saw that the MainActivity is in Stop-Status, when the second Activity is active. So the data from MainActivity is not destroyed, right?)
If you need more information, tell me!
Thank you.
package com.example.grocerylist;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
public class MainActivity extends AppCompatActivity{
public SQLiteDatabase mDatabase;
private EditText mEditTextName;
private EditText mEditTextName2;
private EditText mEditTextName3;
private EditText mEditTextName4;
private EditText mEditTextName5;
private EditText mEditTextName6;
private EditText mEditTextName7;
private EditText mEditTextName8;
private EditText mEditTextName9;
Button buttonIncrease;
Button buttonDecrease;
Button buttonAdd;
Button buttonDatabase;
public databasegrocery database;
Intent IntentDatabase;
private TextView mTextViewAmount;
private int mAmount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GroceryDBHelper dbHelper = new GroceryDBHelper(this);
mDatabase = dbHelper.getWritableDatabase();
mEditTextName = findViewById(R.id.edittext_name);
mTextViewAmount = findViewById(R.id.textview_amount);
mEditTextName2=findViewById(R.id.edittext_name2);
mEditTextName3=findViewById(R.id.edittext_name3);
mEditTextName4=findViewById(R.id.edittext_name4);
mEditTextName5=findViewById(R.id.edittext_name5);
mEditTextName6=findViewById(R.id.edittext_name6);
mEditTextName7=findViewById(R.id.edittext_name7);
mEditTextName8=findViewById(R.id.edittext_name8);
mEditTextName9=findViewById(R.id.edittext_name9);
IntentDatabase=new Intent(MainActivity.this,databasegrocery.class);
buttonIncrease = findViewById(R.id.button_increase);
buttonDecrease = findViewById(R.id.button_decrease);
buttonAdd = findViewById(R.id.button_add);
buttonDatabase=findViewById(R.id.buttonDatabase);
buttonDatabase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(IntentDatabase);
}
});
buttonIncrease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
increase();
}
});
buttonDecrease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
decrease();
}
});
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addItem();
}
});
}
private void increase() {
mAmount++;
mTextViewAmount.setText(String.valueOf(mAmount));
}
private void decrease() {
if (mAmount > 0) {
mAmount--;
mTextViewAmount.setText(String.valueOf(mAmount));
}
}
private void addItem() {
if (mEditTextName.getText().toString().trim().length() == 0 || mAmount == 0) {
return;
}
String name = mEditTextName.getText().toString();
String mkcal1 = mEditTextName2.getText().toString();
String mkcal2=mEditTextName3.getText().toString();
String mFett=mEditTextName4.getText().toString();
String mDavongesaettigtefettsaueren=mEditTextName5.getText().toString();
String mKohlenhydrate=mEditTextName6.getText().toString();
String mZucker=mEditTextName7.getText().toString();
String mEiweiss=mEditTextName8.getText().toString();
String mSalz=mEditTextName9.getText().toString();
//___________________________________________________________________
ContentValues cv = new ContentValues();
cv.put(GroceryContract.GroceryEntry.COLUMN_NAME, name);
cv.put(GroceryContract.GroceryEntry.COLUMN_AMOUNT, mAmount);
//----------------------------------------------------------------------------------------
cv.put(GroceryContract.GroceryEntry.COLUMN_KCAL1, mkcal1);
cv.put(GroceryContract.GroceryEntry.COLUMN_KCAL2, mkcal2);
cv.put(GroceryContract.GroceryEntry.COLUMN_FETT, mFett);
cv.put(GroceryContract.GroceryEntry.COLUMN_DAVONGESAETTIGTEFETTSAEUREN, mDavongesaettigtefettsaueren);
cv.put(GroceryContract.GroceryEntry.COLUMN_Kohlenhydrate, mKohlenhydrate);
cv.put(GroceryContract.GroceryEntry.COLUMN_Zucker, mZucker);
cv.put(GroceryContract.GroceryEntry.COLUMN_EIWEIS, mEiweiss);
cv.put(GroceryContract.GroceryEntry.COLUMN_SALZ, mSalz);
//------------------------------------------------------------------------------------------
mDatabase.insert(GroceryContract.GroceryEntry.TABLE_NAME, null, cv);
databasegrocery.mAdapter.swapCursor(getAllItems());
mEditTextName.getText().clear();
mEditTextName2.getText().clear();
mEditTextName3.getText().clear();
mEditTextName4.getText().clear();
mEditTextName5.getText().clear();
mEditTextName6.getText().clear();
mEditTextName7.getText().clear();
mEditTextName8.getText().clear();
mEditTextName9.getText().clear();
}
public Cursor getAllItems() {
return mDatabase.query(GroceryContract.GroceryEntry.TABLE_NAME, null, null, null, null, null, GroceryContract.GroceryEntry.COLUMN_TIMESTAMP + " ASC");
}
}
package com.example.grocerylist;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
public class databasegrocery extends AppCompatActivity {
public static GroceryAdapter mAdapter;
public MainActivity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.databasegrocery);
activity=new MainActivity();
RecyclerView recyclerView = findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new GroceryAdapter(this, activity.getAllItems());
recyclerView.setAdapter(mAdapter);
}
}

how can i sort firebase data according to their ratings after getting title of value vikas?

Means I want to sort my firebaserecycleradapter according to highest no of ratings first after applying query on data having title with value "vikas"
This is my code:
package com.onlinetuto;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.onlinetuto.model.blog;
import static com.onlinetuto.EmptyActivity.EXTRA_POST_KEY;
public class GetLocation extends AppCompatActivity {
private static final String TAG = "MainActivity";
private RecyclerView re;
private DatabaseReference d,dref;
private FirebaseAuth mauth;
FirebaseRecyclerAdapter<blog,BlogViewholder> firebaseRecyclerAdapter;
DatabaseReference users, comments;
ProgressBar progressBar;
String locname;
SharedPreferences sharedPreferences;
LinearLayoutManager linearLayoutManager;
AutoCompleteTextView autoCompleteTextView;
Intent intent;
Button button;
Long code;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_location);
intent=getIntent();
if(intent!=null)
{
code= intent.getLongExtra("queryname",110094);
}
Toast.makeText(this, code.toString(), Toast.LENGTH_SHORT).show();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mauth = FirebaseAuth.getInstance();
d = FirebaseDatabase.getInstance().getReference().child("Products");
users = FirebaseDatabase.getInstance().getReference().child("Users");
comments = FirebaseDatabase.getInstance().getReference().child("post-comments");
Query nm=d.orderByChild("pincode").equalTo(code);
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
progressBar.setVisibility(View.VISIBLE);
// mquery = dtop.orderByChild("title").equalTo("hul");
// mquery2 = dtop.orderByChild("likeCount").limitToFirst(100);
//for offline capabilities of database
// d3.keepSynced(true);
d.keepSynced(true);
// mdatabaselike.keepSynced(true);
re = (RecyclerView) findViewById(R.id.blog_list);
re.setHasFixedSize(true);
linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
re.setLayoutManager(linearLayoutManager);
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<blog, BlogViewholder>(
blog.class,
R.layout.blog_row,
BlogViewholder.class,
nm
) {
#Override
protected void populateViewHolder(final BlogViewholder viewHolder, final blog model, int position) {
final String post_key = getRef(position).getKey();
//for retrieving each post key getRef() method is used for this.
final DatabaseReference post_ref = getRef(position);
viewHolder.setTitle(model.getClassname());
viewHolder.setImage(getApplicationContext(), model.getImageone());
viewHolder.setReviews(model.getReviews());
viewHolder.setTypo(model.getType());
viewHolder.setNoofComments(model.getNoofreviews());
viewHolder.setratings(model.getNetrat());
viewHolder.setTextRating(model.getNoofreviews());
viewHolder.vi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent newIntent = new Intent(GetLocation.this, EmptyActivity.class);
newIntent.putExtra(EXTRA_POST_KEY, post_key);
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
// newIntent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(newIntent);
}
});
progressBar.setVisibility(View.GONE);
}
};
re.setAdapter(firebaseRecyclerAdapter);
}
private Boolean exit = false;
#Override
public void onBackPressed() {
if (exit) {
finish(); // finish activity
} else {
Toast toast=Toast.makeText(this, "Press Back again to exit", Toast.LENGTH_SHORT);
View view = toast.getView();
view.setBackgroundColor(getResources().getColor(R.color.toa));
TextView text = (TextView) view.findViewById(android.R.id.message);
text.setTextColor(getResources().getColor(R.color.blackm));
/*Here you can do anything with above textview like text.setTextColor(Color.parseColor("#000000"));*/
toast.show();
exit = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
exit = false;
}
}, 2 * 1000);
}
}
public static class BlogViewholder extends RecyclerView.ViewHolder {
View vi;
FirebaseAuth mauth;
EditText e1;
public BlogViewholder(View itemView) {
super(itemView);
vi = itemView;
mauth = FirebaseAuth.getInstance();
}
/* public void setImage(Context context,String image){
ImageView imageView=(ImageView)vi.findViewById(R.id.post_iamge);
Picasso.with(context).load(image).into(imageView);
}*/
public void setTitle(String classname) {
TextView textView = (TextView) vi.findViewById(R.id.textViewTitle);
textView.setText(classname);
}
public void setImage(Context context, String image){
ImageView imageView=(ImageView)vi.findViewById(R.id.imageView);
Glide.with(context).load(image).into(imageView);
}
public void setReviews(String reviews) {
TextView textView = (TextView) vi.findViewById(R.id.reviews);
textView.setText(reviews);
}
public void setTypo(String type) {
TextView textView = (TextView) vi.findViewById(R.id.type);
textView.setText(type);
}
public void setTextRating(long comme) {
TextView textView = (TextView) vi.findViewById(R.id.textViewRating);
textView.setText(comme + "");
}
public void setNoofComments(long comme) {
TextView textView = (TextView) vi.findViewById(R.id.reviews);
textView.setText(comme+" Reviews");
}
public void setratings(Long rat) {
RatingBar textView = (RatingBar) vi.findViewById(R.id.img);
Integer myNum=0;
if(rat==null)
myNum=0;
else
{
Integer integer=(int)(long)rat;
myNum=integer;
}
if(myNum>5)
{
myNum=myNum%5;
textView.setRating(myNum);
}
else
{
textView.setRating(myNum);
}
}
}
}
this is my code please help me.i want to sort query data according to their ratings before passing it to the firebase recycleradapter .how can i acheive that?
Product database reference one key data:-
i am using firebase realtime database here
I'm using this one to sort it by latest post.
#Override
public blog getItem(int position) {
return super.getItem(getItemCount() - (position + 1));
}

Getting error index out of bound exception in my recyclerview

I'm trying to get favourite items in favourite list from main list.When i click on favourite icon in mainlist, favouritelist get updating but when i remove any favourite from favouritelist and trying to add more favourites from mainlist i get error index out of bound exception
MainActivity
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends AppCompatActivity implements RecyclerViewClickListener{
RecyclerView simpleListView;
static Context ctx;
String diseaseList[];
SharedPreference sharedPreference;
DiseaseAdapter da;
List<String> newDiseaseList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ctx=this;
sharedPreference = new SharedPreference();
diseaseList= new String[]{"Abscess",
"Allergies",
"Amnesia",
"Anemia",
"Andropause",
"Angina",
"Weight Loss"};
Arrays.sort(diseaseList);
newDiseaseList = Arrays.asList(diseaseList);
simpleListView= (RecyclerView)findViewById(R.id.simpleListView);
LinearLayoutManager lm=new LinearLayoutManager(MainActivity.this);
simpleListView.setLayoutManager(lm);
/* DividerItemDecoration di=new DividerItemDecoration(MainActivity.this,lm.getOrientation());
simpleListView.addItemDecoration(di);*/
da=new DiseaseAdapter(newDiseaseList,ctx,this);
simpleListView.setAdapter(da);
simpleListView.setHasFixedSize(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_favorites:
Intent i=new Intent(this,Favourite.class);
this.startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
da.notifyDataSetChanged();
}
#Override
public void recyclerViewListClicked(View view, int position) {
ImageView button = (ImageView) view.findViewById(R.id.imgbtn_favorite);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(ctx, newDiseaseList.get(position));
Toast.makeText(ctx,
"add to favourites",
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.star_colour);
} else {
sharedPreference.removeFavorite(ctx, newDiseaseList.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.ic_action_name);
Toast.makeText(ctx,
"removed from favourites",
Toast.LENGTH_SHORT).show();
}
}
}
Favourite.java
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.Collections;
import java.util.List;
public class Favourite extends AppCompatActivity implements RecyclerViewClickListener {
RecyclerView favoriteList;
SharedPreference sharedPreference;
List<String> favorites;
DiseaseAdapter diseaseAdapter;
static Context ctx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favourite);
ctx=this;
sharedPreference = new SharedPreference();
favorites = sharedPreference.getFavorites(ctx);
Collections.sort(favorites);
favoriteList = (RecyclerView)findViewById(R.id.favListView);
LinearLayoutManager lm=new LinearLayoutManager(ctx);
favoriteList.setLayoutManager(lm);
favoriteList.setHasFixedSize(true);
if (favorites == null) {
showAlert(getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
} else {
if (favorites.size() == 0) {
showAlert(
getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
}
if (favorites != null) {
diseaseAdapter = new DiseaseAdapter(favorites,ctx,this);
favoriteList.setAdapter(diseaseAdapter);
}
}
}
public void showAlert(String title, String message) {
if (ctx != null) {
AlertDialog alertDialog = new AlertDialog.Builder(ctx)
.create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setCancelable(false);
// setting OK Button
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
// activity.finish();
getFragmentManager().popBackStackImmediate();
}
});
alertDialog.show();
}
}
#Override
public void recyclerViewListClicked(View view, int position) {
ImageView button = (ImageView) view
.findViewById(R.id.imgbtn_favorite);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(ctx,
favorites.get(position));
Toast.makeText(
ctx,
ctx.getResources().getString(
R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.star_colour);
} else {
sharedPreference.removeFavorite(ctx,
favorites.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.ic_action_name);
/* diseaseAdapter.remove(favorites
.get(position));*/
diseaseAdapter.remove(position);
Toast.makeText(
ctx,
ctx.getResources().getString(
R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
}
}
Adapter
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by admin on 12/4/2017.
*/
public class DiseaseAdapter extends RecyclerView.Adapter<DiseaseAdapter.DiseaseAdapterViewHolder> {
List <String> data;
Context ctx;
private static RecyclerViewClickListener itemListener;
SharedPreference sharedPreference;
DiseaseAdapter(List <String> data, Context ctx, RecyclerViewClickListener itemListener){
this.data=data;
this.ctx=ctx;
sharedPreference = new SharedPreference();
this.itemListener = itemListener;
notifyDataSetChanged();
}
#Override
public DiseaseAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater=LayoutInflater.from(parent.getContext());
View view= inflater.inflate(R.layout.activity_listview,parent,false);
return new DiseaseAdapterViewHolder(view);
}
#Override
public void onBindViewHolder(DiseaseAdapterViewHolder holder, int position) {
final String title=data.get(position);
holder.textView1.setText(title);
if (checkFavoriteItem(title)) {
holder.imageButton.setImageResource(R.drawable.star_colour);
holder.imageButton.setTag("red");
} else {
holder.imageButton.setImageResource(R.drawable.ic_action_name);
holder.imageButton.setTag("grey");
}
}
#Override
public int getItemCount() {
return data.size();
}
class DiseaseAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView textView1;
ImageView imageButton;
public DiseaseAdapterViewHolder(View itemView) {
super(itemView);
textView1=(TextView) itemView.findViewById(R.id.textView);
imageButton=(ImageView)itemView.findViewById(R.id.imgbtn_favorite);
imageButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
notifyDataSetChanged();
itemListener.recyclerViewListClicked(v, this.getLayoutPosition());
}
}
/*Checks whether a particular product exists in SharedPreferences*/
public boolean checkFavoriteItem(String checkProduct) {
boolean check = false;
List<String> favorites = sharedPreference.getFavorites(ctx);
if (favorites != null) {
for (String product : favorites) {
if (product.equals(checkProduct)) {
check = true;
break;
}
}
}
return check;
}
public void add(String product) {
data.add(product);
notifyDataSetChanged();
}
public void remove(int position) {
data.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, data.size());
notifyDataSetChanged();
}
}
SharedPreference
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import com.google.gson.Gson;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SharedPreference {
public static final String PREFS_NAME = "PRODUCT_APP";
public static final String FAVORITES = "Product_Favorite";
public SharedPreference() {
super();
}
// This four methods are used for maintaining favorites.
public void saveFavorites(Context context, List<String> favorites) {
SharedPreferences settings;
Editor editor;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
editor = settings.edit();
Gson gson = new Gson();
String jsonFavorites = gson.toJson(favorites);
editor.putString(FAVORITES, jsonFavorites);
editor.commit();
}
public void addFavorite(Context context, String product) {
List<String> favorites = getFavorites(context);
if (favorites == null)
favorites = new ArrayList<String>();
favorites.add(product);
saveFavorites(context, favorites);
}
public void removeFavorite(Context context, String product) {
List<String> favorites = getFavorites(context);
if (favorites != null) {
favorites.remove(product);
saveFavorites(context, favorites);
}
}
public ArrayList<String> getFavorites(Context context) {
SharedPreferences settings;
List<String> favorites ;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
Gson gson = new Gson();
String [] favoriteItems = (gson.fromJson(jsonFavorites,String [].class));
favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList<String>(favorites);
} else
return null;
return (ArrayList<String>) favorites;
}
}
This is an error that i'm getting
FATAL EXCEPTION: main
Process: com.example.admin.fav, PID: 10974
java.lang.IndexOutOfBoundsException: Invalid index 3, size is 3
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.example.admin.fav.Favourite.recyclerViewListClicked(Favourite.java:145)
at com.example.admin.fav.DiseaseAdapter$DiseaseAdapterViewHolder.onClick(DiseaseAdapter.java:90)
at android.view.View.performClick(View.java:5207)
at android.view.View$PerformClick.run(View.java:21168)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Problem in your listener. You are using same adapter class for both MainActivity recylerview & Favourite activity recylerview. After you go back from favourite activity to Mainactivity still your listener read from Favourite activity. Thats the issue.
Solution
Create Static field to hold listener value here am created in SharedPreference Class:
public class SharedPreference {
public static final String PREFS_NAME = "PRODUCT_APP";
public static final String FAVORITES = "Product_Favorite";
/*Added*/
private static RecyclerViewClickListener listener;
public RecyclerViewClickListener getListener() {
return listener;
}
public void setListener(RecyclerViewClickListener listener) {
SharedPreference.listener = listener;
}
/*Added*/
...
}
Add this code to MainActivity & Favourite Activity 'OnCreate' method
sharedPreference.setListener(this);
public class MainActivity extends AppCompatActivity implements RecyclerViewClickListener{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreference.setListener(this);
....
}
public class Favourite extends AppCompatActivity implements RecyclerViewClickListener{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favourite);
sharedPreference.setListener(this);
....
}
Change Adapter 'OnClick method' to
#Override
public void onClick(View v) {
notifyDataSetChanged();
itemListener = sharedPreference.getListener();
itemListener.recyclerViewListClicked(v, this.getLayoutPosition());
}
And Finally change in MainActivity 'resume' method
#Override
protected void onResume() {
super.onResume();
sharedPreference.setListener(this);
da.notifyDataSetChanged();
}
Hope it helps.!
In your DiseaseAdapterViewHolder change the onclick methode to,
#Override
public void onClick(View v) {
itemListener.recyclerViewListClicked(v, this.getLayoutPosition());
notifyDataSetChanged();
}

Access Shared Preferences Across Activities

I have a SharedPreference in this .java File; towards the bottom you can see I save the values to the SharedPreferences GB_PREFERENCES_BENCH, and GB_PREFERENCES_FLIES. How do I use these values in another activity? See the second code example for how I want to use it.
package com.creativecoders.gymbuddy;
import com.creativecoders.gymbuddy.R;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
public class Benchmark extends Activity {
public static final String GB_PREFERENCES = "Prefs";
public static final String GB_PREFERENCES_BENCH = "Bench";
public static final String GB_PREFERENCES_FLIES = "Flies";
SharedPreferences gBValues;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_benchmark);
gBValues = getSharedPreferences(GB_PREFERENCES, Context.MODE_PRIVATE);
}
public void onStart() {
super.onStart();
findViewById(R.id.button5).setOnClickListener(new handleButton5());
}
class handleButton5 implements OnClickListener {
public void onClick(View v) {
EditText editText1 = (EditText)findViewById(R.id.editText1);
String sWeight = editText1.getText().toString();
final double dWeight = Double.parseDouble(sWeight);
EditText editText2 = (EditText)findViewById(R.id.editText2);
String sPush = editText2.getText().toString();
final double dPush = Double.parseDouble(sPush);
EditText editText3 = (EditText)findViewById(R.id.editText3);
String sSit = editText3.getText().toString();
final double dSit = Double.parseDouble(sSit);
EditText editText4 = (EditText)findViewById(R.id.editText4);
String sPull = editText4.getText().toString();
final double dPull = Double.parseDouble(sPull);
double dBench = (((Math.floor(dWeight*.0664))*10)-10)+dPush;
double dFlies = (Math.floor(((Math.floor(dBench*.6)/10)*10)));
int iBench = (int)dBench;
int iFlies = (int)dFlies;
Editor editor1 = gBValues.edit();
editor1.putInt(GB_PREFERENCES_BENCH, iBench);
editor1.commit();
Editor editor2 = gBValues.edit();
editor2.putInt(GB_PREFERENCES_FLIES, iFlies);
editor2.commit();
}
}
}
Here is how I want to use it; (specifically in the on create method to set a TextView's text to the value in the SharePreference)
package com.creativecoders.gymbuddy;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
public class Upper100Start extends Activity {
public static final String GB_PREFERENCES = "Prefs";
public static final String GB_PREFERENCES_CURLS = "Curls";
SharedPreferences gBValues;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.upper100start);
if (gBValues.contains(GB_PREFERENCES_CURLS)){
TextView TextView2 = (TextView)findViewById(R.id.textView2);
TextView2.setText(gBValues.getString(GB_PREFERENCES_CURLS, ""));
}
}
public void onStart() {
super.onStart();
findViewById(R.id.button2).setOnClickListener(new handleButton2());
findViewById(R.id.button3).setOnClickListener(new handleButton3());
}
class handleButton2 implements OnClickListener {
public void onClick(View v) {
Intent intent = new Intent(Upper100Start.this, Upper101.class);
startActivity(intent);
}
}
class handleButton3 implements OnClickListener {
public void onClick(View v) {
Intent intent = new Intent(Upper100Start.this, Main.class);
startActivity(intent);
}
}
}
The shared preferences are accessible throughout your application, so you can read them from any activity in the application.
Storing a key/value pair in activity A:
SharedPreferences settings = getSharedPreferences("mysettings",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("mystring", "wahay");
editor.commit();
Reading this value from another activity:
SharedPreferences settings = getSharedPreferences("mysettings",
Context.MODE_PRIVATE);
String myString = settings.getString("mystring", "defaultvalue");
You can find more information at http://developer.android.com/guide/topics/data/data-storage.html#pref

Categories

Resources