Android Save spinner state in onCreate, and Activity onResume - java

I am currently facing 2 problems, the spinner state is not saving and when I am on the InformationActivity the spinner is reset. I have used the information on other posts but it doesnt seem to help.
At the moment I cant use finish(); in my onBackPressed(); on InformationActivity because it goes back to the ScannerView as I am Implementing the ZXing library. How could I save the Spinner state and also stop the program from crashing onBackPressed when I am on HomeActivity.
Thanks.
HomeActivity:
public class HomeActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
private FirebaseAuth firebaseAuth;
private Button buttonLogout;
private ZXingScannerView scannerView;
private final int permission_code = 1;
String [] selectedProfile;
Spinner spinner;
ArrayAdapter<CharSequence> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
firebaseAuth = FirebaseAuth.getInstance();
if(firebaseAuth.getCurrentUser() == null){
finish();
startActivity(new Intent(this, MainActivity.class));
}
FirebaseUser user = firebaseAuth.getCurrentUser();
if (savedInstanceState != null) {
spinner.setSelection(savedInstanceState.getInt("yourSpinner", 0));
// do this for each of your text views
}
else {
//android spinner to select profile
spinner = (Spinner) findViewById(R.id.spinnerProfiles);
adapter = ArrayAdapter.createFromResource(this, R.array.restrictions, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_list_item_1);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
}
}
//opens camera when button is pressed
public void scanBarcode(View view) {
//check if user given app camera permissions
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, permission_code);
}
//opens camera
scannerView = new ZXingScannerView(this);
scannerView.setResultHandler(new ZXingScannerResultHandler());
//stops camera and scannerview
setContentView(scannerView);
scannerView.startCamera();
}
//selects an item from the spinner and passes it to InformationActivity
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
Toast.makeText(getBaseContext(), item + " Selected", Toast.LENGTH_SHORT).show();
switch (position){
case 0:
selectedProfile = getResources().getStringArray(R.array.Wheat);
break;
case 1:
selectedProfile = getResources().getStringArray(R.array.Crustaceans);
break;
case 2:
selectedProfile = getResources().getStringArray(R.array.Eggs);
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
//stops camera and outputs barcode result to a Toast
class ZXingScannerResultHandler implements ZXingScannerView.ResultHandler {
#Override
public void handleResult(Result result) {
String resultBarcode = result.getText();
Intent intent = new Intent(getApplicationContext(), InformationActivity.class);
intent.putExtra("BarcodeString", resultBarcode.toString());
intent.putExtra("ProfileArray", selectedProfile);
startActivity(intent);
scannerView.stopCamera();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == permission_code) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission Granted", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_LONG).show();
}
}
//go back to home after permissions accepted
Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
startActivity(intent);
scannerView.stopCamera();
}
//goes back to homepage when back button is pressed
#Override
public void onBackPressed() {
setContentView(R.layout.activity_home);
scannerView.stopCamera();
}
//stops the camera on pause
#Override
public void onPause(){
super.onPause();
scannerView.stopCamera();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("yourSpinner", spinner.getSelectedItemPosition());
}
}
InformationActivity:
public class InformationActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_information);
TextView barcodeView = (TextView) findViewById(R.id.tvBarcode);
barcodeView.setText(getIntent().getExtras().getString("BarcodeString"));
TextView profileView = (TextView) findViewById(R.id.tvProfile);
String[] selectedProfile = getIntent().getStringArrayExtra("ProfileArray");
profileView.setText(selectedProfile[0]);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
startActivity(intent);
}
}

