Not able to start activity in android - android

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!!!

Related

NullPointerException whlie changing startactivity

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.

firebase login register app crash

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)

Firebase error "invoke virtual method" on null object when object should be initialized

I keep getting a null object error and my app crashes, though I don't see why there should be an error. I have looked at other examples and those are all the same, and don't help with my issue. My issue occurring although from what I have seen it shouldn't be. The code is:
package com.example.matthew.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
import static android.content.ContentValues.TAG;
public class makecharact extends Activity {
Button retur, mak, cont;
FirebaseUser user;
DataSnapshot datasss;
Spinner spinner2;
List<String> list = new ArrayList<String>();
String id;
DatabaseReference myRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.charlist);
Intent task = getIntent();
retur = (Button) findViewById(R.id.returnToLast);
mak = (Button) findViewById(R.id.make);
cont = (Button) findViewById(R.id.Conti);
addListenerOnButton();
ValueEventListener postListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
datasss = dataSnapshot;
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
myRef = FirebaseDatabase.getInstance().getReference();
user = FirebaseAuth.getInstance().getCurrentUser();
Log.d("Test Point 1", "Got to line 61 at the least");
id = user.getUid();
int check = 0;
boolean done = false;
Log.d("User ID", id);
while(done == false) {
String sCheck = Integer.toString(check);
if (datasss.hasChild(id) == true){
if(datasss.child(id).hasChild("Character List") == true){
if (datasss.child(id).child("Character List").hasChild(sCheck) == true) {
list.add(datasss.child(id).child("Character List").child(sCheck).getValue().toString());
check = check + 1;
}else{
done = false;
}
}else{
list.add("No characters");
done = true;
}
}
}
ArrayAdapter<String> dataset = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, list);
dataset.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(dataset);
Log.d("Test Point 2", "Got to line 77 at the least");
}
public void addListenerOnButton() {
cont.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
String stats;
stats = spinner2.getSelectedItem().toString();
myRef.child(id).child("Current Character").setValue(stats);
Intent TaskIntent = new Intent(getApplicationContext(), MainScreen.class);
startActivity(TaskIntent);
finish();
}
});
mak.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Log.d(TAG, "Moving");
Intent TaskIntent = new Intent(getApplicationContext(), spinner.class);
startActivity(TaskIntent);
finish();
}
});
retur.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "Moving");
finish();
}
});
}
}
My logcat shows:
05-31 21:05:39.802 14318-14318/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.matthew.myapplication, PID: 14318
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.matthew.myapplication/com.example.matthew.myapplication.makecharact}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.google.firebase.database.DataSnapshot.hasChild(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3253)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349)
at android.app.ActivityThread.access$1100(ActivityThread.java:223)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7223)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.google.firebase.database.DataSnapshot.hasChild(java.lang.String)' on a null object reference
at com.example.matthew.myapplication.makecharact.addListenerOnButton(makecharact.java:81)
at com.example.matthew.myapplication.makecharact.onCreate(makecharact.java:45)
at android.app.Activity.performCreate(Activity.java:6877)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3206)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349) 
at android.app.ActivityThread.access$1100(ActivityThread.java:223) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:7223) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 
I have tried a lot though I still don't get why it isn't working. Any help is appreciated, even if it is it's already been solved on another post (which i couldn't find with a link to said post. Thanks
Yes it will return Null pointer exception Because your variable dataass not initialized.
and its is initialized only when ValueEventListener() is triggers onDataChange() So you need to execute every thing inside the onDataChange()
ValueEventListener postListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
datasss = dataSnapshot;myRef = FirebaseDatabase.getInstance().getReference();
user = FirebaseAuth.getInstance().getCurrentUser();
Log.d("Test Point 1", "Got to line 61 at the least");
id = user.getUid();
int check = 0;
boolean done = false;
Log.d("User ID", id);
while(done == false) {
String sCheck = Integer.toString(check);
if (datasss.hasChild(id) == true){
if(datasss.child(id).hasChild("Character List") == true){
if (datasss.child(id).child("Character List").hasChild(sCheck) == true) {
list.add(datasss.child(id).child("Character List").child(sCheck).getValue().toString());
check = check + 1;
}else{
done = false;
}
}else{
list.add("No characters");
done = true;
}
}
}
ArrayAdapter<String> dataset = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, list);
dataset.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(dataset);
Log.d("Test Point 2", "Got to line 77 at the least");
}
You can get firebase data like this.
DatabaseReference databaseTracks;
List<Track> tracks;
databaseTracks = FirebaseDatabase.getInstance().getReference("tracks").child(intent.getStringExtra(MainActivity.ARTIST_ID));
#Override
protected void onStart() {
super.onStart();
databaseTracks.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
tracks.clear();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Track track = postSnapshot.getValue(Track.class);
tracks.add(track);
}
TrackList trackListAdapter = new TrackList(ArtistActivity.this, tracks);
listViewTracks.setAdapter(trackListAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}

