facing difficulties with mainactivity - java

i face some errors when trying to run my app here is the logcat
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.chatapp/com.example.chatapp.MainActivity}: java.lang.InstantiationException: java.lang.Class<com.example.chatapp.MainActivity> has no zero argument constructor
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2843)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.InstantiationException: java.lang.Class<com.example.chatapp.MainActivity> has no zero argument constructor
and here is my mainAcivity
`public class MainActivity extends AppCompatActivity {
Button login, register;
FirebaseUser firebaseUser;
#Override
protected void onStart() {
super.onStart();
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
//check if user in null
if (firebaseUser != null){
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
new MainActivity(intent);
finish();
}
}
`
but also i think this is an error
public MainActivity(Intent intent) {
}

Activities do not need to be instantiated, so you only need to call the following to start one:
//check if user in null
if (firebaseUser != null){
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
startActivity(intent);
finish();
}
Basically you only need to remove this line:
new MainActivity(intent);
And start the Activity with:
startActivity(intent);

Related

Pass String (or Array) to ListView in another Activity (NPE error)

I would like to have the working ListView from the MainActivity in the ExpAct (2.Activity).
What I have: Edittext and a Button that creates a new entry to a Listview upon clicking.
The ListView on MainAct is just for checking and will be deleted if ExpAct works.
Upon clicking the "next"Btn I get to ExpAct.
I get a raw use parameter warning. -- And if I were to fix that, it gives me an NPE-crash for the ExpAct, or an empty ListView.
Is the issue that the getter Intent for the String/Array doesnt work? Or does it lie with the creation of the ArrayAdapter?
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView LV1;
ArrayList < String > listExp;
Button button1, btnext;
EditText ETbc;
ArrayAdapter < String > arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LV1 = findViewById(R.id.LV1);
button1 = findViewById(R.id.button1);
ETbc = findViewById(R.id.ETbc);
listExp = new ArrayList < String > ();
arrayAdapter = new ArrayAdapter < String > (getApplicationContext(),
android.R.layout.simple_list_item_1, listExp);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String names = ETbc.getText().toString();
listExp.add(names);
LV1.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
Intent inter = new Intent(MainActivity.this, ExpAct.class);
inter.putExtra("key", listExp);
setResult(Activity.RESULT_OK, inter);
}
});
btnext = findViewById(R.id.btnext);
btnext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ExpAct.class);
startActivity(intent);
finish();
}
});
}
}
*ExpAct.java: *
public class ExpAct extends MainActivity {
ListView LV2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exp);
Intent i = getIntent();
listExp = i.getStringArrayListExtra("key");
LV2 = findViewById(R.id.LV2);
ArrayAdapter arrayAdapter = new ArrayAdapter < String > (getApplicationContext(),
android.R.layout.simple_list_item_1, R.id.LV2, listExp); // here without R.id.LV2
LV2.setAdapter(arrayAdapter);
}
}
Logs since it has become red.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.testcheckbox, PID: 20358
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.testcheckbox/com.example.testcheckbox.ExpAct}.
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2789)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6255)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:344)
at android.widget.ListView.setAdapter(ListView.java:510)
at com.example.testcheckbox.ExpAct.onCreate(ExpAct.java:27)
at android.app.Activity.performCreate(Activity.java:6670)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2677)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2789) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527) 
at android.os.Handler.dispatchMessage(Handler.java:110) 
at android.os.Looper.loop(Looper.java:203) 
at android.app.ActivityThread.main(ActivityThread.java:6255) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924) 
Disconnected from the target VM, address: 'localhost:57662', transport: 'socket'
It looks like you're trying to start the activity without putting the ArrayList as an extra.
btnext = findViewById(R.id.btnext);
btnext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ExpAct.class);
// You need to put the extra data here:
intent.putExtra("key", listExp);
startActivity(intent);
finish();
}
});
When you get a NullPointerException, you should first check why would the list be null:
Attempt to invoke interface method 'int java.util.List.size()' on a
null object reference
So after looking at your code, I saw that you're not passing the ArrayList with the intent.

Getting NPE Unable to start activity: Attempt to invoke virtual method on a null object reference even with setContentView [duplicate]

