Android error at Intent command [closed] - android

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm having trouble with my code. When I click on the Title "New Profile" a new Activity has to start but when I click, an alert is shown: "Unfortunately %AppName% has stopped.".
Here is log of Android Monitor
--------- beginning of crash
05-17 01:19:54.545 2568-2568/com.example.felipe.myappproject E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.felipe.myappproject, PID: 2568
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.felipe.myappproject/com.example.felipe.myappproject.NewProfileActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
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.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.content.ContextWrapper.getPackageName(ContextWrapper.java:133)
at android.content.ComponentName.<init>(ComponentName.java:128)
at android.content.Intent.<init>(Intent.java:4449)
at com.example.felipe.myappproject.NewProfileActivity.<init>(NewProfileActivity.java:14)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
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) 
And here my NewProfileActivity.java
public class NewProfileActivity extends AppCompatActivity {
EditText profile, password, confirmpass;
Intent insert = new Intent(NewProfileActivity.this, MainActivity.class);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_profile);
}
public void backMain(View v){
startActivity(back);
}
public void insertData(View v) {
profile = (EditText) findViewById(R.id.profileName);
password = (EditText) findViewById(R.id.password);
confirmpass = (EditText) findViewById(R.id.confirmPassword);
insert.putExtra("profile", profile.getText().toString());
insert.putExtra("password", password.getText().toString());
insert.putExtra("profile", confirmpass.getText().toString());
compare(password.getText().toString(), confirmpass.getText().toString());
}
public void compare(String x, String y){
final AlertDialog alert = new AlertDialog.Builder(NewProfileActivity.this).create();
if(x.equals(y)){
alert.setTitle("New Profile!");
alert.setMessage("Profile "+profile+" registered");
alert.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}
);
startActivity(insert);
} else {
alert.setTitle("Ops...");
alert.setMessage("Passwords don't macth");
alert.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}
);
}
}
}
I can't find what I am doing wrong. I tried to simplify the code by removing everything except the "public void backMain(View v)" but I still get the same problem.

As per #MikeM's comment, you are initializing your Intent at the very beginning, where even the class that you are passing as a parameter isn't fully initialized yet.
You should simply just initialize right before you would use it like so:
public class NewProfileActivity extends AppCompatActivity {
EditText profile, password, confirmpass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_profile);
}
public void backMain(View v) {
// startActivity(back);
}
public void insertData(View v) {
profile = (EditText) findViewById(R.id.profileName);
password = (EditText) findViewById(R.id.password);
confirmpass = (EditText) findViewById(R.id.confirmPassword);
compare(password.getText().toString(), confirmpass.getText().toString());
}
public void compare(String x, String y) {
final AlertDialog alert = new AlertDialog.Builder(NewProfileActivity.this).create();
if (x.equals(y)) {
alert.setTitle("New Profile!");
alert.setMessage("Profile " + profile + " registered");
alert.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}
);
// CODES Transferred here ====
Intent insert = new Intent(NewProfileActivity.this, MainActivity.class);
insert.putExtra("profile", profile.getText().toString());
insert.putExtra("password", password.getText().toString());
insert.putExtra("profile", confirmpass.getText().toString());
// CODES Transferred here ====
startActivity(insert);
} else {
alert.setTitle("Ops...");
alert.setMessage("Passwords don't macth");
alert.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}
);
}
}
}
Cheers! :D

Related

White screen appearing when trigger a button

