When I run my app it just opens a white screen and stays there, it slows my whole phone down until I'm forced to shut it down. Logcat says that the first error is "Perfoming stop of activity that is not resumed". I don't really have a onResume on my main file. Should I have a onResume or is there another way to fix this problem?
Here is the error I get when it runs:
05-13 05:13:34.124: E/ActivityThread(27498): Performing stop of activity that is not resumed: {com.example.douglas.topic/com.example.douglas.topic.LoginActivity}
05-13 05:13:34.124: E/ActivityThread(27498): java.lang.RuntimeException: Performing stop of activity that is not resumed: {com.example.douglas.topic/com.example.douglas.topic.LoginActivity}
05-13 05:13:34.124: E/ActivityThread(27498): at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:3214)
05-13 05:13:34.124: E/ActivityThread(27498): at android.app.ActivityThread.handleStopActivity(ActivityThread.java:3301)
05-13 05:13:34.124: E/ActivityThread(27498): at android.app.ActivityThread.access$1100(ActivityThread.java:139)
05-13 05:13:34.124: E/ActivityThread(27498): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
05-13 05:13:34.124: E/ActivityThread(27498): at android.os.Handler.dispatchMessage(Handler.java:102)
05-13 05:13:34.124: E/ActivityThread(27498): at android.os.Looper.loop(Looper.java:136)
05-13 05:13:34.124: E/ActivityThread(27498): at android.app.ActivityThread.main(ActivityThread.java:5097)
05-13 05:13:34.124: E/ActivityThread(27498): at java.lang.reflect.Method.invokeNative(Native Method)
05-13 05:13:34.124: E/ActivityThread(27498): at java.lang.reflect.Method.invoke(Method.java:515)
05-13 05:13:34.124: E/ActivityThread(27498): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
05-13 05:13:34.124: E/ActivityThread(27498): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
05-13 05:13:34.124: E/ActivityThread(27498): at dalvik.system.NativeStart.main(Native Method)
Here is the code for my main activity:
package com.example.douglas.topic;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.douglas.topic.LoginActivity;
import com.example.douglas.topic.PostActivity;
import com.example.douglas.topic.PostAdapter;
import com.example.douglas.topic.PostDataProvider;
import com.example.douglas.topic.R;
import com.parse.Parse;
import com.parse.ParseObject;
import com.parse.ParseUser;
public class Lorem extends ActionBarActivity {
//private static final String="POST";
ListView listView;
int[] pic_thumbnail_resource = {R.mipmap.ic_launcher, R.mipmap.ic_launcher, R.mipmap.ic_launcher, R.mipmap.ic_launcher,
R.mipmap.ic_launcher, R.mipmap.ic_launcher,};
String[] post_ratings;
String[] post_titles;
PostAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
// Parse
// Enable Local Datastore.
//Parse.enableLocalDatastore(this);
Parse.initialize(getApplicationContext(), "wHN7DSZyAzVXT5xs5ASDFGwOWasUExbeuePvQvL", "SsvjuJ7e97FsScI12VB7dlv8RilgSoFSw5waIOXM");
//ParseObject testObject = new ParseObject("TestObject");
//testObject.put("foo", "bar");
//testObject.saveInBackground();
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser != null) {
// do stuff with the user
} else {
// show the signup or login screen
Intent takeUsertoLogin = new Intent(this, LoginActivity.class);
startActivity(takeUsertoLogin);
}
// End Parse
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lorem);
listView = (ListView)findViewById(R.id.list_view);
post_ratings = getResources().getStringArray(R.array.post_ratings);
post_titles = getResources().getStringArray(R.array.post_titles);
//populateListView();
registerClickCallback();
int i = 0;
adapter = new PostAdapter(getApplicationContext(),R.layout.row_layout);
listView.setAdapter(adapter);
for(String titles: post_titles)
{
PostDataProvider dataProvider = new PostDataProvider(pic_thumbnail_resource[i], titles, post_ratings[i]);
adapter.add(dataProvider);
i++;
}
}
private void registerClickCallback(){
ListView list = (ListView) findViewById(R.id.list_view);
list.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id){
TextView textView = (TextView) viewClicked;
String message = "You clicked # " + position + ",which is string: " + textView.getText().toString();
Toast.makeText(Lorem.this, message, Toast.LENGTH_LONG).show();
}
});
}
/*
#Override
public void onActivityResult(String requestCode, String resultCode, Intent data){
if (requestCode == "POST")
{
myItems.add
}
super.onActivityResult(requestCode, resultCode, data);
}
*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_lorem, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()){
case R.id.post:
aboutItemPost();
break;
case R.id.location:
aboutItemLocation();
break;
case R.id.topic:
aboutItemTopic();
break;
case R.id.sort:
aboutItemSort();
break;
case R.id.login:
aboutItemLogin();
case R.id.Register:
aboutItemRegister();
case R.id.Logout:
aboutItemLogout();
}
return true;
}
private void aboutItemPost(){
Intent intent = new Intent(getApplicationContext(), PostActivity.class);
startActivityForResult(intent, 0);
}
private void aboutItemLocation(){
Intent intent = new Intent(getApplicationContext(), LocationActivity.class);
startActivityForResult(intent, 0);
}
private void aboutItemTopic(){
Intent intent = new Intent(getApplicationContext(), TopicActivity.class);
startActivityForResult(intent, 0);
}
private void aboutItemSort(){
new AlertDialog.Builder(this)
.setTitle("Sort")
.setMessage("This is where the user will sort what they want to see")
.setNeutralButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
private void aboutItemLogin(){
Intent takeUsertoLogin = new Intent(this, LoginActivity.class);
startActivity(takeUsertoLogin);
}
private void aboutItemRegister(){
Intent intent = new Intent(getApplicationContext(), RegisterActivity.class);
startActivityForResult(intent, 0);
}
private void aboutItemLogout() {
// log the user out
ParseUser.logOut();
// take the user back to log in screen
Intent takeUsertoLogin = new Intent(this, LoginActivity.class);
startActivity(takeUsertoLogin);
}
}
Here is the code for my Login activity:
package com.example.douglas.topic;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.parse.LogInCallback;
import com.parse.Parse;
import com.parse.ParseUser;
import java.text.ParseException;
/**
* Created by Douglas on 5/10/2015.
*/
public class LoginActivity extends Lorem {
protected EditText mUsername;
protected EditText mPassword;
protected Button mLoginButton;
protected Button mCreateAccountButton;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//initialize
mUsername = (EditText)findViewById(R.id.LoginUserName);
mPassword = (EditText)findViewById(R.id.LoginPassword);
mLoginButton = (Button)findViewById(R.id.LoginButton);
mCreateAccountButton = (Button)findViewById(R.id.LoginRegisterButton);
// Listen to when mLoginButton is clicked
mLoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// get the user input from the edit text and convert into string
String username = mUsername.getText().toString().trim();
String password = mPassword.getText().toString().trim();
// Login the user using Parse SDK
ParseUser.logInInBackground(username, password, new LogInCallback() {
#Override
public void done(ParseUser parseUser, com.parse.ParseException e) {
if (e == null) {
// Success, user logged in
Toast.makeText(LoginActivity.this, "Welcome Back!", Toast.LENGTH_SHORT).show();
Intent takeUserHome = new Intent(LoginActivity.this, Lorem.class);
startActivity(takeUserHome);
} else {
// Failure to Log in, advise user
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage(e.getMessage());
builder.setTitle("Sorry!");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// close the dialog window
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
});
}
}
Thank you for your time.
You have made action before Activity has finished loading:
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lorem);
must be on the top in Your onCreate(). Also, the logcat says, that the problem might be in the LoginActivity. Change the order like I said and come back if this was not the problem.
Related
Hi Please help me to resolve this issue I m getting this error
message. The app crashes I have tried almost every solution suggested
on Google
I am creating a Notes application for Android and the logic of the app when it starts is to check if there is a user created and logged in or not. if there is a user created then start MainActivity
if there is no user created login with Anonymous account
package com.russrezepov.mynotes;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.russrezepov.mynotes.auth.Login;
public class Splash extends AppCompatActivity {
private FirebaseAuth fAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
fAuth = FirebaseAuth.getInstance();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (fAuth.getCurrentUser() != null) {
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
} else {
//create a new Anonymous account if a User is not logged in or does not have an account
fAuth.signInAnonymously().addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
Toast.makeText(Splash.this, "Logged in with Temp Account", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),MainActivity.class));
finish();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Splash.this, "Error" + e.getMessage(), Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), Login.class));
finish();
}
});
}
}
}, 1000);
}
}
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.russrezepov.mynotes, PID: 5158
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.russrezepov.mynotes/com.russrezepov.mynotes.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.google.firebase.auth.FirebaseUser.isAnonymous()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.google.firebase.auth.FirebaseUser.isAnonymous()' on a null object reference
at com.russrezepov.mynotes.MainActivity.onCreate(MainActivity.java:97)
at android.app.Activity.performCreate(Activity.java:8000)
at android.app.Activity.performCreate(Activity.java:7984)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
I/Process: Sending signal. PID: 5158 SIG: 9
Disconnected from the target VM, address: 'localhost:54989', transport: 'socket'
The Error message shows that if (user.isAnonymous()) is where the code below is stops
package com.russrezepov.mynotes;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
import com.russrezepov.mynotes.auth.Login;
import com.russrezepov.mynotes.auth.Register;
import com.russrezepov.mynotes.model.Note;
import com.russrezepov.mynotes.note.AddNote;
import com.russrezepov.mynotes.note.EditNote;
import com.russrezepov.mynotes.note.TheNoteDetails;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawerLayout;
ActionBarDrawerToggle toggle;
NavigationView nav_view;
RecyclerView noteList;
FloatingActionButton fab;
FirebaseUser user;
FirebaseAuth fAuth;
private FirebaseFirestore fStore;
//private Adapter adapter;
//private NoteAdapter noteAdapter;
final static String TAG = "Firebase Not Reading";
final static String TAGF = "Firebase CONNECTED";
FirestoreRecyclerAdapter<Note,NoteViewHolder> noteAdapter;
//>>>ON CREATE <<<
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Log.i(TAGF,"onCreate");
drawerLayout = findViewById(R.id.drawer);
nav_view = findViewById(R.id.nav_view);
nav_view.setNavigationItemSelectedListener(this);
toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open, R.string.close);
drawerLayout.addDrawerListener(toggle);
toggle.setDrawerIndicatorEnabled(true);
toggle.syncState();
noteList = findViewById(R.id.noteList);
fab = findViewById(R.id.addNoteFloat);
View headerView = nav_view.getHeaderView(0);
TextView userDisplayName = headerView.findViewById(R.id.userDisplayName);
TextView userDisplayEmail = headerView.findViewById(R.id.userDisplayEmail);
if (user.isAnonymous()) {
userDisplayName.setText("Temporary Account");
userDisplayEmail.setVisibility(View.GONE);
} else {
userDisplayEmail.setText(user.getEmail());
userDisplayName.setText(user.getDisplayName());
}
setUpRecyclerView();
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(view.getContext(), AddNote.class));
overridePendingTransition(R.anim.slide_up,R.anim.slide_down);
finish();
}
});
}
private void setUpRecyclerView() {
fStore = FirebaseFirestore.getInstance();
fAuth = FirebaseAuth.getInstance();
user = fAuth.getCurrentUser();
//query notes=>UID=>MyNotes=>user all notes
Query query = fStore.collection("notes").document(user.getUid()).collection("myNotes").orderBy("title",Query.Direction.DESCENDING);
//executing the query
FirestoreRecyclerOptions<Note> allNotes;
allNotes = new FirestoreRecyclerOptions.Builder<Note>()
.setQuery(query, Note.class)
.build();
// fStore.collection("notes")
// .get()
// .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
// #Override
// public void onComplete(#NonNull Task<QuerySnapshot> task) {
// if (task.isSuccessful()) {
// Log.i(TAGF,"Firebase Connected Successfully");
// for (QueryDocumentSnapshot document : Objects.requireNonNull(task.getResult())) {
// //titles.add(document.getString("title"));
// //content.add(document.getString("content"));
// Log.i(TAGF,document.getString("title"));
// Log.i(TAGF,document.getString("content"));
// Log.i(TAGF,"Firebase Connected Successfully");
// }
// } else {
// Log.w(TAG,"Error getting documents.", task.getException());
// }
// }
// });
noteAdapter = new FirestoreRecyclerAdapter<Note, NoteViewHolder> (allNotes) {
#RequiresApi(api = Build.VERSION_CODES.M)
protected void onBindViewHolder(#NonNull NoteViewHolder noteViewHolder, final int i, #NonNull final Note note) {
//Binding data from MainActivity, when Adapter object is created, to this View that we have here
noteViewHolder.noteTitle.setText(note.getTitle());
noteViewHolder.noteContent.setText(note.getContent());
final int colorCodes = getRandomColor();
noteViewHolder.mCardView.setBackgroundColor(noteViewHolder.view.getResources().getColor(colorCodes,null));
//getting each doc id to be able to update them in EditNote using i as a position in collections
final String docId = noteAdapter.getSnapshots().getSnapshot(i).getId();
noteViewHolder.view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//getting current context where we are starting the Activity and passing them to another activity
Intent i = new Intent(v.getContext(), TheNoteDetails.class);
//When someone clicks on the first item in the RecyclerView it is going to get the position as Zero -> Position
//passing the title and description to the NoteDetails
i.putExtra("title", note.getTitle());
i.putExtra("content", note.getContent());
i.putExtra("color", colorCodes);
i.putExtra("noteId",docId);
v.getContext().startActivity(i); //Not passing anything yet. Just getting current context and passing current context
}
});
//Adding menu Edit & Delete functionality for each Note in Main Activity
ImageView menuIcon = noteViewHolder.view.findViewById(R.id.menuIcon);
menuIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
final String docId = noteAdapter.getSnapshots().getSnapshot(i).getId();
PopupMenu popupMenu = new PopupMenu(v.getContext(),v);
popupMenu.setGravity(Gravity.END);
popupMenu.getMenu().add("Edit").setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
Intent i = new Intent(v.getContext(), EditNote.class);
i.putExtra("title",note.getTitle());
i.putExtra("content",note.getContent());
i.putExtra("noteId",docId);
startActivity(i);
return false;
}
});
popupMenu.getMenu().add("Delete").setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
DocumentReference docRef = fStore.collection("notes").document(user.getUid()).collection("myNotes").document(docId);
docRef.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(MainActivity.this, "Note Deleted", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Error Deleting Note", Toast.LENGTH_SHORT).show();
}
});
return false;
}
});
popupMenu.show();
}
});
}
#NonNull
#Override
public NoteViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.note_view_layout,parent, false);
return new NoteViewHolder(view);
}
};
//Staggered layout expands based on Context Size
noteList.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL));
noteList.setAdapter(noteAdapter);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
drawerLayout.closeDrawer(GravityCompat.START);
switch (item.getItemId()) {
case R.id.addNote:
startActivity(new Intent(this, AddNote.class));
overridePendingTransition(R.anim.slide_up,R.anim.slide_down);
break;
case R.id.sync:
// sending Anonymous users only to Sync Activity aka Register New Account
if (user.isAnonymous()) {
startActivity(new Intent(this, Login.class));
overridePendingTransition(R.anim.slide_up,R.anim.slide_down);
} else {
Toast.makeText(this, "You Are Already Connected", Toast.LENGTH_SHORT).show();
}
break;
case R.id.logout:
checkUser();
break;
default:
Toast.makeText(this, "Coming Soon!", Toast.LENGTH_SHORT).show();
}
return false;
}
private void checkUser() {
//Check if the user is real or Anonymous
if (user.isAnonymous()) {
displayAlert();
} else {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(getApplicationContext(), Splash.class));
overridePendingTransition(R.anim.slide_up,R.anim.slide_down);
}
}
private void displayAlert() {
AlertDialog.Builder warnignAlert = new AlertDialog.Builder(this)
.setTitle("Are you sure?")
.setMessage("you are logged in with Temp account. Logging out will delete all unsaved notes")
.setPositiveButton("Sync Note", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(getApplicationContext(), Register.class));
finish();
}
}).setNegativeButton("Logout", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//TODO: delete all the notes created by the anonymous user
// fStore.collection("notes").document(user.getUid()).document()
// fStore.collection("notes").document(user.getUid())
// .delete()
// .addOnSuccessListener(new OnSuccessListener<Void>() {
// #Override
// public void onSuccess(Void aVoid) {
// Log.d(TAG, "Notes successfully deleted!");
// }
// })
// .addOnFailureListener(new OnFailureListener() {
// #Override
// public void onFailure(#NonNull Exception e) {
// Log.w(TAG, "Error deleting Notes", e);
// }
// });
//TODO: delete the anonymous user
user.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
startActivity(new Intent(getApplicationContext(),Splash.class));
overridePendingTransition(R.anim.slide_up,R.anim.slide_down);
}
});
}
});
warnignAlert.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.option_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == R.id.settings) {
Toast.makeText(this, "Settings Menu is Clicked!", Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
#Override
protected void onStart() {
super.onStart();
noteAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
noteAdapter.stopListening();
}
public static class NoteViewHolder extends RecyclerView.ViewHolder {
TextView noteTitle, noteContent;
View view;
CardView mCardView;
private NoteViewHolder(#NonNull final View itemView) {
super(itemView);
noteTitle = itemView.findViewById(R.id.titles);
noteContent = itemView.findViewById(R.id.content);
mCardView = itemView.findViewById(R.id.noteCard);
view = itemView; //Handles clicks on Recycle View items. Clicks are redirected to the inside of a Note
}
}
private int getRandomColor() {
List<Integer> colorCode = new ArrayList<>();
colorCode.add(R.color.blue);
colorCode.add(R.color.yellow);
colorCode.add(R.color.skyBlue);
colorCode.add(R.color.lightPurple);
colorCode.add(R.color.lightGreen);
colorCode.add(R.color.greenlight);
colorCode.add(R.color.gray);
colorCode.add(R.color.pink);
colorCode.add(R.color.red);
colorCode.add(R.color.notgreen);
Random randomColor = new Random();
int numberColor = randomColor.nextInt(colorCode.size());
return colorCode.get(numberColor);
}
}
You are initializing the user object after accessing it. You are doing it in setUpRecyclerView but accessing it before.
setUpRecyclerView();
if (user.isAnonymous()) {
userDisplayName.setText("Temporary Account");
userDisplayEmail.setVisibility(View.GONE);
} else {
userDisplayEmail.setText(user.getEmail());
userDisplayName.setText(user.getDisplayName());
}
This will make sure you have user object before using it.
I am trying to implement the logout method in my android application
and write the below code. Main Activity is a login activity and ChoosingProcActivity is an activity which contains logout button.
when I press logout button it moves me to Main Activity but when I open application next time it directly moves me to ChoosingProcActivity.
in addition to that when I log in successfully and then go back or press back it show Main Activity (login). how can I avoid this?
are shared preferences wrong?
Main Activity code
package com.example.lenovo.tactic;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Vibrator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
public class MainActivity extends AppCompatActivity {
EditText email_input,password_input;
TextView reset;
Button btnLogin;
Boolean isLogedBefore = false;
Vibrator v;
String organizer_ID;
SharedPreferences test_name;
final String loginURL = "http://tactickevent.com/phpApp/loginApp.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
email_input = findViewById(R.id.etUserName);
password_input = findViewById(R.id.etPassword);
btnLogin = findViewById(R.id.btnLogin);
test_name = getSharedPreferences("NAME", Context.MODE_PRIVATE);
test_name.getString("email", "");
test_name.getString("organizer_ID", "");
// if(isLogedBefore == true){
boolean is = test_name.getBoolean("isLoged", false);
if (is==true) {
Intent intent = new Intent(MainActivity.this, ChoosingProcActivity.class);
startActivity(intent);
// }
}
v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
validateUserData();
}
});
}
private void validateUserData() {
//first getting the values
final String email = email_input.getText().toString();
final String password = password_input.getText().toString();
//checking if email is empty
if (TextUtils.isEmpty(email)) {
email_input.setError("أدخل البريد الالكتروني من فضلك");
email_input.requestFocus();
// Vibrate for 100 milliseconds
v.vibrate(100);
btnLogin.setEnabled(true);
return;
}
//checking if password is empty
if (TextUtils.isEmpty(password)) {
password_input.setError("أدخل كلمة السر من فضلك");
password_input.requestFocus();
//Vibrate for 100 milliseconds
v.vibrate(100);
btnLogin.setEnabled(true);
return;
}
//validating email
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
email_input.setError("أدخل بريد الكتروني صحيح");
email_input.requestFocus();
//Vibrate for 100 milliseconds
v.vibrate(100);
btnLogin.setEnabled(true);
return;
}
//Login User if everything is fine
//first getting the values
//String emaill = email_input.getText().toString();
// String passwordd = password_input.getText().toString();
loginUser(email,password);
}
private void loginUser(final String email,final String password) {
RequestQueue queue = Volley.newRequestQueue(this);
//Call our volley library
StringRequest stringRequest = new StringRequest(Request.Method.POST,loginURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
// Toast.makeText(getApplicationContext(),response.toString(), Toast.LENGTH_SHORT).show();
JSONObject obj = new JSONObject(response);
if (obj.getInt("value")== 1) {
organizer_ID = obj.getString("organizer_ID");
//storing the user in shared preferences
//SharedPref.getInstance(getApplicationContext()).storeID(organizer_ID);
//starting the ChoosingProcActivity
SharedPreferences.Editor editor = test_name.edit();
editor.putBoolean("isLoged",true);
editor.putString("email", email);
editor.putString("organizer_ID", organizer_ID);
//apply
editor.commit();
Toast.makeText(getApplicationContext(), "تم تسجيل الدخول بنجاح", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), ChoosingProcActivity.class));
//finish();
// startActivity(new Intent(getApplicationContext(), ChoosingProcActivity.class));
} else{
Toast.makeText(getApplicationContext(),"هناك خطأ في كلمة السر أو البريد الالكتروني ", Toast.LENGTH_SHORT).show();
//getting user name
//Toast.makeText(getApplicationContext(), obj.getString("messagee"), Toast.LENGTH_SHORT).show();
//storing the user in shared preferences
//SharedPref.getInstance(getApplicationContext()).storeUserName(organizer_ID);
//starting the profile activity
//finish();
//startActivity(new Intent(getApplicationContext(), ChoosingProcActivity.class));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Connection Error"+error, Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
}) {
//email key mean the value that will send to php in $_POST["email"];
//password key mean the value that will send to php in $_POST["password"];
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("email", email);
params.put("password", password);
return params;
}
};
queue.add(stringRequest);
/*
String type = "login";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type, email, password);
try {
JSONObject jsonObject = new JSONObject(result1);
SharedPreferences.Editor editor = test_name.edit();
editor.putBoolean("isLoged",true);
editor.putString("email", email);
editor.putString("organizer_ID", jsonObject.getString("organizer_ID"));
//apply
editor.commit();
*/
}
}
code of second activity
package com.example.lenovo.tactic;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class ChoosingProcActivity extends AppCompatActivity {
Button eventBTN, subeventBTN;
SharedPreferences test_name;
String emailToPass,organizer_ID;
SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choosing_proc);
eventBTN= (Button)findViewById(R.id.BtnEvent);
subeventBTN= (Button)findViewById(R.id.BtnSubEvent);
test_name = getSharedPreferences("NAME", Context.MODE_PRIVATE);
emailToPass= test_name.getString("email", "");
organizer_ID= test_name.getString("organizer_ID", "");
eventBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ChoosingProcActivity.this, EventProcActivity.class);
startActivity(intent);
}
});
subeventBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ChoosingProcActivity.this, SubeventProcActivity.class);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
if(item.getItemId() ==R.id.logout)
{
preferences =getSharedPreferences("Name",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();
finish();
}
return true;
}
}
You can finish your activity every time the test is true so that it can no longer be accessible from the stack.
boolean is = test_name.getBoolean("isLoged", false);
if (is) {
Intent intent = new Intent(MainActivity.this, ChoosingProcActivity.class);
startActivity(intent);
finish();
}
I am assuming that your MainActivity is the first one to get launched when opening the app.
In your MainActivity add this:
#Override
protected void onStart() {
super.onStart();
if (SharedPrefManager.getInstance(this).isLoggedIn()) {
Intent intent = new Intent(this, ChoosingProcActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
}
What it does during startup of your app it will query if there is someone already logged in if yes it will go to the ChoosingProcActivity. I am assuming that in your SharedPrefManager implementation you have a code to know if there is a logged in user.
In your login method uncomment the finish() method
startActivity(new Intent(getApplicationContext(), ChoosingProcActivity.class));
//finish();
After successfull login, if you press back button you will not see the MainActivity.
In your ChoosingProcActivity it will look like this:
#Override
protected void onStart() {
super.onStart();
if (!SharedPrefManager.getInstance(this).isLoggedIn()) {
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
}
Basically, it will ask if there is currently logged in user if not, it will go back to the MainActivity.
EDIT In Logout you may use this as basis from your code,
logoutComponent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPrefManager.getInstance(getActivity()).clear();
Intent intent = new Intent(ChooseProcActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
});
I am working on a project in which I used Bottom Navigation Bar. On Nav Bar, I used 4 menu items(Profile, Home, Reservation, Logout), for them I used fragment.
Moving to Home, a list of restaurant will be appear. When the user tap on any restaurant from the list, an activity( name ReservationInfo ) will be opened. There are 3 edit text fields and a button in ReservationInfo activity. When the user click on the button it will move to the fragment(Reservation) which is placed on third position of bottom nav bar.
The question is how to move from activity to fragmentand the fragment is set to the 3rd menu item of the bottom navigation bar.
Here is the code:
Resrvation.java
package restaurantlocator.application;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
public class Resrvation extends AppCompatActivity {
Button reserve;
ImageButton imageButton;
EditText food, chooseTime, date;
DataBaseHelper db;
// ReservationInfo reservationInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_resrvation);
db = new DataBaseHelper(this);
food = (EditText) findViewById(R.id.etfood);
chooseTime = (EditText) findViewById(R.id.ettime);
date = (EditText) findViewById(R.id.edate);
reserve = (Button) findViewById(R.id.btnreserve);
imageButton = (ImageButton) findViewById(R.id.imgButton);
imageButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
finish();
}
});
//reservationInfo = new ReservationInfo();
reserve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!emptyValidation()) {
db.AddData(new Data(food.getText().toString(),
chooseTime.getText().toString(),
date.getText().toString()));
AlertMessage();
food.setText(null);
chooseTime.setText(null);
date.setText(null);
} else {
Toast.makeText(Resrvation.this, "Empty Fields", Toast.LENGTH_SHORT).show();
}
}
private void AlertMessage() {
AlertDialog.Builder builder = new AlertDialog.Builder(Resrvation.this);
builder.setTitle("Reserved!");
builder.setMessage("A notification will be send on your device regarding your reservation.");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//move to fragment ReservationInfo
}
});
builder.show();
}
});
}
private boolean emptyValidation() {
if (TextUtils.isEmpty(food.getText().toString()) || TextUtils.isEmpty(chooseTime.getText().toString())) {
return true;
} else {
return false;
}
}
}
BottomNavigation.java
package restaurantlocator.application;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.FrameLayout;
public class BottomNavigation extends AppCompatActivity {
private BottomNavigationView mMianNav;
private FrameLayout mMainFrame;
private HomeActivity homeActivity;
private ReservationInfo reservationInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bottom_navigation);
startService(new Intent(this, NotificationService.class));
mMainFrame = (FrameLayout) findViewById(R.id.main_frame);
mMianNav = (BottomNavigationView) findViewById(R.id.main_nav);
homeActivity = new HomeActivity();
reservationInfo = new ReservationInfo();
setFragment(homeActivity);
//Listener for handling selection events on bottom navigation items
mMianNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.tohome:
setFragment(homeActivity);
return true;
case R.id.toresrvation:
setFragment(reservationInfo);
return true;
case R.id.tologout:
logout();
return true;
default:
return false;
}
}
private void logout() {
Intent intent = new Intent(BottomNavigation.this, Registration.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
});
}
private void setFragment(Fragment fragment) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_frame, fragment);
fragmentTransaction.commit();
fragmentTransaction.addToBackStack(null);
}
public void onBackPressed() {
Intent homeIntent = new Intent(Intent.ACTION_MAIN);
homeIntent.addCategory(Intent.CATEGORY_HOME);
homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homeIntent);
finish();
}
}
Solution:
Follow the steps below:
Step1: Add the lines as shown in below reserve click listener
reserve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
....
....
Intent intent = new Intent(Resrvation.this, BottomNavigation.class);
intent.putExtra("FromReservation", "1");
startActivity(intent);
....
}
}
Next, Step2: In your write the below code in onCreate() of BottomNavigation class:
Intent i = getIntent();
String data = i.getStringExtra("FromReservation");
if (data != null && data.contentEquals("1")) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_frame, new ReservationInfo());
fragmentTransaction.commitNow();
mMianNav.setSelectedItemId(R.id.toresrvation);
}
Try it, If any problem, do comment below.
All you need to do is just use startActivityForResults instead of startActivity when user selects a restaurant from your home fragment.
e.g :
startActivityForResult(yourIntent, 1000);
And on the reservationInfo Activity in the onClick function use
Intent returnIntent = new Intent();
setResult(Activity.RESULT_CANCELED, returnIntent);
finish();
And then in your first activity override onActivityResult() method and set the selected fragment as reservation if request code matches
e.g:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1000) {
mMianNav.setSelectedItemId(R.id.toresrvation);
}
}
I have tried a lot of times and in different ways to pass a string from one activity (LoginActivity) to another one (SettingsActivity). Of course I did a lot of research and tried each provided solution, but nothing could help me until now
LoginActivity.class:
package com.naderk.pds;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.kosalgeek.genasync12.AsyncResponse;
import com.kosalgeek.genasync12.PostResponseAsyncTask;
import com.naderk.pds.contexts.ContextServerActivity;
import java.util.HashMap;
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
final String LOG = "LoginActivity";
Button btnLogin, btnRegister;
EditText etUsername, etPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnRegister = (Button) findViewById(R.id.bRegister);
btnLogin.setOnClickListener(this);
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent seeTasksIntent= new Intent(LoginActivity.this, RegisterActivity.class);
LoginActivity.this.startActivity(seeTasksIntent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View view) {
HashMap postData = new HashMap();
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
postData.put("txtUsername", username);
postData.put("txtPassword", password);
PostResponseAsyncTask task1 = new PostResponseAsyncTask(LoginActivity.this, postData, new AsyncResponse() {
#Override
public void processFinish(String s) {
Log.d(LOG, s);
if(s.contains("success")){
Toast.makeText(LoginActivity.this, "Login successful", Toast.LENGTH_LONG).show();
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(LoginActivity.this, "Wrong username or password. Please register and try again.", Toast.LENGTH_LONG).show();
}
}
});
task1.execute("http://192.168.0.11/customer/");
visitactivity1();
}
public void visitactivity1() {
Intent i = new Intent(LoginActivity.this, SettingsActivity.class);
Bundle bundle = new Bundle();
bundle.putString("key", etUsername.getText().toString());
i.putExtras(bundle);
startActivity(i);
finish();
}
}
SettingsActivity.class:
package com.naderk.pds;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.content.Intent;
public class SettingsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
TextView textView = (TextView) findViewById(R.id.tvUserName);
Bundle bundle = getIntent().getExtras();
String stuff = bundle.getString("key");
textView.setText(stuff);
}
}
Logcat:
Exceeds 30.000 characters lol
I really hope that someone is able to help me.
Cheers!
Try this
public void visitactivity1() {
Intent i = new Intent(LoginActivity.this, SettingsActivity.class);
i.putExtra("key", etUsername.getText().toString());
startActivity(i);
finish();
}
and on the second activity
public class SettingsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
TextView textView = (TextView) findViewById(R.id.tvUserName);
String stuff = getIntent().getStringExtra("key");
textView.setText(stuff);
}
}
Hope it helps (:
You can add the putExtras
if(s.contains("success")){
Toast.makeText(LoginActivity.this, "Login successful", Toast.LENGTH_LONG).show();
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra("passwordText", password.getText().toString());
intent.putExtra("usernameText",username.getText().toString());
startActivity(intent);
On your second activity implement the following within your onCreate() method
Intent intent = getIntent();
String password = intent.getStringExtra("passwordText");
String username = intent.getSringExtra("usernameText");
You can read this blog for more information about intents : What are intents
In summary is a tutorial about how to implement intents. It may help you in case you want to change your structure.
Finally, I´m not sure if this is the way you wanted to pass the data : instead use it as I recommend. I hope it helps !
postData.put("txtUsername", username);
postData.put("txtPassword", password);
You can use Bundle methods to to send and receive Strings across your Activity class.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have 1 problem and Who can help me?.
I have 1 Activity run when start App
package com.example.khuatduytan.doantotnghiep;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.Serializable;
public class MainActivity extends AppCompatActivity {
DatabaseHelper db;
Button btnLogin, btnRegister, btnFindPassword;
EditText editUsername, editPassword;
private static final int REQUEST_CODE = 10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DatabaseHelper(this);
btnLogin = (Button) findViewById(R.id.button_login);
btnRegister = (Button) findViewById(R.id.button_register);
btnFindPassword = (Button) findViewById(R.id.button_findPassword);
editUsername = (EditText) findViewById(R.id.editText_username);
editPassword = (EditText) findViewById(R.id.editText_password);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarActivity);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Đăng nhập");
Login();
Register();
FindPassword();
}
public void Login(){
btnLogin.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor res = db.getDataTableUser();
int temp = 1;
if (res.getCount() == 0) {
showMessage("Error", "Tài khoản không tồn tại");
return;
}
while (res.moveToNext()) {
String username, password, idUser;
idUser = res.getString(0);
username = res.getString(1);
password = res.getString(2);
if (editUsername.getText().toString().equals(username) == true&&editPassword.getText().toString().equals(password) == true) {
doOpenManagePage(idUser);
temp = 0;
break;
}
}
if (temp==1){
showMessage("Error", "Account does not exist");
}
}
}
);
}
public void Register(){
btnRegister.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v) {
doOpenRegister();
}
}
);
}
public void FindPassword(){
btnFindPassword.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v) {
doOpenFindPasswordStep1();
}
}
);
}
public void doOpenRegister(){
Intent newIntent = new Intent(this, Register.class);
startActivity(newIntent);
}
public void doOpenFindPasswordStep1(){
Intent newIntent = new Intent(this, FindPasswordStep1.class);
startActivity(newIntent);
}
public void doOpenManagePage(String idUser){
Intent newIntent = new Intent(this, ManagePage.class);
newIntent.putExtra("IdUser", idUser);
startActivityForResult(newIntent, REQUEST_CODE);
}
public void showMessage(String title, String Message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_manage_page, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_logout) {
return true;
}
else if (id==R.id.action_search){
return true;
}
return super.onOptionsItemSelected(item);
}
}
Then it send IdUser to this Activity
package com.example.khuatduytan.doantotnghiep;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
public class ManagePage extends AppCompatActivity{
private static final int REQUEST_CODE = 10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manage_page);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.add_note);
Bundle extras = getIntent().getExtras();
final String idUser = extras.getString("IdUser");
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
doOpenInsertNote(idUser);
}
});
}
public String getIdUser(){
Bundle extras = getIntent().getExtras();
String idUser = extras.getString("IdUser");
return idUser;
}
public void doOpenInsertNote(String idUser){
Intent newIntent = new Intent(this, InsertNote.class);
newIntent.putExtra("IdUser", idUser);
startActivityForResult(newIntent, REQUEST_CODE);
}
}
When i run it 1st time, this app is ok, it can go to next Activity
package com.example.khuatduytan.doantotnghiep;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.Calendar;
public class InsertNote extends AppCompatActivity implements View.OnClickListener {
private ImageButton insertDate;
private Calendar cal;
private int day;
private int month;
private int year;
private EditText et, content_InsertNote, money_InsertNote;
private Button btnSubmitNote, btnCancelNote;
private Spinner SelectTypeNote;
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert_note);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
insertDate = (ImageButton) findViewById(R.id.dateInsert);
cal = Calendar.getInstance();
et = (EditText) findViewById(R.id.dateInsert_editText);
btnSubmitNote = (Button) findViewById(R.id.insertNote);
btnCancelNote = (Button) findViewById(R.id.cancelNote);
content_InsertNote = (EditText) findViewById(R.id.noiDung);
money_InsertNote = (EditText) findViewById(R.id.soTien);
SelectTypeNote = (Spinner) findViewById(R.id.loai);
db = new DatabaseHelper(this);
cal = Calendar.getInstance();
day = cal.get(Calendar.DAY_OF_MONTH);
month = cal.get(Calendar.MONTH);
year = cal.get(Calendar.YEAR);
insertDate.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
final String idUser = extras.getString("IdUser");
setBtnSubmitNote(idUser);
setBtnCancelNote();
}
#Override
public void onClick(View v) {
showDialog(0);
}
#Override
#Deprecated
protected Dialog onCreateDialog(int id) {
return new DatePickerDialog(this, datePickerListener, year, month, day);
}
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
et.setText(selectedDay + " / " + (selectedMonth + 1) + " / " + selectedYear);
}
};
private void setBtnSubmitNote(final String idUser){
btnSubmitNote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
confirmDialog(idUser);
}
});
}
private void setBtnCancelNote(){
Intent newIntent = new Intent(this, ManagePage.class);
startActivity(newIntent);
}
private void confirmDialog(final String idUser) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder
.setMessage("Are you sure?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
String date = null, content = null, money = null, TypeNote_Selected;
int Type_Note = 0, id_User;
id_User = Integer.parseInt(idUser);
date = et.getText().toString();
content = content_InsertNote.getText().toString();
money = money_InsertNote.getText().toString();
TypeNote_Selected = SelectTypeNote.getSelectedItem().toString();
if(TypeNote_Selected.equals("Thu")){
Type_Note = 0;
} else{
Type_Note = 1;
}
if(date.equals("")||content.equals("")||money.equals("")){
Toast.makeText(InsertNote.this, "Bạn chưa nhập đủ dữ liệu", Toast.LENGTH_LONG).show();
}
else {
long isInserted = db.insertNoteTable(date, content, Type_Note, money, id_User);
if (isInserted == -1) {
Toast.makeText(InsertNote.this, "Thêm ghi chú không thành công", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(InsertNote.this, "Thêm ghi chú thành công", Toast.LENGTH_LONG).show();
}
}
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
})
.show();
}
}
`
But when i run it second time, When i click button to open Activity
InsertNote, I receive a error
03-26 16:12:32.161 2614-2614/? E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.khuatduytan.doantotnghiep/com.example.khuatduytan.doantotnghiep.ManagePage}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.khuatduytan.doantotnghiep.ManagePage.onCreate(ManagePage.java:21)
at android.app.Activity.performCreate(Activity.java:5104)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
I tried to print what i send from Activity Main to Activity ManagePage by Toast, it display exactly what i want to send.
But i dont know why this error display.
Can you help me?
Sorry about my English
You call setBtnCancelNote() method in the onCreate() method of your InsertNote activity. so as soon as InsertNote starts it tries to launch the ManagePage activity.
The problem is your ManagePage activity expects the value IdUser in the bundle received from the intent. But you do not pass this value to ManagePage activity when you start it from InsertNote activity.
You probably want to add this line to your setBtncancelNote() method in InsertPage activity -
newIntent.putExtra("IdUser", //The Values here);
If you pass this value then ManageNote will not crash.
please add more info like line numbers, otherwise its difficult to debug it remotely ..
Anyway, my guess is you have to check for null pointers when you do stuff like getIntent().getExtras()
just put some breakpoints there, and step by step and you'll figure it out