This question already has answers here:
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference
(5 answers)
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
I'm following this tutorial to explore Firebase and use email authentication using
three java classes
MainActivity
RegisterActivity
ProfileActivity
and
three layout views.
activity_main.xml
activity_register.xml
profilepage.xml
[Youtube tutorial]1
I'm getting
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.firebaselearning/com.example.firebaselearning.RegisterActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
full error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.firebaselearning, PID: 8008
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.firebaselearning/com.example.firebaselearning.RegisterActivity}: 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:2913)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
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 com.example.firebaselearning.RegisterActivity.onCreate(RegisterActivity.java:60)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:193) 
at android.app.ActivityThread.main(ActivityThread.java:6669) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 
following are the codes (excluding gradle because i don't think it's where error originates from)
MainActivity.java
public class MainActivity extends AppCompatActivity {
//views
Button mRegisterBtn, mLogInBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initialise view
mRegisterBtn = findViewById(R.id.registerbutton);
mLogInBtn = findViewById(R.id.login);
//handle register button click
mRegisterBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//start register activity
startActivity(new Intent(MainActivity.this, RegisterActivity.class));
}
});
}
}
RegisterActivity.java
public class RegisterActivity extends AppCompatActivity {
//views
EditText mEmailET, mPassword;
Button mRegistrationBTN;
//progressbar to display progress which registering
ProgressDialog progressDialog;
//declare instance of fireAuth
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
//actionbar and its title
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("Create Account");
//enable back button
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
//init
mEmailET = findViewById(R.id.editTextTextEmailAddress);
mPassword = findViewById(R.id.editTextTextPassword);
mRegistrationBTN = findViewById(R.id.registerbutton);
//initialising firebaseAuth instance
mAuth = FirebaseAuth.getInstance();
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Registering user ...");
//handle register btn click
mRegistrationBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//input email, password
String email = mEmailET.getText().toString().trim();
String password = mPassword.getText().toString().trim();
//validate
if(Patterns.EMAIL_ADDRESS.matcher(email).matches()){
//show error and focus to edittext
mEmailET.setError("Invalid Email");
mEmailET.setFocusable(true);
}else if (password.length()<6){
//set error and focus to password
mPassword.setError("Password length must be at least 6 characters");
mPassword.setFocusable(true);
}else{
//register the user
registerUser(email,password);
}
}
});
}
private void registerUser(String email, String password){
//email and password is valid ,shows progress dialog and start registering user
progressDialog.show();
mAuth.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, dismiss dialog and start register activity
progressDialog.dismiss();
FirebaseUser user = mAuth.getCurrentUser();
assert user != null;
Toast.makeText(RegisterActivity.this,"Registered..."+user.getEmail(), Toast.LENGTH_SHORT).show();
startActivity(new Intent(RegisterActivity.this, ProfileActivity.class));
finish();
} else {
// If sign in fails, display a message to the user.
progressDialog.dismiss();
Toast.makeText(RegisterActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show();
}
}
}) .addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
//error, dismiss progrss dialog and get and show error message
progressDialog.dismiss();
Toast.makeText(RegisterActivity.this,""+e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed(); //go previous activity on clicking back
return super.onSupportNavigateUp();
}
}
I've reverified that names of my xml files are same .
Error arose due to referencing register button from activity_main.xml layout which is view of MainActivity , from RegisterActivity which has another register button in it's view of activity_register.xml
sorry to waste your time
.
the register button from activity_main thus wasn't initialised in the Register.java

MainActivity cannot be cast to android.app.Activity