why does every time that I trigger the button it makes my screen white. But the values are getting remove.
Here is my code for it where it throws error.
final String uniqueKey = requestFormArrayList.get(position).getRequestid();
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("ResearchRequest").child(uniqueKey);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String termsAgreement = snapshot.child("requestStatus").getValue(String.class);
if(termsAgreement.equals("accepted")){
holder.acceptresearch_request.setText("accepted");
holder.acceptresearch_request.setEnabled(false);
holder.deleteresearch_request.setEnabled(false);
holder.publishresearch_request.setEnabled(true);
}
else if (termsAgreement.equals("published")){
holder.acceptresearch_request.setEnabled(false);
holder.deleteresearch_request.setEnabled(false);
holder.publishresearch_request.setText("published");
holder.publishresearch_request.setEnabled(false);
}
else{
holder.acceptresearch_request.setEnabled(true);
holder.deleteresearch_request.setEnabled(true);
holder.publishresearch_request.setEnabled(false);
}
}
the code above makes the button enable/disable depends on the value on the condition. But every time I delete or trigger the delete button it turns the screen white and go back to the MainActivity but it deletes the data without issue, it's just that it turns white instead of toasting and here's my code for it.
holder.deleteresearch_request.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Delete Research Record");
alert.setMessage("Are you sure you want to delete");
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
final String uniqueKey = requestFormArrayList.get(position).getRequestid();
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("ResearchRequest").child(uniqueKey);
databaseReference.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (!task.isSuccessful()) {
Log.i("firebase", "Throwing exception");
throw new RuntimeException(task.getException());
}
else {
Toast.makeText(context, "Research has been deleted", Toast.LENGTH_SHORT).show();
}
}
});
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(context, "Cancelled", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
alert.show();
}
});
EDIT: This is the error that throws at me, I've searched about the NullPointerException here. But I don't quite follow
2021-01-07 16:37:28.706 25163-25163/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.citeresearchrepository, PID: 25163
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at com.example.citeresearchrepository.AdminAdapter.AdminRequestFormAdapter$1.onDataChange(AdminRequestFormAdapter.java:60)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:75)
at com.google.firebase.database.core.view.DataEvent.fire(DataEvent.java:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(EventRaiser.java:55)
at android.os.Handler.handleCallback(Handler.java:900)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:219)
at android.app.ActivityThread.main(ActivityThread.java:8347)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1055)
Should I add another condition where termsAgreement.isEmpty() ? I think it's on the condition above since when you deleted it, there's no termsAgreement.equals("deleted"); in the database, any idea on for solution with this one?
String termsAgreement = snapshot.child("requestStatus").getValue(String.class);
if(termsAgreement.equals("accepted")){
holder.acceptresearch_request.setText("accepted");
holder.acceptresearch_request.setEnabled(false);
holder.deleteresearch_request.setEnabled(false);
holder.publishresearch_request.setEnabled(true);
}
else if (termsAgreement.equals("published")){
holder.acceptresearch_request.setEnabled(false);
holder.deleteresearch_request.setEnabled(false);
holder.publishresearch_request.setText("published");
holder.publishresearch_request.setEnabled(false);
}
else{
holder.acceptresearch_request.setEnabled(true);
holder.deleteresearch_request.setEnabled(true);
holder.publishresearch_request.setEnabled(false);
}
Here, your termsAgreement is null. Look at top line you wrote that String.class. String is data type. So, how you are calling it? I think that's why you are getting error. Maybe, you actually wanted to write string.class. On .getValue(String.class) you are unable to call value. That's why you are getting error.

getting null pointer exception in android while trying to get values from radio button