To Save Spinner posotion in sharedpreference :
int userChoice = spinner.getSelectedItemPosition();
SharedPreferences sharedPref = getSharedPreferences("FileName",0);
SharedPreferences.Editor prefEditor = sharedPref.edit();
prefEditor.putInt("userChoiceSpinner",usersChoice);
prefEditor.commit();
Get Data from sharedpreferences :
SharedPreferences sharedPref = getSharedPreferences("FileName",MODE_PRIVATE);
int spinnerValue = sharedPref.getInt("userChoiceSpinner",-1);
if(spinnerValue != -1) {
// set the selected value of the spinner
spinner.setSelection(spinnerValue);
}
Also look into this :
One Another Example to save : https://stackoverflow.com/a/29527936/8448886
SharedPreference Tutorial :https://www.journaldev.com/9412/android-shared-preferences-example-tutorial

when you select any item from spinner at that time get that selected item and store that position and after when you come back to activity load spinner first, compare that item with array items and get position of that item then set that position to spinner i think this way you get exact selection of that item into spinner.

Related

How to make sure that the data in the portrait mode shows the data exactly the same position/index when you switch to the landscape mode?

I'm currently working with an app which has 2 activities: ListActivity and EditActivity. The purpose of ListActivity is to implement a recyclerview that contains a picture, word, description of the word and rating. Picture, name and description datas are already known and rating can be set by the help of a seekbar at EditActivity. I've already handled the interaction between those 2 activities and can show rating in ListActivity after it has been set at EditActivity.
My goal is now to implement a simple onSaveInstanceState, so I can save state and don't lose any data, when I switch to landscape. I tried to do that, but for some reason the ListActivity "grabs" the latest rating value that I've set and show the following value at position/index 0.
Why might/could be an issue here? I can't really see the problem.
ListActivity:
public class ListActivity extends AppCompatActivity implements WordAdapter.OnItemListener {
private ArrayList<WordItem> mWords = new ArrayList<>();
private WordAdapter mAdapter;
private static final int REQUEST_CODE_DETAILS_ACTIVITY = 1;
Button exitBtn;
TextView txtRating;
String rating, note;
int wordClickedIndex = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
setUpViews();
if (savedInstanceState != null) {
rating = savedInstanceState.getString(getString(R.string.key_rating));
WordItem i = mWords.get(wordClickedIndex);
i.setRating(rating);
// mWords.set(wordClickedIndex, i);
// mAdapter.updateData(mWords);
// mAdapter.notifyDataSetChanged();
}
}
public void setUpViews() {
RecyclerView mRecyclerView = findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
mAdapter = new WordAdapter(mWords, this);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
}
#Override
public void onItemClick(int position) {
Intent intent = new Intent(this, DetailsActivity.class);
WordItem clickedWord = mWords.get(position);
wordClickedIndex = position;
intent.putExtra("resId", clickedWord.getImageResource());
intent.putExtra(getString(R.string.key_name), clickedWord.getWord());
intent.putExtra(getString(R.string.key_pronouncing), clickedWord.getPronouncing());
intent.putExtra(getString(R.string.key_description), clickedWord.getDescription());
intent.putExtra(getString(R.string.key_rating), clickedWord.getRating());
intent.putExtra(getString(R.string.key_notes), clickedWord.getNotes());
startActivityForResult(intent, REQUEST_CODE_DETAILS_ACTIVITY);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_DETAILS_ACTIVITY) {
if (resultCode == RESULT_OK) {
if (data != null) {
rating = data.getStringExtra(getString(R.string.key_rating));
note = data.getStringExtra(getString(R.string.key_notes));
WordItem i = mWords.get(wordClickedIndex);
i.setRating(rating);
i.setNotes(note);
mWords.set(wordClickedIndex, i);
mAdapter.updateData(mWords);
mAdapter.notifyDataSetChanged();
}
}
}
}
#Override
protected void onSaveInstanceState(#NonNull Bundle outState) {
// WordItem i = mWords.get(wordClickedIndex);
outState.putString(getString(R.string.key_rating), rating);
super.onSaveInstanceState(outState);
}
}

How can I stop the 'jumping effect' when opening an activity?