I know this has been asked multiple times, and I been trying to fix it, but I really can't seem to understand what the problem is. I'm really new to Android Studio and Android Room, so if I'm honest, I barely have a clue what I'm doing. I assume the error occurs in my "MainActivity.java" class based off what the logcat tells me. This is my logcat
2020-06-15 01:33:41.885 21773-21773/com.example.hoply5 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.hoply5, PID: 21773
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.hoply5/com.example.hoply5.MainActivity}: java.lang.ClassCastException: com.example.hoply5.MainActivity cannot be cast to android.app.Activity
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3272)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3500)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
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:2049)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7523)
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:941)
Caused by: java.lang.ClassCastException: com.example.hoply5.MainActivity cannot be cast to android.app.Activity
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:41)
at android.app.Instrumentation.newActivity(Instrumentation.java:1253)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3260)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3500) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
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:2049) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:223) 
at android.app.ActivityThread.main(ActivityThread.java:7523) 
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:941) 
Here is my MainActivity class
public class SecondFragment extends Fragment {
EditText editTxtName, editTxtEmail, editTxtPwd, editTextCnfPwd;
Button backBtn, registerBtn;
private UserDao userDao;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_second, container, false);
editTxtName = view.findViewById(R.id.editName);
editTxtEmail = view.findViewById(R.id.editEmail);
editTxtPwd = view.findViewById(R.id.editPwd);
registerBtn = view.findViewById(R.id.registerBtn2);
editTextCnfPwd = view.findViewById(R.id.editCnfPwd);
backBtn = view.findViewById(R.id.backBtn);
backBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), MainActivity.class);
startActivity(intent);
}
});
userDao = Room.databaseBuilder(getActivity(), UserDatabase.class, "User").build().getUserDao();
registerBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String userName = editTxtName.getText().toString().trim();
String email = editTxtEmail.getText().toString().trim();
String password = editTxtPwd.getText().toString().trim();
String passwordCnf = editTextCnfPwd.getText().toString().trim();
if(password.equals(passwordCnf)) {
User user = new User(userName,password,email);
userDao.insert(user);
Intent transitionLogin = new Intent(getActivity(), MainActivity.class);
startActivity(transitionLogin);
} else {
Toast.makeText(getActivity(), "Password is not matching", Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
}
Your MainActivity is Fragment,so you have to replace it

Check if nfc tag is near by

I want my phone to detect if there is a nfc tag near by (near the surface of it)
The following code has no errors but as soon as i run the app, it crashes. It would be very helpful if someone of you can look through my code and check if there is something i dont see. Down bellow is the runtimeerror.
public class AccessControlActivity extends AppCompatActivity {
NfcAdapter nfcAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_access_control);
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
// Checks if there is NFC function
if(nfcAdapter != null && nfcAdapter.isEnabled()) {
//Toast.makeText(this, "NFC works", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, "NFC is not available!", Toast.LENGTH_SHORT).show();
//finish();
}
}
#Override
protected void onNewIntent(Intent intent) {
Toast.makeText(this, "NFC intent received", Toast.LENGTH_LONG).show();
super.onNewIntent(intent);
}
#Override
protected void onResume() {
Intent intent = new Intent(this, AccessControlActivity.class);
intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
IntentFilter[] intentFilters = new IntentFilter[]{};
nfcAdapter.enableForegroundDispatch(this, pendingIntent, intentFilters, null);
super.onResume();
}
#Override
protected void onPause() {
nfcAdapter.disableForegroundDispatch(this);
super.onPause();
}
}
The runtimeerror looks like this:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.nfc.netvision, PID: 5484
java.lang.RuntimeException: Unable to resume activity {com.nfc.netvision/com.nfc.netvision.AccessControlActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.nfc.NfcAdapter.enableForegroundDispatch(android.app.Activity, android.app.PendingIntent, android.content.IntentFilter[], java.lang.String[][])' on a null object reference
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4341)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4373)
at android.app.servertransaction.ResumeActivityItem.execute(ResumeActivityItem.java:52)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:176)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2043)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7464)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:955)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.nfc.NfcAdapter.enableForegroundDispatch(android.app.Activity, android.app.PendingIntent, android.content.IntentFilter[], java.lang.String[][])' on a null object reference
at com.nfc.netvision.AccessControlActivity.onResume(AccessControlActivity.java:116)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1456)
at android.app.Activity.performResume(Activity.java:8125)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4331)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4373) 
at android.app.servertransaction.ResumeActivityItem.execute(ResumeActivityItem.java:52) 
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:176) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2043) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:216) 
at android.app.ActivityThread.main(ActivityThread.java:7464) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:955) 
I/Process: Sending signal. PID: 5484 SIG: 9
So you check that the nfcAdapter != null in onCreate and just show a toast, your app will then blindly go and try and use a possibly null adapter in onResume.
This would explain the Attempt to invoke virtual method on a null object reference in onResume as the variable nfcAdapter is probably null in onResume
You should check for null again in onResume
Also your Intent filters don't look right as well, they code either cause no Intents to be sent to you or the opposite cause all including non NFC Intents to be sent to you.
More normal code to get called when any type of tag is presented would be.
#Override
protected void onResume() {
super.onResume();
IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
IntentFilter ndefDetected = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
try {
ndefDetected.addDataType("*/*");
} catch (IntentFilter.MalformedMimeTypeException e) {}
IntentFilter techDetected = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
IntentFilter[] nfcIntentFilter = new IntentFilter[]{ndefDetected,techDetected,tagDetected};
PendingIntent pendingIntent = PendingIntent.getActivity(
this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
if(nfcAdapter!= null)
nfcAdapter.enableForegroundDispatch(this, pendingIntent, nfcIntentFilter, null);
}
#Override
protected void onPause() {
super.onPause();
if(nfcAdapter!= null)
nfcAdapter.disableForegroundDispatch(this);
}

Button Click Intent crashes App

I have a problem,
I can't get my button to work
On click it should switch from MainActivity to Login
Both classes work fine without the Button,
but now, as I brought in the Button, it keeps crashing.
What am I doing wrong?
This Button, which brings me from login to Mainactivity, works just fine:
public class login extends Activity {
Button b1,b2;
EditText ed1,ed2;
TextView tx1;
int counter = 3;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setContentView(R.layout.login);
b1 = (Button)findViewById(R.id.button);
ed1 = (EditText)findViewById(R.id.editText);
ed2 = (EditText)findViewById(R.id.editText2);
b2 = (Button)findViewById(R.id.button2);
tx1 = (TextView)findViewById(R.id.textView3);
tx1.setVisibility(View.GONE);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(ed1.getText().toString().equals("admin") && ed2.getText().toString().equals("admin")) {
Toast.makeText(getApplicationContext(),"Redirecting...",Toast.LENGTH_SHORT).show();
Intent i = new Intent(login.this, MainActivity.class);
startActivity(i);
}
else{
Toast.makeText(getApplicationContext(), "Fehlerhafte Eingabe",Toast.LENGTH_SHORT).show();
tx1.setVisibility(View.VISIBLE);
tx1.setBackgroundColor(Color.RED);
counter--;
tx1.setText(Integer.toString(counter));
if (counter == 0) {
b1.setEnabled(false);
}
}
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
}
Button code
StrgS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
{
Toast.makeText(getApplicationContext(), "Goodbye", Toast.LENGTH_LONG).show();
Intent j = new Intent(MainActivity.this, login.class);
startActivity(j);
}
}
});
}
}
Error Code
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.cris.zeiterfassungv2, PID: 10555
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.cris.zeiterfassungv2/com.example.cris.zeiterfassungv2.MainActivity}: android.view.InflateException: Binary XML file line #0: Can't convert value at index 6 to dimension: type=0x12
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: android.view.InflateException: Binary XML file line #0: Can't convert value at index 6 to dimension: type=0x12
Caused by: java.lang.UnsupportedOperationException: Can't convert value at index 6 to dimension: type=0x12
at android.content.res.TypedArray.getDimensionPixelSize(TypedArray.java:730)
at android.view.ViewGroup$MarginLayoutParams.<init>(ViewGroup.java:7797)
at android.widget.LinearLayout$LayoutParams.<init>(LinearLayout.java:1976)
at android.widget.LinearLayout.generateLayoutParams(LinearLayout.java:1874)
at android.widget.LinearLayout.generateLayoutParams(LinearLayout.java:1872)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:865)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
at com.example.cris.zeiterfassungv2.MainActivity.onCreate(MainActivity.java:76)
at android.app.Activity.performCreate(Activity.java:6999)
at android.app.Activity.performCreate(Activity.java:6990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Thank you

Categories

Resources