i have a layout register and i want to check if the user has entered all fields then move to next activity. I have checked that register_layout contains all the view that i want to access.
code for activity register.java
public class Register extends AppCompatActivity {
private Button register_user;
private EditText first_name_et,last_name_et,email_id_et,mobile_no_et,password_et,address_et; private RadioGroup gender_rad,user_type_rad;
private RadioButton gender_rb,user_rb;
private String first_name,last_name,email_id,mobile_no,password,address,gender,user_type;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
getDetails();
setDetails();
if(validation())
{
onClickRegister_driver();
}
else
{
Toast.makeText(this, "please fill all the details!!!", Toast.LENGTH_SHORT).show();
}
}
public void onClickRegister_driver()
{
register_user = (Button)findViewById(R.id.register_btn);
register_user.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("com.cablocator.my.cablocator.SetupDriver");
startActivity(intent);
}
}
);
}
public void getDetails()
{
first_name_et = (EditText) findViewById(R.id.firstname_txt);
last_name_et = (EditText) findViewById(R.id.lastname_txt);
email_id_et = (EditText) findViewById(R.id.email_txt);
mobile_no_et = (EditText) findViewById(R.id.mobile_txt);
password_et = (EditText) findViewById(R.id.password_txt);
address_et = (EditText) findViewById(R.id.address_txt);
gender_rad = (RadioGroup) findViewById(R.id.gender_radio);
user_type_rad = (RadioGroup) findViewById(R.id.user_type_radio);
int selected_gender = gender_rad.getCheckedRadioButtonId();
gender_rb = (RadioButton) findViewById(selected_gender);
int selected_user_type = user_type_rad.getCheckedRadioButtonId();
user_rb = (RadioButton) findViewById(selected_user_type);
}
public void setDetails()
{
first_name = first_name_et.getText().toString().trim();
last_name = last_name_et.getText().toString().trim();
email_id = email_id_et.getText().toString().trim();
mobile_no = mobile_no_et.getText().toString().trim();
password = password_et.getText().toString().trim();
address = address_et.getText().toString().trim();
gender = gender_rb.getText().toString().trim();
user_type = user_rb.getText().toString().trim();
}
public Boolean validation()
{
if(first_name.isEmpty())
{
return false;
}
else if(last_name.isEmpty())
{
return false;
}
else if(email_id.isEmpty())
{
return false;
}
else if(mobile_no.isEmpty())
{
return false;
}
else if(password.isEmpty())
{
return false;
}
else if(address.isEmpty())
{
return false;
}
else if(gender.isEmpty())
{
return false;
}
else if(user_type.isEmpty())
{
return false;
}
else
{
return true;
}
}
}
logcat:
10-07 15:40:14.071 4303-4303/com.cablocator.my.cablocator E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.cablocator.my.cablocator, PID: 4303
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.cablocator.my.cablocator/com.cablocator.my.cablocator.Register}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.RadioButton.getText()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2493)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2576)
at android.app.ActivityThread.access$1000(ActivityThread.java:155)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1421)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5539)
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.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.RadioButton.getText()' on a null object reference
at com.cablocator.my.cablocator.Register.setDetails(Register.java:93)
at com.cablocator.my.cablocator.Register.onCreate(Register.java:26)
at android.app.Activity.performCreate(Activity.java:6289)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2446)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2576) 
at android.app.ActivityThread.access$1000(ActivityThread.java:155) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1421) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5539) 
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) 
According to me this is showing NullPointer Exception when the user dont select and gender in the radioGroup If User dnt select and radio Button this leads to int selected_gender = gender_rad.getCheckedRadioButtonId(); equals to null
so to ignore this situation put a default gender in radio Group i.e put something in int selected_gender by default