I have more than three activities and these other activities transition so well but one activity which I have included the code for below appear to be jumping every time I navigate to it.
I have overridden the animation class but the jump still persists.How can I go about it? Is my Ui thread overloaded?
public class ListActivity extends AppCompatActivity implements
RecyclerViewAdapter.OnItemClickListener {
RecyclerViewAdapter recyclerViewAdapter;
RecyclerView recyclerView;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference dbRef = db.collection("Archives");
Context context;
FloatingActionButton fab;
Item clickedItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
recyclerView = findViewById(R.id.recyclerView);
fab = findViewById(R.id.fab);
Toolbar toolbar = findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
});
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ListActivity.this,
EnterDataActivity.class);
startActivity(intent);
}
});
setUpAdapter();
}
private void setUpAdapter() {
Query query = dbRef.orderBy("fname", Query.Direction.DESCENDING);
FirestoreRecyclerOptions<Item> options = new
FirestoreRecyclerOptions.Builder<Item>()
.setQuery(query, Item.class)
.build();
recyclerViewAdapter = new RecyclerViewAdapter(options,
ListActivity.this);
recyclerViewAdapter.notifyDataSetChanged();
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
recyclerView.setAdapter(recyclerViewAdapter);
recyclerViewAdapter.setOnItemClickListener(ListActivity.this);
}
#Override
public void onStart() {
super.onStart();
recyclerViewAdapter.startListening();
}
#Override
public void onStop() {
super.onStop();
recyclerViewAdapter.stopListening();
}
#Override public void onItemClick(DocumentSnapshot documentSnapshot, int
position) {
clickedItem = documentSnapshot.toObject(Item.class);
clickedItem.setId((documentSnapshot.getId()));
Intent intent = new Intent(ListActivity.this, DetailActivity.class);
intent.putExtra(First_Name, clickedItem.getFname());
intent.putExtra(Middle_Name, clickedItem.getMname());
intent.putExtra(Sur_Name, clickedItem.getSname());
intent.putExtra(Email, clickedItem.getEmail());
intent.putExtra(phone, clickedItem.getPhone());
intent.putExtra(city, clickedItem.getCity());
intent.putExtra(parents_Name, clickedItem.getParentsName());
intent.putExtra(parents_Phone, clickedItem.getParentsContact());
intent.putExtra(dob, clickedItem.getDob());
intent.putExtra(emergency, clickedItem.getEmergency());
intent.putExtra(profile_Picture, clickedItem.getProfilePicture());
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
startActivityForResult(intent, 45);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if ((requestCode == 45 && resultCode == RESULT_OK && data != null)) {
String fname = data.getStringExtra(First_Name);
String mname = data.getStringExtra(Middle_Name);
String sname = data.getStringExtra(Sur_Name);
String email = data.getStringExtra(Email);
String Phone = data.getStringExtra(phone);
String City = data.getStringExtra(city);
String pname = data.getStringExtra(parents_Name);
String pphone = data.getStringExtra(parents_Phone);
String Dob = data.getStringExtra(dob);
String Emergency = data.getStringExtra(emergency);
String profile = data.getStringExtra(profile_Picture);
Item items = new Item(fname, mname, sname, email, Phone, City,
pname, pphone, Dob, Emergency, profile);
db.collection("Archives").document(clickedItem.getId())
.set(items).addOnSuccessListener(new
OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(ListActivity.this, "Updated Successfully",
Toast.LENGTH_LONG).show();
}
});
}
}
}
Activity documentation of overridePendingTransition says:
Call immediately after one of the flavors of startActivity(android.content.Intent) or finish() to specify an explicit transition animation to perform next.
So calling overridePendingTransition in any other places at least does nothing. Remove such calls like in ListActivity#onCreate after setContentView and place them next line to startActivity or startActivityForResult.

Keep the data save in sharedPreference although pressed back button - Android Studio

