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

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.

Related

getting error when i try to use switch button is differen class

So I defined a switch button in ProfileSettingsfragment but i am using that button in Explanation.class. What I am really trying to do is when switch button is checked i want start service else i don't want to star service from Explanation.class
SO I tried Some code and it showing me this error " java.lang.NullPointerException: Attempt to invoke virtual method 'boolean androidx.appcompat.widget.SwitchCompat.isChecked()' on a null object reference
at com.harsh.preacher.ui.Home.Explaination$1.onClick(Explaination.java:43)"
P.S I have designed switch button in ProfileSettingsfragment.xml
Here is ProfileSettingsfragment class code
public class ProfileSettingsFragment extends Fragment {
private GoogleSignInClient mGoogleSignInClient;
public SwitchCompat notePopUp;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_profilesettings, container, false);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(requireContext(), gso);
final ProfileSettingsFragment profileSettingsFragment =new ProfileSettingsFragment();
Button signOut1 = root.findViewById(R.id.signOut);
signOut1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//TODO Custom Alert Dialog Bar
// signOut();
Intent intent = new Intent(getContext(), AndarAwoo.class);
startActivity(intent);
// Animation(signOut1);
}
});
notePopUp = (SwitchCompat) root.findViewById(R.id.notePopUp);
RelativeLayout EditName = root.findViewById(R.id.EditName);
RelativeLayout ProfileSettingsLayout= root.findViewById(R.id.profileSettingsCardView);
TextView EditNameText = root.findViewById(R.id.EditNameText);
EditNameText.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onClick(View view) {
if(EditName.getVisibility() == View.GONE){
TransitionManager.beginDelayedTransition(ProfileSettingsLayout,new AutoTransition());
EditName.setVisibility(View.VISIBLE);
}else {
TransitionManager.beginDelayedTransition(ProfileSettingsLayout,new AutoTransition());
EditName.setVisibility(View.GONE);
}
}
});
return root;
}
Here is my explanation class code
public class Explaination extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_explaination);
Intent intent = getIntent();
String about = intent.getStringExtra("about");
TextView about1 = findViewById(R.id.about);
about1.setText(about);
Button resource = findViewById(R.id.Resource);
resource.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = getIntent();
String url = intent.getStringExtra("button");
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
ProfileSettingsFragment checkNotePopUp = new ProfileSettingsFragment();
checkNotePopUp.notePopUp = findViewById(R.id.notePopUp);
if(checkNotePopUp.notePopUp.isChecked()){
startService(new Intent(Explaination.this, NotePopUpHead.class));
}
else{
stopService(new Intent(Explaination.this,NotePopUpHead.class));
}
finish();
startActivity(i);
}
});
}
}

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);
}
}

Having a problem when i touch a user to start chatting

I am having a trouble on open the contact from my contact list page it was working fine but when i touch the user to open the messages activity so it should start chatting there.
This is my messages activity:
public class MessageActivity extends AppCompatActivity {
CircleImageView imageView;
FirebaseUser firebaseUser;
DatabaseReference reference;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
final Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
imageView = findViewById(R.id.profile_image);
intent = getIntent();
String userid = intent.getStringExtra("userid");
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
reference = FirebaseDatabase.getInstance().getReference("parent").child(userid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
if (user.getImageURL().equals("default")) {
imageView.setImageResource(R.drawable.ic_user);
}else {
Glide.with(MessageActivity.this).load(user.getImageURL()).into(imageView);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
And this is the intent i was calling for:
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, MessageActivity.class);
intent.putExtra("userid", user.getId());
context.startActivity(intent);
}
});
This is my logcat when i run the app:
2020-05-01 20:39:12.857 12974-12974/net.gobz.gobz E/AndroidRuntime: FATAL EXCEPTION: main
Process: net.gobz.gobz, PID: 12974
android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
at android.app.ContextImpl.startActivity(ContextImpl.java:994)
at android.app.ContextImpl.startActivity(ContextImpl.java:970)
at android.content.ContextWrapper.startActivity(ContextWrapper.java:389)
at net.gobz.gobz.Adapter.UserAdapter$1.onClick(UserAdapter.java:54)
After reading your logcat , which is saying that you have to use Flags to your IntentActivity so try with replacing your code with this one.
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, MessageActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|
Intent.FLAG_ACTIVITY_CLEAR_TASK |
Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("userid", user.getId());
context.startActivity(intent);
}
});

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();
}

How manage data upload sent PutExtra

I am sending the data between activities, through PutExtra. It's working perfectly.
The problem is when you click the back button, give an error and for the activity.
I've already tried to implement the StarActivityForResult option, and I can not get it to work.
Images below. Code "12345" is used as an example, and is sent to the three screens as PutExtra
Code:
Activity1:
public class MainActivity extends AppCompatActivity {
private Button btnIrAct2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnIrAct2 = (Button) findViewById(R.id.btnIrAct2);
btnIrAct2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent2 = new Intent(MainActivity.this, Activity2.class);
intent2.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent2.putExtra("id_empresa", "12345");
startActivity(intent2);
}
});
}
}
Activity 2:
public class Activity2 extends AppCompatActivity {
private Button btnIrAct3;
private String mId_Empresa = null;
static final int SERVICO_DETALHES_REQUEST = 1;
private TextView tvResultado;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
/* Recebe id de outra tela*/
mId_Empresa = getIntent().getExtras().getString("id_empresa");
tvResultado = (TextView) findViewById(R.id.tvAct2);
tvResultado.setText(mId_Empresa);
btnIrAct3 = (Button) findViewById(R.id.btnIrAct3);
btnIrAct3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent3 = new Intent(Activity2.this, Activity3.class);
intent3.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent3.putExtra("id_empresa", "12345");
startActivityForResult(intent3, SERVICO_DETALHES_REQUEST );
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == SERVICO_DETALHES_REQUEST && resultCode == RESULT_OK) {
String resultBack = data.getStringExtra("id_empresa");
}
}
}
Activity 3:
public class Activity3 extends AppCompatActivity {
private String idEmpresa = null;
private TextView resultado;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_3);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
/* Recebe id de outra tela*/
idEmpresa = getIntent().getExtras().getString("id_empresa");
resultado = (TextView) findViewById(R.id.tvAct3);
resultado.setText(idEmpresa);
}
#Override
public void finish()
{
Intent data = new Intent();
data.putExtra("id_empresa", "12345");
setResult(Activity.RESULT_OK, data);
super.finish();
}
}
I need to resolve the conflict. Because on my return I need to send a data like PutExtra, at the same time that this Activity already has a piece of code that already receives a PutExtra.
If I understand the issue correctly, you should to use fragments instead of activities and save all the data in main activity but if you want to continue with this way try onBackPressed() method to choose what to do when the user pressed back button.
Insert this code in Activity 2
if(getIntent().getExtras().getString("id_empresa") != null)
{
mId_Empresa = getIntent().getExtras().getString("id_empresa");
}
Checking the data before setting it to the textview is must. If the string you are putting to textview is null, it will generate an error which will lead to crash.
Hope it helps!

Categories

Resources