NullPointerException when using database object [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm new to Android, and i've got some issues.
It looks like it's saying DB.EmployeeOperations.open() is having an null object passed to it, but I'm not sure.
Where I missed a step?
Any help is appreciated.
Thanks in advance.
Logcat:
* 06-10 16:10:52.605 17203-17203/com.androidtutorialpoint.employeemanagementsystem E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.androidtutorialpoint.employeemanagementsystem, PID: 17203
java.lang.RuntimeException: Unable to resume activity {com.androidtutorialpoint.employeemanagementsystem/com.androidtutorialpoint.employeemanagementsystem.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.androidtutorialpoint.employeemanagementsystem.DB.EmployeeOperations.open()' on a null object reference
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3019)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3050)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2425)
at android.app.ActivityThread.access$900(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5294)
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 com.androidtutorialpoint.employeemanagementsystem.DB.EmployeeOperations.open()' on a null object reference
at com.androidtutorialpoint.employeemanagementsystem.MainActivity.onResume(MainActivity.java:148)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1257)
at android.app.Activity.performResume(Activity.java:6076)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3008)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3050)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2425)
at android.app.ActivityThread.access$900(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
Java Code:
public class MainActivity extends AppCompatActivity{
private Button addEmployeeButton;
private Button editEmployeeButton;
private Button deleteEmployeeButton;
private Button viewAllEmployeeButton;
private EmployeeOperations employeeOps;
private static final String EXTRA_EMP_ID = "com.androidtutorialpoint.empId";
private static final String EXTRA_ADD_UPDATE = "com.androidtutorialpoint.add_update";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addEmployeeButton = (Button) findViewById(R.id.button_add_employee);
editEmployeeButton = (Button) findViewById(R.id.button_edit_employee);
deleteEmployeeButton = (Button) findViewById(R.id.button_delete_employee);
viewAllEmployeeButton = (Button)findViewById(R.id.button_view_employees);
addEmployeeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,AddUpdateEmployee.class);
i.putExtra(EXTRA_ADD_UPDATE, "Add");
startActivity(i);
}
});
editEmployeeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getEmpIdAndUpdateEmp();
}
});
deleteEmployeeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getEmpIdAndRemoveEmp();
}
});
viewAllEmployeeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, ViewAllEmployees.class);
startActivity(i);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.employee_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.menu_item_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void getEmpIdAndUpdateEmp(){
LayoutInflater li = LayoutInflater.from(this);
View getEmpIdView = li.inflate(R.layout.dialog_get_emp_id, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
// set dialog_get_emp_id.xml to alertdialog builder
alertDialogBuilder.setView(getEmpIdView);
final EditText userInput = (EditText) getEmpIdView.findViewById(R.id.editTextDialogUserInput);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// get user input and set it to result
// edit text
Intent i = new Intent(MainActivity.this,AddUpdateEmployee.class);
i.putExtra(EXTRA_ADD_UPDATE, "Update");
i.putExtra(EXTRA_EMP_ID, Long.parseLong(userInput.getText().toString()));
startActivity(i);
}
}).create()
.show();
}
public void getEmpIdAndRemoveEmp(){
LayoutInflater li = LayoutInflater.from(this);
View getEmpIdView = li.inflate(R.layout.dialog_get_emp_id, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
// set dialog_get_emp_id.xml to alertdialog builder
alertDialogBuilder.setView(getEmpIdView);
final EditText userInput = (EditText) getEmpIdView.findViewById(R.id.editTextDialogUserInput);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// get user input and set it to result
// edit text
employeeOps = new EmployeeOperations(MainActivity.this);
employeeOps.removeEmployee(employeeOps.getEmployee(Long.parseLong(userInput.getText().toString())));
Toast t = Toast.makeText(MainActivity.this,"Employee removed successfully!",Toast.LENGTH_SHORT);
t.show();
}
}).create()
.show();
}
#Override
protected void onResume() {
super.onResume();
employeeOps.open();
}
#Override
protected void onPause() {
super.onPause();
employeeOps.close();
}
}
The problem is you're calling employeeOps.open() in onResume(), but employeeOps is not instantiated yet, it's value is still null.
Take a look at the Activity lifecycle.
As you can see, when an Activity gets created two methods get called before onResume(): onCreate() and onStart().
If you would like to call the open() method of EmployeeOperations in onResume(), you need to have an instance of it by then.
Call the following in onCreate():
employeeOps = new EmployeeOperations(this);
Your problem is a misunderstanding of the Android lifecycle. Specifically, from that resource,
Once the onCreate() finishes execution, the system calls the onStart() and onResume() methods in quick succession.
What this means for you is that onResume() triggers before you ever set employeeOps to a non-null value. You're only initializing it in response to a button press, but your Activity is only visible for a very short duration before onResume is triggered.

Call AlertDialog Method with parameters inside Fragment

im doing an app for my project but im not sure what to pass in my method.
Heres how i call the method:
public void scanBar(View v) {
switch (v.getId()) {
case R.id.barcode_scan_btn:
try {
Intent intent = new Intent(ACTION_SCAN);
intent.putExtra("SCAN_MODE", "PRODUCT_MODE");
startActivityForResult(intent, 0);
} catch (ActivityNotFoundException anfe) {
showDialog(getActivity(), "No Scanner Found", "Download the scanner application?", "Yes", "No").show();
}
break;
}
}
And here is my method:
private static AlertDialog showDialog(final Activity act, CharSequence title, CharSequence message, CharSequence buttonYes, CharSequence buttonNo) {
AlertDialog.Builder downloadDialog = new AlertDialog.Builder(act);
downloadDialog.setTitle(title);
downloadDialog.setMessage(message);
downloadDialog.setPositiveButton(buttonYes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Uri uri = Uri.parse("market://search?q=pname:" + "com.google.zxing.client.android");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
try {
act.startActivity(intent);
} catch (ActivityNotFoundException anfe) {
}
}
});
downloadDialog.setNegativeButton(buttonNo, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
return downloadDialog.show();
}
Here is the error:
09-20 05:20:31.774 17032-17032/app.psiteportal.com.psiteportal E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: app.psiteportal.com.psiteportal, PID: 17032
java.lang.IllegalStateException: Could not find a method scanBar(View) in the activity class app.psiteportal.com.psiteportal.DrawerMainAdapter for onClick handler on view class android.support.v7.widget.AppCompatButton with id 'barcode_scan_btn'
at android.view.View$1.onClick(View.java:3994)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19761)
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:5253)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NoSuchMethodException: scanBar [class android.view.View]
at java.lang.Class.getMethod(Class.java:664)
at java.lang.Class.getMethod(Class.java:643)
at android.view.View$1.onClick(View.java:3987)
            