Return to main menu when clicking on button

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...

No errors in Android studio but application crashes

I am new to android development and tried to make a simple calculator app. The last thing that I changed was try to concatenate two string into one and display the new string in the EditText. There are no errors in my project when I look at it in Android Studio, however when I run the application on my phone it stops working. Is this a phone problem or ... ?
package com.example.jeff.calculator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
double total = 0;
double transaction = 0;
String Back = "";
String currentString = "";
String transactionString = "";
EditText calcInput = (EditText) findViewById(R.id.EtCalc);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonSetup();
}
private void concatenation() {
transactionString = transactionString + currentString;
calcInput.setText(String.valueOf(transactionString));
}
private void buttonSetup() {
Button button0 = (Button) findViewById(R.id.Btn0);
Button button1 = (Button) findViewById(R.id.Btn1);
Button button2 = (Button) findViewById(R.id.Btn2);
Button button3 = (Button) findViewById(R.id.Btn3);
Button button4 = (Button) findViewById(R.id.Btn4);
Button button5 = (Button) findViewById(R.id.Btn5);
Button button6 = (Button) findViewById(R.id.Btn6);
Button button7 = (Button) findViewById(R.id.Btn7);
Button button8 = (Button) findViewById(R.id.Btn8);
Button button9 = (Button) findViewById(R.id.Btn9);
button0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentString = "0";
calcInput.setText(String.valueOf(transactionString));
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentString = "1";
concatenation();
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentString = "2";
concatenation();
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentString = "3";
concatenation();
}
});
button4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentString = "4";
concatenation();
}
});
button5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentString = "5";
concatenation();
}
});
button6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentString = "6";
concatenation();
}
});
button7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentString = "7";
concatenation();
}
});
button8.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentString = "8";
concatenation();
}
});
button9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentString = "9";
concatenation();
}
});
// (EditText) inputTxt = (EditText) findViewById(R.id.input);
// Store EditText in Variable
// String str = inputTxt.getText().toString();
}
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);
}
}
LOGCAT
09-07 23:54:12.649 22823-22823/com.example.jeff.calculator I/art﹕ Late-enabling -Xcheck:jni
09-07 23:54:12.718 22823-22823/com.example.jeff.calculator D/AndroidRuntime﹕ Shutting down VM
09-07 23:54:12.719 22823-22823/com.example.jeff.calculator E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.jeff.calculator, PID: 22823
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.jeff.calculator/com.example.jeff.calculator.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2290)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2442)
at android.app.ActivityThread.access$800(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1351)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5373)
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:1020)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
at android.app.Activity.findViewById(Activity.java:2072)
at com.example.jeff.calculator.MainActivity.<init>(MainActivity.java:22)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2280)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2442)
            at android.app.ActivityThread.access$800(ActivityThread.java:156)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1351)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:211)
            at android.app.ActivityThread.main(ActivityThread.java:5373)
            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:1020)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815)
Do not call methods that you are inheriting from Activity until after super.onCreate() has been called, unless specifically told otherwise.
Also, you cannot call findViewById() until you call setContentView(), as there are no widgets to find.
Replace:
EditText calcInput = (EditText) findViewById(R.id.EtCalc);
with:
EditText calcInput;
and add:
calcInput = (EditText) findViewById(R.id.EtCalc);
after your call to setContentView() in onCreate().
You are defining a variable
EditText calcInput = (EditText) findViewById(R.id.EtCalc);
It means that when the class is initialized, your are trying to to find an element in a null windows.
You can't do it.
Just use:
EditText calcInput;
Then init the variable in your onCreate method.
Something like:
public class MainActivity extends AppCompatActivity {
//...
EditText calcInput;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonSetup();
calcInput = (EditText) findViewById(R.id.EtCalc);
}
}
You have to move this line :
EditText calcInput = (EditText) findViewById(R.id.EtCalc);
below the following line:
setContentView(R.layout.activity_main);

Categories

Resources