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 */ });
Related
error occurs when startActvityResult() called.
I use this to call FragmentFotosdePerfil from other fragment
public void verFotosPerfil(String userID){
fragmentFotosPerfil=new FragmentFotosPerfil();
Bundle bundle= new Bundle();
bundle.putString("userID",userID);
fragmentFotosPerfil.setArguments(bundle);
getFragmentManager().beginTransaction().
replace(R.id.frameLayout2,fragmentFotosPerfil).commit();
}
I call "cargarFotoPerfil" from the XML with Onclick in different buttons
public void cargarFotoPerfil(View view){
switch(view.getId()) {
case R.id.btnCargarFoto2:
System.out.println("caso2");
cargarFotoPerfil2(view);
foto=2;
break;
case R.id.btnCargarFoto3:
cargarFotoPerfil2(view);
foto=3;
break;
case R.id.btnCargarFoto4:
cargarFotoPerfil2(view);
foto=4;
break;
case R.id.btnCargarFoto5:
cargarFotoPerfil2(view);
foto=5;
break;
}
public void cargarFotoPerfil2(View view){
final CharSequence[] opciones={"Elegir de Galeria","Cancelar"};
final AlertDialog.Builder builder=new
AlertDialog.Builder(view.getContext());
builder.setTitle("Elige una Opción");
builder.setItems(opciones, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (opciones[i].equals("Elegir de Galeria")){
Intent intent=new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/");
startActivityForResult
(intent.createChooser(intent,"Seleccione"),10);
}else{
dialogInterface.dismiss();
}
}
});
builder.show();
}
here is my logcat report as you show below.
//ERROR.CRASHES IN LINE startActivityForResult()
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.clemente.prueba6, PID: 4937
java.lang.IllegalStateException: Fragment FragmentFotosPerfil{18cbf6df} not attached to Activity
at android.support.v4.app.Fragment.startActivityForResult(Fragment.java:1019)
at android.support.v4.app.Fragment.startActivityForResult(Fragment.java:1010)
at com.example.clemente.prueba6.FragmentFotosPerfil$1.onClick(FragmentFotosPerfil.java:159)
at android.support.v7.app.AlertController$AlertParams$3.onItemClick(AlertController.java:1067)
at android.widget.AdapterView.performItemClick(AdapterView.java:300)
at android.widget.AbsListView.performItemClick(AbsListView.java:1143)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3044)
at android.widget.AbsListView$3.run(AbsListView.java:3833)
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:5221)
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)
Does anyone know the solution to this problem?
Thanks in advance
I believe that any way you want to dismiss the Dialog, And it might fix your crash...
Try changing the onClick to look like this:
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
if (opciones[i].equals("Elegir de Galeria")){
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/");
startActivityForResult(intent.createChooser(intent,"Seleccione"),10);
}
}
Use isAdded to check if fragment is attached to Activity.
if(isAdded){
final CharSequence[] opciones={"Elegir de Galeria","Cancelar"};
final AlertDialog.Builder builder=new AlertDialog.Builder(view.getContext());
builder.setTitle("Elige una Opción");
builder.setItems(opciones, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (opciones[i].equals("Elegir de Galeria")){
Intent intent=new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/");
startActivityForResult(intent.createChooser(intent,"Seleccione"),10);
}else{
dialogInterface.dismiss();
}
}
});
}
I think you need check your code. Because I replied the fragment and your code is working fine. Maybe your mistake is the way that you are using to load the fragment in the Activity.
I let you the code that i use to launch the fragment. This code is working.
Calling another fragment from TestFragment
public class TestFragment extends Fragment {
public TestFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_test_two, container, false);
TestFragmentTwo fragment = new TestFragmentTwo();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container, fragment);
fragmentTransaction.addToBackStack(fragment.toString());
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.commit();
return v;
}
}
TestFragmentTwo
public class TestFragmentTwo extends Fragment {
public TestFragmentTwo() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_test_two, container, false);
final CharSequence[] opciones={"Elegir de Galeria","Cancelar"};
final AlertDialog.Builder builder=new AlertDialog.Builder(v.getContext());
builder.setTitle("Elige una Opción");
builder.setItems(opciones, (dialogInterface, i) -> {
if (opciones[i].equals("Elegir de Galeria")){
Intent intent=new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/");
getActivity().startActivityForResult(intent.createChooser(intent,"Seleccione"),10);
}else{
dialogInterface.dismiss();
}
});
builder.show();
return v;
}
}
As you can see, I am loading a fragment from another fragment, and then I am calling the startActivityResult without problem.
I hope it helps you.
The exception says that you are not attached the fragment or else that attached fragment may be destroyed kindly reattach the fragment.
I am getting a window leak when I am starting a free walk activity. I have handled that scenario but still don't understand why I am still getting.
Here is my code:
private void showPopUp() {
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); //before
dialog.setContentView(R.layout.wwmove_screen_popup);
TextView mNo = (TextView) dialog.findViewById(R.id.move_no);
// if button is clicked, close the custom dialog
mNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
TextView mYes = (TextView) dialog.findViewById(R.id.moveyes);
mYes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
killAll();
storeSegmentcompletdInformation("skipped");
storeOneDayInformation("skipped");
Intent gotoSummary = new Intent(WwFreeWalkMoveActivity.this, WwFreeWalkSummaryActivity.class);
gotoSummary.putExtra(ParamConstants.SUMMARY_GOOGLEFIT_KEY, String.valueOf(stepCountGoogleFit));
startActivity(gotoSummary);
}
});
dialog.show();
}
The error I am getting is:
08-18 10:38:53.172 28118-28118/com.mobiefit.walk E/WindowManager: android.view.WindowLeaked: Activity com.mobiefit.walk.freewalk.activity.WwFreeWalkMoveActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{21f913f9 V.E..... R.....I. 0,0-960,516} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:364)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:274)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
at android.app.Dialog.show(Dialog.java:298)
at com.mobiefit.walk.freewalk.activity.WwFreeWalkMoveActivity.showPopUp(WwFreeWalkMoveActivity.java:953)
at com.mobiefit.walk.freewalk.activity.WwFreeWalkMoveActivity.onOptionsItemSelected(WwFreeWalkMoveActivity.java:1806)
at android.app.Activity.onMenuItemSelected(Activity.java:2936)
at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:404)
at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:185)
at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:100)
at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:100)
at android.support.v7.widget.ToolbarWidgetWrapper$1.onClick(ToolbarWidgetWrapper.java:192)
at android.view.View.performClick(View.java:4785)
at android.view.View$PerformClick.run(View.java:19888)
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:5273)
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:908)
Can anyone tell me what I am doing wrong?
Window leaked exceptions are usually caused by dialogs which are not dismissed properly.
you have to dismiss the dialog
In your code
use this
dialog.dismiss();
mYes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
killAll();
storeSegmentcompletdInformation("skipped");
storeOneDayInformation("skipped");
Intent gotoSummary = new Intent(WwFreeWalkMoveActivity.this, WwFreeWalkSummaryActivity.class);
gotoSummary.putExtra(ParamConstants.SUMMARY_GOOGLEFIT_KEY, String.valueOf(stepCountGoogleFit));
startActivity(gotoSummary);
}
});
Before proceeding to next activity or task. dismiss your dialog.dismiss(); dialog.
public void onClick(View v) {
killAll();
storeSegmentcompletdInformation("skipped");
storeOneDayInformation("skipped");
Intent gotoSummary = new Intent(WwFreeWalkMoveActivity.this, WwFreeWalkSummaryActivity.class);
gotoSummary.putExtra(ParamConstants.SUMMARY_GOOGLEFIT_KEY, String.valueOf(stepCountGoogleFit));
dialog.dismiss(); // here you just have to add one line.
startActivity(gotoSummary);
}
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.
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
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.