I dont know if where should i put my method either in the activity or in the fragment. pls help
EDIT: Do i need to change the parameter to Fragment or just Activity?
The problem is that your method scanBar() was declared as onClick callback (inside your layout). This won't work in fragments.
"The Activity hosting the layout must then implement the corresponding method." - developer.android.com
Its not a bug. If you would like to implement callback in this way, you must use activities instead of fragments.
So the solutions is to set an onClick listener, like this:
setOnClickListener(new OnClickListener() {/* Some Code */ });

Error when creating an intent inside of an AlertDialog

I am making an app that enables users to sign up on Parse.com. I have made Dialogs for the signing up just to add a more fluent feel in the app. So after they click "sign up" for example. I want it to take them to HomescreenActivity....So i made an intent inside of my Dialog. I know that It is a class and does not have context... but how would i make an intent inside of it? getContext() is not avaliable and getActivity() is giving me an error. I will post the code below. Thank you.
public class SignUpDialog extends DialogFragment {
private View v;
private LayoutInflater inflater;
private EditText adressEditText, fullnameEditText , passwordEditText , usernameEditText;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
inflater = getActivity().getLayoutInflater();
v = inflater.inflate(R.layout.sign_up_dialog_layout , null);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(v).setPositiveButton("Sign Up!" , new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
fullnameEditText = (EditText) v.findViewById(R.id.fullNameEditTextLayout);
passwordEditText = (EditText) v.findViewById(R.id.passwordEditTextLayout);
usernameEditText = (EditText) v.findViewById(R.id.usernameEditTextLayout);
adressEditText = (EditText) v.findViewById(R.id.addressEditTextLayout);
String username = usernameEditText.getText().toString().trim();
String password = usernameEditText.getText().toString();
String address = adressEditText.getText().toString();
Toast.makeText(getActivity() , "We are signing you u now!" , Toast.LENGTH_SHORT).show();
ParseUser user = new ParseUser();
user.setUsername(username);
user.setPassword(password);
user.put("address", address);
user.signUpInBackground(new SignUpCallback() {
public void done(ParseException e) {
if (e == null) {
// Hooray! Let them use the app now.
Intent intent = new Intent(getActivity(), HomescreenActivity.class);
getActivity().startActivity(intent);
} else {
// Sign up didn't succeed. Look at the ParseException
// to figure out what went wrong
}
}
});
}
}).setNegativeButton("Cancel" , new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
return builder.create();
}
}
Here is the error i am getting
java.lang.NullPointerException
at com.xxx.xxx.dialogs.SignUpDialog$2$1.done(SignUpDialog.java:69)
at com.xxx.xxx.dialogs.SignUpDialog$2$1.done(SignUpDialog.java:63)
at com.parse.Parse$5.done(Parse.java:903)
at com.parse.Parse$5.done(Parse.java:900)
at com.parse.Parse$6$1.run(Parse.java:944)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
In Fragments you need to null check getActivity() since the Fragment can outlive the Activity.
Alternatives to getActivity() and getContext() are:
getApplicationContext()
Or, to create a context that is available anywhere in your app, you can extend Application and create your custom application class.
Inside your custom application class you create a static variable:
private static final CustomApplication INSTANCE;
In CustomApplication's onCreate():
INSTANCE = this;
Create a static method
public static CustomApplication getInstance() {
return INSTANCE;
}
Then from anywhere in your app, to get the context, you can call:
CustomApplication.getInstance()
which is a context.

Categories

Resources