I have some problem as I mention in my question. I have two activity, Activity A and Activity B. When I Enter some data in Activity A, then I press next button, it will redirect to Activity B. At Activity B, I also enter some data. When I press back button, the data at Activity A is display as I entered before. When I press next button, the data that I entered at Activity B is missing. Below is my SharedPreferences code.
Activity A:
public class NewSuggestion extends AppCompatActivity {
private EditText etYear, etMonth, etTitle, etOwnValue;
private RadioGroup rgSuggestWill;
private RadioButton radioButton;
private Button btnNext;
ArrayAdapter<CharSequence> adapter;
private Spinner spReviewer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_suggestion);
final ActionBar abar = getSupportActionBar();
View viewActionBar = getLayoutInflater().inflate(R.layout.activity_new_suggestion, null);
ActionBar.LayoutParams params = new ActionBar.LayoutParams(//Center the textview in the ActionBar !
ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.MATCH_PARENT,
Gravity.CENTER);
TextView tvTitle = viewActionBar.findViewById(R.id.title);
tvTitle.setText("NEW SUGGESTION");
abar.setCustomView(viewActionBar, params);
abar.setDisplayShowCustomEnabled(true);
abar.setDisplayShowTitleEnabled(false);
//abar.setDisplayHomeAsUpEnabled(true);
abar.setHomeButtonEnabled(true);
etTitle = findViewById(R.id.etTitle);
etYear = findViewById(R.id.etYear);
etMonth = findViewById(R.id.etMonth);
rgSuggestWill =findViewById(R.id.rgSuggestWill);
final Calendar c = Calendar.getInstance();
String mm = c.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.US);
int yy = c.get(Calendar.YEAR);
etYear.setText(new StringBuilder().append(yy));
etMonth.setText(new StringBuilder().append(mm));
spReviewer = findViewById(R.id.spReviewer);
adapter = ArrayAdapter.createFromResource(this,R.array.reviewer,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spReviewer.setAdapter(adapter);
spReviewer.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
btnNext = findViewById(R.id.btnNext);
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPref = getSharedPreferences("MyData",MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("title",etTitle.getText().toString());
editor.putString("year",etYear.getText().toString());
editor.putString("month",etMonth.getText().toString());
// get selected radio button from radioGroup
int selectedId = rgSuggestWill.getCheckedRadioButtonId();
// find the radiobutton by returned id
radioButton = findViewById(selectedId);
editor.putString("suggestionwill",radioButton.getText().toString());
if (spReviewer.getSelectedItem().toString().equals("Please choose")){
AlertDialog alertDialog = new AlertDialog.Builder(NewSuggestion.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Please choose your reviewer");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}else{
editor.putString("reviewer",spReviewer.getSelectedItem().toString());
Intent intent = new Intent(NewSuggestion.this,NewSuggestion2.class);
startActivity(intent);
}
editor.apply();
}
});
}
#Override
public void onBackPressed() {
Intent intent = new Intent(NewSuggestion.this, DashboardApp.class);
startActivity(intent);
}
}
Activity B:
public class NewSuggestion2 extends AppCompatActivity {
private EditText etPresent, etDetails, etBenefit;
private ImageView imgAttach,btnCamera,btnGallery;
private Button btnNext,btnClear;
private Intent intent;
private Bitmap bitmap;
private int REQUEST_CODE = 1;
public static final int RequestPermissionCode = 1 ;
public static final String DEFAULT = "N/A";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_suggestion2);
final ActionBar abar = getSupportActionBar();
View viewActionBar = getLayoutInflater().inflate(R.layout.activity_new_suggestion, null);
ActionBar.LayoutParams params = new ActionBar.LayoutParams(//Center the textview in the ActionBar !
ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.MATCH_PARENT,
Gravity.CENTER);
TextView tvTitle = viewActionBar.findViewById(R.id.title);
tvTitle.setText("NEW SUGGESTION (Cont..)");
abar.setCustomView(viewActionBar, params);
abar.setDisplayShowCustomEnabled(true);
abar.setDisplayShowTitleEnabled(false);
//abar.setDisplayHomeAsUpEnabled(true);
abar.setHomeButtonEnabled(true);
etPresent = findViewById(R.id.etPresent);
etDetails = findViewById(R.id.etDetails);
etBenefit = findViewById(R.id.etBenefit);
imgAttach = findViewById(R.id.imgAttach);
btnCamera=findViewById(R.id.btnCamera);
EnableRuntimePermission();
btnCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 7);
}
});
btnGallery=findViewById(R.id.btnGallery);
btnGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Photo"),REQUEST_CODE);
}
});
btnNext = findViewById(R.id.btnNext);
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPref = getSharedPreferences("MyData", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("present", etPresent.getText().toString());
editor.putString("details", etDetails.getText().toString());
editor.putString("benefit", etBenefit.getText().toString());
editor.apply();
Intent intent = new Intent(NewSuggestion2.this,ConfirmSuggestion.class);
startActivity(intent);
}
});
btnClear = findViewById(R.id.btnClear);
btnClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imgAttach.setImageBitmap(null);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 7 && resultCode == RESULT_OK) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
imgAttach.setImageBitmap(bitmap);
}
if(requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null && data.getData() != null){
Uri uri = data.getData();
try{
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
imgAttach.setImageBitmap(bitmap);
}catch (IOException e){
e.printStackTrace();
}
}
}
public void EnableRuntimePermission(){
if (ActivityCompat.shouldShowRequestPermissionRationale(NewSuggestion2.this,
Manifest.permission.CAMERA))
{
Toast.makeText(NewSuggestion2.this,"CAMERA permission allows us to Access CAMERA app", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(NewSuggestion2.this,new String[]{
Manifest.permission.CAMERA}, RequestPermissionCode);
}
}
#Override
public void onRequestPermissionsResult(int RC, String per[], int[] PResult) {
switch (RC) {
case RequestPermissionCode:
if (PResult.length > 0 && PResult[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(NewSuggestion2.this,"Permission Granted, Now your application can access CAMERA.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(NewSuggestion2.this,"Permission Canceled, Now your application cannot access CAMERA.", Toast.LENGTH_LONG).show();
}
break;
}
}
#Override
public void onBackPressed() {
}
}
Assign value to present,details,benefit from sharedpref
SharedPreferences sharedPref = getSharedPreferences("MyData", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
etPresent = findViewById(R.id.etPresent);
etDetails = findViewById(R.id.etDetails);
etBenefit = findViewById(R.id.etBenefit);
etPresent.setText(sharedPref.getString("present", ""));
etDetails.setText(sharedPref.getString("details", ""));
etBenefit.setText(sharedPref.getString("benefit", ""));
In Activity B make sure you save data in onBackPressed()
#Override
public void onBackPressed() {
editor.putString("present", etPresent.getText().toString());
editor.putString("details", etDetails.getText().toString());
editor.putString("benefit", etBenefit.getText().toString());
editor.apply();
super.onBackPressed();
}
You have to override the onBackPress() method.In Activity B it is necessary to put data in to SharedPreferences.
#Override
public void onBackPressed() {
SharedPreferences sharedPref = getSharedPreferences("MyData", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("present", etPresent.getText().toString());
editor.putString("details", etDetails.getText().toString());
editor.putString("benefit", etBenefit.getText().toString());
editor.commit();
}

Pass data from ListView in activity to fragment

How to pass data from ListView in activity to fragment To view the location on the map, look on my method addMarker() in FragmentTwoClass?
.....................................................................................................
FavoritesActivity:
public class Favorites extends AppCompatActivity {
private ArrayList<MapModel> mMapList; // ArrayList of MovieModel
private MapCustomAdapterFavorites mAdapter; // CustomAdapter of MainActivity
private GetMapsAsyncTaskFavorites mGetMapsAsyncTaskFavorites; // AsyncTask for AddMovie to add movie to MainActivity
private ListView mListView; // ListView of MainActivity
private MapDBHelperFavorites mMapDBHelper; // The SQLiteHelper of the app
private SwipeRefreshLayout swipeRefreshLayout; // SwipeRe freshLayout of MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favorite);
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("LocationProject");
mListView = findViewById(R.id.listFavorites); // ID of the ListView of MainActivity
swipeRefreshLayout = findViewById(R.id.swipe_container); // ID of the SwipeRefreshLayout of MainActivity
mMapDBHelper = new MapDBHelperFavorites(this); // Put the SQLiteHelper in MainActivity
mMapList = mMapDBHelper.getAllMaps(); // Put the getAllMovies of SQLiteHelper in the ArrayList of MainActivity
mAdapter = new MapCustomAdapterFavorites(this, mMapList); // Comparing the ArrayList of MainActivity to the CustomAdapter
registerForContextMenu(mListView);
// Put AsyncTask in the ListView of MainActivity to execute the SQLiteHelper
mGetMapsAsyncTaskFavorites = new GetMapsAsyncTaskFavorites(mListView);
mGetMapsAsyncTaskFavorites.execute(mMapDBHelper);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
FragmentTwo fragObj = new FragmentTwo();
Bundle bundle = new Bundle();
bundle.putSerializable(getString(R.string.map_edit_favorites), (mMapList.get(position)));
fragObj.setArguments(bundle);
}
});
swipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.colorOrange)); // Colors of the SwipeRefreshLayout of MainActivity
// Refresh the MovieDBHelper of app in ListView of MainActivity
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mGetMapsAsyncTaskFavorites = new GetMapsAsyncTaskFavorites(mListView);
mGetMapsAsyncTaskFavorites.execute(mMapDBHelper);
// Vibration for 0.1 second
Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
vibrator.vibrate(VibrationEffect.createOneShot(100, VibrationEffect.DEFAULT_AMPLITUDE));
} else {
vibrator.vibrate(100);
}
finish();
startActivity(getIntent()); // Refresh activity
Toast toast = Toast.makeText(Favorites.this, "The list are refreshed!", Toast.LENGTH_SHORT);
View view = toast.getView();
view.getBackground().setColorFilter(getResources().getColor(R.color.colorLightBlue), PorterDuff.Mode.SRC_IN);
TextView text = view.findViewById(android.R.id.message);
text.setTextColor(getResources().getColor(R.color.colorBrown));
toast.show(); // Toast
swipeRefreshLayout.setRefreshing(false);
}
});
}
// Sets off the menu of activity_menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.favorites_menu, menu);
return super.onCreateOptionsMenu(menu);
}
// Sets off the menu of list_menu
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.favorites_list_menu, menu);
}
// Options in the activity_menu
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.mute: // Mute all the sound in app
AudioManager managerYes = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
managerYes.setStreamMute(AudioManager.STREAM_MUSIC, true);
Toast toastMute = Toast.makeText(this, "The sound are mute!", Toast.LENGTH_SHORT);
View viewMute = toastMute.getView();
viewMute.getBackground().setColorFilter(getResources().getColor(R.color.colorLightBlue), PorterDuff.Mode.SRC_IN);
TextView textMute = viewMute.findViewById(android.R.id.message);
textMute.setTextColor(getResources().getColor(R.color.colorBrown));
toastMute.show(); // Toast
break;
case R.id.unMute: // Allow all the sound in app
AudioManager managerNo = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
managerNo.setStreamMute(AudioManager.STREAM_MUSIC, false);
Toast toastUnMute = Toast.makeText(this, "The sound are on!", Toast.LENGTH_SHORT);
View viewUnMute = toastUnMute.getView();
viewUnMute.getBackground().setColorFilter(getResources().getColor(R.color.colorLightBlue), PorterDuff.Mode.SRC_IN);
TextView textUnMute = viewUnMute.findViewById(android.R.id.message);
textUnMute.setTextColor(getResources().getColor(R.color.colorBrown));
toastUnMute.show(); // Toast
break;
case R.id.intentMainActivity:
Intent intentBackMainActivity = new Intent(this, MainActivity.class);
startActivity(intentBackMainActivity);
break;
case R.id.deleteAllDataFavorites: // Delete all data of the app for delete all the data of the app
Intent intentDeleteAllData = new Intent(this, DeleteAllDataFavorites.class);
startActivity(intentDeleteAllData);
break;
}
return super.onOptionsItemSelected(item);
}
// Options in the list_menu
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
int listPosition = info.position;
switch (item.getItemId()) {
case R.id.edit: // Edit the movies on MainActivity
Intent intent = new Intent(Favorites.this, EditMap.class);
intent.putExtra(getString(R.string.map_id), mMapList.get(listPosition).getId());
intent.putExtra(getString(R.string.map_edit), mMapList.get(listPosition));
startActivity(intent);
break;
case R.id.shareIntent:
String name = mMapList.get(listPosition).getName();
String address = mMapList.get(listPosition).getVicinity();
double lat = mMapList.get(listPosition).getLat();
double lng = mMapList.get(listPosition).getLng();
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Name: " + name + "\nAddress: " + address + "\nLatitude: " + lat + "\nLongitude: " + lng);
sendIntent.setType("text/plain");
startActivity(sendIntent);
break;
case R.id.delete: // Delete item(movie) on MainActivity
mGetMapsAsyncTaskFavorites.deleteMovie(listPosition);
mMapDBHelper.deleteMap(mMapList.get(listPosition));
Intent intentDeleteData = new Intent(Favorites.this, DeleteMap.class);
startActivity(intentDeleteData);
break;
}
return super.onContextItemSelected(item);
}
FragmentTwoClass:
public class FragmentTwo extends Fragment implements OnMapReadyCallback {
private GoogleMap mGoogleMap;
private MapView mMapView;
private View mView;
private MapModel mapModel;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_two_layout, container, false);
mapModel = (MapModel) getArguments().getSerializable(getString(R.string.map_edit_favorites)); // GetSerializable for the texts
return mView;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mMapView = view.findViewById(R.id.map);
if (mMapView != null) {
mMapView.onCreate(null);
mMapView.onResume();
mMapView.getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
MapsInitializer.initialize(getContext());
mGoogleMap = googleMap;
addMarker();
googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
googleMap.setMyLocationEnabled(true);
}
public void addMarker() {
MarkerOptions marker = new MarkerOptions().position(new LatLng(mapModel.getLat(), mapModel.getLng())).title("Elior home");
mGoogleMap.addMarker(marker);
mGoogleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
return true;
}
});
}

