i want to change my start activity for actvity MainActivity to TuserActivity. i declared these line in my manifest:
<activity android:name=".TuserActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
But i got NullPointerException while running the application, how can i slove this problem?
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.krushi/com.example.krushi.TuserActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.TextView.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.TextView.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference
at com.example.krushi.TuserActivity.onCreate(TuserActivity.java:44)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
TuserActivity:
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class TuserActivity extends AppCompatActivity {
private EditText tphnumber;
Button btSend;
TextView tEmail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tuser);
tphnumber = findViewById(R.id.tphone);
btSend = findViewById(R.id.btSend);
btSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mobile = tphnumber.getText().toString().trim();
if(mobile.isEmpty() || mobile.length() < 10){
tphnumber.setError("Enter a valid mobile");
tphnumber.requestFocus();
return;
}
Intent intent = new Intent(TuserActivity.this, VerifyPhoneActivity.class);
intent.putExtra("mobile", mobile);
startActivity(intent);
}
});
tEmail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(TuserActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
}
MainActivity:
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
public EditText emailId, passwd;
Button btnSignUp;
TextView signIn,txuser;
FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuth = FirebaseAuth.getInstance();
emailId = findViewById(R.id.ETemail);
passwd = findViewById(R.id.ETpassword);
btnSignUp = findViewById(R.id.btnSignUp);
signIn = findViewById(R.id.TVSignIn);
txuser = findViewById(R.id.tuser);
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String emailID = emailId.getText().toString();
String paswd = passwd.getText().toString();
if (emailID.isEmpty()) {
emailId.setError("Enter your E-mail");
emailId.requestFocus();
} else if (paswd.isEmpty()) {
passwd.setError("Enter your password");
passwd.requestFocus();
} else if (emailID.isEmpty() && paswd.isEmpty()) {
Toast.makeText(MainActivity.this, "Fields Empty!", Toast.LENGTH_SHORT).show();
} else if (!(emailID.isEmpty() && paswd.isEmpty())) {
firebaseAuth.createUserWithEmailAndPassword(emailID, paswd).addOnCompleteListener(MainActivity.this, new OnCompleteListener() {
#Override
public void onComplete(Task task) {
if (!task.isSuccessful()) {
Toast.makeText(MainActivity.this.getApplicationContext(),
"SignUp unsuccessful: " + task.getException().getMessage(),
Toast.LENGTH_SHORT).show();
} else {
startActivity(new Intent(MainActivity.this, UserActivity.class));
}
}
});
} else {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
}
});
signIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent I = new Intent(MainActivity.this, Activity_Login.class);
startActivity(I);
}
});
txuser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent I = new Intent(MainActivity.this, TuserActivity.class);
startActivity(I);
}
});
}
}
hey you missing the initiate tEmail textview
please add this to the TuserActivity.java before call tEmail.setOnClickListener()
tEmail = findViewById(R.id...);
You have to initialize tEmail before using it.
tEmail = findViewById(R.id.tEmail);
The final initializing block should be like
tphnumber = findViewById(R.id.tphone);
btSend = findViewById(R.id.btSend);
tEmail = findViewById(R.id.tEmail);
In TuserActivity, your code is failing at:
tEmail.setOnClickListener(...)
... because you never instantiated tEmail.
you need to find the view by calling :
tEmail = findViewById(...);
Hope this helps.
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'm working on a login register kinda app using Firebase on Android Studio. It builds just fine, but when I run it on my phone, the launcher activity works but the problem occurs when I use my button to access my Firebase login activity. My logcat is given below with my launcher activity code and login activity code. How do I resolve the exceptions and stack traces in my logcat?
My login activity:
package com.delaroystudios.database;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class Teacher extends AppCompatActivity {
private EditText inputEmail, inputPassword;
private FirebaseAuth auth;
private ProgressBar progressBar;
private Button btnSignup, btnLogin, btnReset;
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
if (auth.getCurrentUser() != null) {
startActivity(new Intent(Teacher.this, MainActivity.class));
finish();
}
// set the view now
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
btnSignup = (Button) findViewById(R.id.btn_signup);
btnLogin = (Button) findViewById(R.id.btn_login);
btnReset = (Button) findViewById(R.id.btn_reset_password);
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
btnSignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Teacher.this, SignupActivity.class));
}
});
btnReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Teacher.this, ResetPasswordActivity.class));
}
});
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = inputEmail.getText().toString();
final String password = inputPassword.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
//authenticate user
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(Teacher.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
progressBar.setVisibility(View.GONE);
if (!task.isSuccessful()) {
// there was an error
if (password.length() < 6) {
inputPassword.setError(getString(R.string.minimum_password));
} else {
Toast.makeText(Teacher.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
}
} else {
Intent intent = new Intent(Teacher.this, Login.class);
startActivity(intent);
finish();
}
}
});
}
});
}
}
My launcher activity:
package com.delaroystudios.database;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.view.menu.MenuAdapter;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final Button bstudent = (Button) findViewById(R.id.bstudent);
final Button bteacher = (Button) findViewById(R.id.bteacher);
bstudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent stuintent = new Intent(MainActivity.this,Student.class);
MainActivity.this.startActivity(stuintent);
}
});
bteacher.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent teaintent = new Intent(MainActivity.this,Teacher.class);
MainActivity.this.startActivity(teaintent);
}
});
}
}
MY logcat after the app crash:
06-26 20:38:31.327 18100-18100/com.delaroystudios.database E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.delaroystudios.database, PID: 18100
Theme: themes:{default=overlay:com.ngocgiap.hightlifelight, iconPack:com.ngocgiap.hightlifelight, fontPkg:com.ngocgiap.hightlifelight, com.android.systemui=overlay:com.ngocgiap.hightlifelight, com.android.systemui.navbar=overlay:com.ngocgiap.hightlifelight}
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.delaroystudios.database/com.delaroystudios.database.Teacher}: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2450)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2510)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5461)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
at android.support.v7.app.AppCompatDelegateImplV9.setSupportActionBar(AppCompatDelegateImplV9.java:207)
at android.support.v7.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:130)
at com.delaroystudios.database.Teacher.onCreate(Teacher.java:44)
at android.app.Activity.performCreate(Activity.java:6251)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2403)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2510)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5461)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Im working on Websocket android application. I want to create Register and Login application with websocket. I am able to connect to websocket server with websocket android project. I have created Register,Login activity with online reference.In register Activity, when I'm storing Registered data to Server using "send" method of websocketclient Java Class I'm getting "java.lang.NullPointerException: Attempt to invoke virtual method 'void org.java_websocket.client.WebSocketClient.send(java.lang.String)' on a null object reference" Error on my Log-cat window.
here is my Main Activity:
package org.asperohgedgetws.a7.hgadgetws;
import android.app.Activity;
import android.app.Fragment;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
import java.net.URISyntaxException;
import android.widget.Button;
import android.widget.Toast;
import android.content.Intent;
public class MainActivity extends Activity implements View.OnClickListener {
Button bLogout;
UserLocalStore userLocalStore;
private WebSocketClient mWebSocketClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bLogout = (Button) findViewById(R.id.bLogout);
bLogout.setOnClickListener(this);
userLocalStore = new UserLocalStore(this);
connectWebSocket();
}
#Override
protected void onStart() {
super.onStart();
if (authenticate()== true){
displayUserDetails();
} else{
Toast.makeText(getApplicationContext(), "Not Registered User :(", Toast.LENGTH_SHORT).show();
startActivity(new Intent(MainActivity.this,Login.class));
}
}
private boolean authenticate(){
return userLocalStore.getUserLoggedIn();
}
private void displayUserDetails(){
User user = userLocalStore.getLoggedInUser();
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.bLogout:
startActivity(new Intent(this,Login.class));
userLocalStore.clearUserData();
userLocalStore.setUserLoggedIn(false);
Toast.makeText(getApplicationContext(), "Logout :)", Toast.LENGTH_SHORT).show();
break;
}
}
private void connectWebSocket() {
URI uri;
try {
uri = new URI("ws://xxx.xxx.xxx.xxx:xxxx");
} catch (URISyntaxException e) {
e.printStackTrace();
return;
}
mWebSocketClient = new WebSocketClient(uri) {
#Override
public void onOpen(ServerHandshake serverHandshake) {
Log.i("Websocket", "Opened");
//mWebSocketClient.send("Hello from " + Build.MANUFACTURER + " " + Build.MODEL);
mWebSocketClient.send("{\"1512BD002\":\"SO#0\":\"2\"}");
}
#Override
public void onMessage(String s) {
final String message = s;
runOnUiThread(new Runnable() {
#Override
public void run() {
//TextView textView = (TextView)findViewById(R.id.messages);
//textView.setText(textView.getText() + "\n" + message);
}
});
}
#Override
public void onClose(int i, String s, boolean b) {
Log.i("Websocket", "Closed " + s);
}
#Override
public void onError(Exception e) {
Log.i("Websocket", "Error " + e.getMessage());
}
};
mWebSocketClient.connect();
}
public void sendMessage(View view) {
// EditText editText = (EditText)findViewById(R.id.message);
// mWebSocketClient.send(editText.getText().toString());
//editText.setText("");
}
}
RegisterActivity
package org.asperohgedgetws.a7.hgadgetws;
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.EditText;
import android.widget.Toast;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.java_websocket.client.WebSocketClient;
public class Register extends AppCompatActivity implements View.OnClickListener {
Button bRegister;
EditText etName, etAge, etUsername, etPassword;
WebSocketClient nwebsocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
etName = (EditText) findViewById(R.id.etName);
etAge = (EditText) findViewById(R.id.etAge);
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
bRegister = (Button) findViewById(R.id.bRegister);
bRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bRegister:
// Toast.makeText(getApplicationContext(), "Register", Toast.LENGTH_SHORT).show();
String name = etName.getText().toString();
int age = Integer.parseInt(etAge.getText().toString());
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
User user = new User(name, age, username, password);
registerUser(user);
break;
}
}
private void registerUser(User user) {
String strtosend = "";
JSONObject object = new JSONObject();
try {
// Add the id to the json
object.put("name", user.name);
object.put("age", user.age);
object.put("username", user.username);
object.put("password", user.password);
strtosend = object.toString();
} catch (JSONException e) {
// Handle impossible error
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), strtosend, Toast.LENGTH_SHORT).show();
nwebsocket.send("Hi!");
Intent loginIntent = new Intent(Register.this, Login.class);
startActivity(loginIntent);
}
}
Logcat Output:
05-27 11:49:54.331 19459-19459/org.asperohgedgetws.a7.hgadgetws E/AndroidRuntime: FATAL EXCEPTION: main
Process: org.asperohgedgetws.a7.hgadgetws, PID: 19459
java.lang.NullPointerException: Attempt to invoke virtual method 'void org.java_websocket.client.WebSocketClient.send(java.lang.String)' on a null object reference
at org.asperohgedgetws.a7.hgadgetws.Register.registerUser(Register.java:73)
at org.asperohgedgetws.a7.hgadgetws.Register.onClick(Register.java:51)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Do I have to use again below code in Registered activity?
private void connectWebSocket() {
URI uri;
try {
uri = new URI("ws://xxx.xxx.xxx.xxx:xxxx");
} catch (URISyntaxException e) {
e.printStackTrace();
return;
}
nWebsocketClient = new WebSocketClient(uri) {
#Override
public void onOpen(ServerHandshake serverHandshake) {
Log.i("Websocket", "Opened");
}
#Override
public void onMessage(String s) {
final String message = s;
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}
#Override
public void onClose(int i, String s, boolean b) {
Log.i("Websocket", "Closed " + s);
}
#Override
public void onError(Exception e) {
Log.i("Websocket", "Error " + e.getMessage());
}
};
nWebsocketClient.connect();
}
The problem is that your nwebsocket is never initialized, its value is null and that's why you get this error when trying to execute the send method.
You need to initialize it somewhere:
nwebsocket = new WebSocketClient(...);
NB: If you want to share the same instance of WebSocketClient between MainActivity and Register activity, you could make it public static in MainActivity
public static WebSocketClient mWebSocketClient;
Then remove your WebSocketClient nwebsocket from Register and use MainActivity.mWebSocketClient instead.
this is error m getting.. i have interview.. n i need to show this app.. but getting error.. plz help.. the app was running an hour back fluently.. i was trying to put logout button on main activity to come back on login activity but lost login button function itself...
01-18 11:59:14.938 7321-7321/info.androidhive.materialdesign E/AndroidRuntime: FATAL EXCEPTION: main
Process: info.androidhive.materialdesign, PID: 7321
java.lang.RuntimeException: Unable to start activity ComponentInfo{info.androidhive.materialdesign/info.androidhive.materialdesign.activity.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2373)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2435)
at android.app.ActivityThread.access$900(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1324)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5375)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at info.androidhive.materialdesign.activity.MainActivity.onClickButtonListener3(MainActivity.java:51)
at info.androidhive.materialdesign.activity.MainActivity.onCreate(MainActivity.java:45)
at android.app.Activity.performCreate(Activity.java:6865)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2326)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2435)
at android.app.ActivityThread.access$900(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1324)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5375)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
this is my Login.java
package info.androidhive.materialdesign.activity;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.content.Intent;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import info.androidhive.materialdesign.R;
import info.androidhive.materialdesign.db.sqlitedb;
public class Login extends Activity {
sqlitedb sqlitehelper;
SQLiteDatabase db;
private static Button btn_login, btn_back;
EditText emailEditText, passwordEditText;
int i;
int flag;
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btn_login = (Button) findViewById(R.id.login_1);
emailEditText = (EditText)findViewById(R.id.uemail);
passwordEditText = (EditText)findViewById(R.id.upass);
sqlitehelper = new sqlitedb(getApplicationContext());
db = sqlitehelper.getWritableDatabase();
onClickButtonListener1();
onClickButtonListener2();
btn_login.setClickable(true);
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
public void onClickButtonListener1()
{
btn_back = (Button)findViewById(R.id.back_1);
btn_back.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// Intent i = new Intent("info.androidhive.materialdesign.activity.Home");
// startActivity(i);
finish();
}
}
);
}
public void onClickButtonListener2()
{
btn_login = (Button) findViewById(R.id.login_1);
btn_login.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
onLoginClick(v);
}
}
);
}
public void onLoginClick(View v) {
if (v.getId() == R.id.login_1)
{
String contactEmail = emailEditText.getText().toString();
String contactPassword = passwordEditText.getText().toString();
String password = sqlitehelper.getSingleEntry(contactEmail);
if (contactPassword.equals(password))
{
Intent i = new Intent("info.androidhive.materialdesign.activity.MainActivity");
startActivity(i);
finish();
}
else
{
Toast temp = Toast.makeText(Login.this, "Email and password don't match", Toast.LENGTH_SHORT);
temp.show();
}
}
}
}
You initialize the login button in the onCreate() here:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btn_login = (Button) findViewById(R.id.login_1);
and then you call the onClickButtonListener2(); in which you initialize the button again in here:
public void onClickButtonListener2()
{
btn_login = (Button) findViewById(R.id.login_1);
So just do this:
call this onClickButtonListener2(); method in onCreate() and modify code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btn_login = (Button) findViewById(R.id.login_1);
emailEditText = (EditText)findViewById(R.id.uemail);
passwordEditText = (EditText)findViewById(R.id.upass);
sqlitehelper = new sqlitedb(getApplicationContext());
db = sqlitehelper.getWritableDatabase();
btn_login.setClickable(true);
onClickButtonListener1();
onClickButtonListener2();
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
and change the onClickButtonListener2(); to:
public void onClickButtonListener2(){
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String contactEmail = emailEditText.getText().toString();
String contactPassword = passwordEditText.getText().toString();
String password = sqlitehelper.getSingleEntry(contactEmail);
if (contactPassword.equals(password)){
Intent i = new Intent("info.androidhive.materialdesign.activity.MainActivity");
startActivity(i);
YourActivity.this.finish();
}else{
Toast temp = Toast.makeText(Login.this, "Email and password don't match", Toast.LENGTH_SHORT);
temp.show();
}
}
}
);
}
Hope it helps!!!
When I click on the menu button I want to return to the main menu, activity with which the app starts with. What must follow the app.mobiledevicesecurity part? I thought it must be the starting class name? I am new to android studio development. Any help will be appreciated.
Logcat details:
09-01 19:02:04.755 1988-1988/app.mobiledevicesecurity E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: app.mobiledevicesecurity, PID: 1988
android.content.ActivityNotFoundException: No Activity found to handle Intent { act=app.mobiledevicesecurity.MainActivity }
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1781)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1501)
at android.app.Activity.startActivityForResult(Activity.java:3745)
at android.app.Activity.startActivityForResult(Activity.java:3706)
at android.app.Activity.startActivity(Activity.java:4016)
at android.app.Activity.startActivity(Activity.java:3984)
at app.mobiledevicesecurity.Result$2.onClick(Result.java:46)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Result.java:
package app.mobiledevicesecurity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Result extends Activity
{
private static Button playbtn;
private static Button menubutton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
OnClickPlayButtonListener();
OnClickMenuButtonListener();
TextView textResult = (TextView) findViewById(R.id.textResult);
Bundle b = getIntent().getExtras();
int score = b.getInt("score");
textResult.setText("You scored" + " " + score + " for the quiz.");
}
public void OnClickPlayButtonListener() {
playbtn = (Button) findViewById(R.id.btn);
playbtn.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.Quiz");
startActivity(intent);
}
}
);
}
public void OnClickMenuButtonListener() {
menubutton = (Button) findViewById(R.id.menubtn);
menubutton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.MainActivity");
startActivity(intent);
}
}
);
}
}
Any suggestions with what I must replace the MainActivity text?
try to put like this:
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
this works for me...