How to save the data in my ListView from the first Activity to the second Activity?

I am writing an app for a restaurant and would like to be able to select a specific dish that you would like to order and that it has been added to OrderActivity where, in the form of ListView, you will be displaying individual dishes selected by the user.
I do not know how to do it in the best way, do you need to use the interface and maybe just get the intention of a specific dish?
And how do I save a specific request in OrderActivity so that when I return to an earlier Activity I do not lose the saved data in the ListView?
I managed to solve the problem of transmitting data from one Activity to the second Activity and showing it on the ListView, I do not know how to save that data, say on the example of SharedPreferences?
If I click the back button in my second Activity, my list becomes empty.
I understand that the fault is on onResume() because I am killing the second Activity, when I come back to the first, is that so?
How to solve the problem?
FirstActivity:
public class DinnerDetailActivity extends AppCompatActivity {
public static final String EXTRA_DINNER = "dinner";
private final int requestCode = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_obiady_domowe_detail);
int dinner = (Integer) getIntent().getExtras().get(EXTRA_DINNER);
String dinnerName = Dinner.dinn[dinner].getName();
TextView textView = (TextView) findViewById(R.id.dinner_text);
textView.setText(dinnerName);
int dinnerImage = Dinner.dinn[dinner].getImageResourceId();
ImageView imageView = (ImageView) findViewById(R.id.dinner_image);
imageView.setImageDrawable(getResources().getDrawable(dinnerImage));
imageView.setContentDescription(dinnerName);
Toolbar myChildToolbar = (Toolbar)
findViewById(R.id.my_child_toolbar_obiady_detail);
setSupportActionBar(myChildToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
/* #Override
protected void onResume() {
SharedPreferences sharedPref = getSharedPreferences("KEY", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("KEY", listItems.add();
editor.apply();
Toast.makeText(getApplicationContext(), "Save!", Toast.LENGTH_SHORT).show();
super.onResume();
}
*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
TextView textView = (TextView) findViewById(R.id.dinner_text);
CharSequence dinnerName = textView.getText();
MenuItem menuItem = menu.findItem(R.id.action_share);
ShareActionProvider shareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, dinnerName);
shareActionProvider.setShareIntent(intent);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_create_order:
Intent intent = new Intent(this, TopFragment.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
//Click button, and add dinnerName to SecondActivity ListView
public void addInOrder(View view) {
int dinner = (Integer) getIntent().getExtras().get(EXTRA_DINNER);
String dinnerName = Dinner.dinn[dinner].getName();
Intent intent1 = new Intent(this, CreateYourOrderActivity.class);
intent1.putExtra("OK", dinnerName);
startActivityForResult(intent1, requestCode);
}
}
Second Activity:
public class CreateYourOrderActivity extends AppCompatActivity {
private ListView listView;
private ArrayAdapter<String> adapter;
private ArrayList<String> listItems;
private String dinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zloz_zamowienie);
Toolbar myChildToolbar = (Toolbar)
findViewById(R.id.my_child_toolbar);
setSupportActionBar(myChildToolbar);
ActionBar ab = getSupportActionBar();
ab.setDisplayHomeAsUpEnabled(true);
textView = (TextView) findViewById(R.id.text_view);
}
/*
#Override
protected void onResume() {
SharedPreferences sharedPref = getSharedPreferences("KEY", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("KEY", obiad);
editor.apply();
listItems.add(obiad);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Save!", Toast.LENGTH_SHORT).show();
super.onResume();
}
*/
/* #Override
public void onBackPressed() {
SharedPreferences sharedPref = getSharedPreferences("KEY", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("KEY", listItems.get(0).toString());
editor.apply();
Toast.makeText(getApplicationContext(), "Save!", Toast.LENGTH_SHORT).show();
}*/
public void saveInfo(View view) {
}
public void openInfo(View view) {
SharedPreferences sharedPref = getSharedPreferences("KEY", Context.MODE_PRIVATE);
String obiadNames = sharedPref.getString("KEY", "");
textView.setText(obiadNames);
//listItems.add(obiadNames);
//adapter.notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_create_order:
Intent intent = new Intent(this, MainActivity.class);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Intent intent = getIntent();
if(resultCode == RESULT_OK) {
if(requestCode == 1){
dinner = data.getExtras().getString("OK");
listView = (ListView) findViewById(R.id.listView);
listItems.add(dinner);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems);
listView.setAdapter(adapter);
// adapter.add(dinner);
adapter.notifyDataSetChanged();
finish();
}
}
}
So as you can see in the attached photos we have the first Activity, several dishes from which we go to the detailed Activity, where we have AddOrder Button.
I would like to click on this button to add the name of my specific dish in the 3 Activities that you see in the pictures.
This is to be added as a ListView.
Also, I would like to have the names of dishes not gone when I return to 1 Activity.
SharedPreferences are for simple values.
You'll need a proper database (Sqlite, Realm, or other) with which you can persistently store and query your data across the entire application without passing entire objects across Intent boundaries.
More specifically, you need to replace the Dinner.dinn array
To get specific items when you go to a detail view, you can pass the database ID of the object, then query it later.
When you add a new item and go back to the list, you will update the adapter with all the database entries

Categories

Resources