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.
Related
I am working on an App that has a DialogBuilder Class where I implemented all the Dialogs for the App in order to be able to call them in other Services or Activities; that works very well except in one Activity, where I tried everything to pass the context - it is not working; hence, I would be more than delighted for any hints or help on this, thanks!
The Dialog:
public static void bookingConfirmationDialog(Context mContext) {
if(mContext != null) {
final Dialog dialog = new Dialog(GoldbekStorageApp.getInstance(), 0);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setContentView(R.layout.new_booking_layout);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
TextView textView = dialog.findViewById(R.id.messageId);
textView.setText(GoldbekStorageApp.getInstance().messageId);
Button okButton = dialog.findViewById(R.id.ok);
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
}
The call of the Dialog:
proceedButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
message.setType(type);
message.setFromId(fromID);
message.setToId(toID);
message.setTypeId(typeID);
message.setTime(time);
message.setTitle(title);
message.setReceiptNo(receiptNo);
message.setNote(note);
RestClient.putBookingOnPallet(basic,message,context);
DialogBuilder.bookingConfirmationDialog(context);
/* Intent activityChangeIntent = new Intent( NewProductActivity.this,
NewProductActivity.class);
NewProductActivity.this.startActivity(activityChangeIntent);*/
}
});
I may be missing something but you could override onAttach in the DialogFragment class instead of passing the context in through the constructor.
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
}
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.
I am sending a string from an activity to my custom dialog.
This is the activity in which I create a bundle and insert the string, then send it to the dialog activity.
Bundle sendToDialog = new Bundle();
sendToDialog.putString("caloreis", strCalories);
Intent a = new Intent(CaloriesLogMainActivity.this, ActivityDialog.class);
a.putExtras(sendToDialog);
This is the custom dialog activity in which I am trying to receive the intent from the activity.
getIntent(), is coming up as an error. How would I get around this error?
public class ActivityDialog {
Context mContext;
Date mDate;
public ActivityDialog(Context context, CaloriesLogMainActivity caloriesLogMainActivity) {
mContext = context;
}
public void show() {
LayoutInflater factory = LayoutInflater.from(mContext);
View view = factory.inflate(R.layout.dialog_activity, null);
AlertDialog.Builder builder = new AlertDialog.Builder((mContext));
final EditText calories = (EditText) view.findViewById(R.id.etCalories);
Bundle recieveFromActivity = getIntent().getExtras();
String strCaloreis = recieveFromActivity.getString("calories");
calories.setText(strCaloreis);
builder.setTitle(R.string.edit_log_title);
builder.setNegativeButton(R.string.create_log_negative_button,
new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setNeutralButton(R.string.create_log_neutral_button, null);
builder.setPositiveButton(R.string.create_log_positive_button, null);
builder.create().show();
builder.setView(view);
builder.create().show();
}
}
you have to extend Activity class , then only you can access getIntent()...
so your code should be like this
public class ActivityDialog extends Activity{
Context mContext;
Date mDate;
protected void onCreate(Bundle savedInstanceState){
//here you can call getIntent()
}
public void show() {
// or even from here ,you can call getIntent()
LayoutInflater factory = LayoutInflater.from(mContext);
View view = factory.inflate(R.layout.dialog_activity, null);
AlertDialog.Builder builder = new AlertDialog.Builder((mContext));
final EditText calories = (EditText) view.findViewById(R.id.etCalories);
Bundle recieveFromActivity = getIntent().getExtras();
String strCaloreis = recieveFromActivity.getString("calories");
calories.setText(strCaloreis);
builder.setTitle(R.string.edit_log_title);
builder.setNegativeButton(R.string.create_log_negative_button,
new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setNeutralButton(R.string.create_log_neutral_button, null);
builder.setPositiveButton(R.string.create_log_positive_button, null);
builder.create().show();
builder.setView(view);
builder.create().show();
}
}
Your ActivityDialog class is an Activity and thus should extend Activity. This is a general rule, but specifically your problem here is due to the fact that getIntent() is defined in Activity, so you must extend that in order to use it.
It might be because of your spelling mistake in sendToDialog.putString("caloreis", strCalories); because you later reference the extra as "calories" not "caloreis". (I tried to put this in an edit but it was uner 6 characters long...)
Im at my wits end here. I have a Class which Implements the OnClickListener cous i need the same action on Buttons accros my Application. This used to work just fine. But since I added some functionality by getting some needed data from the app preferences. startActivity throws a null pointer exception.Here is the class:
//Imports
public class CallClickListener extends Activity implements View.OnClickListener {
protected AppPreferences appPrefs;
String contactPersonName;
String contactPersonTelephone;
String name;
public CallClickListener(Context context){
Log.d("TRACE", "init CallClick");
appPrefs = new AppPreferences(context);
try {
JSONObject object = appPrefs.getConsultantObject();
contactPersonName = object.getString("contactPersonName");
contactPersonTelephone = object.getString("contactPersonTelephone");
name = object.getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onClick(View view) {
final View v = view;
AlertDialog.Builder alert = new AlertDialog.Builder(view.getContext());
alert.setTitle("Anrufen");
alert.setMessage("Kontakt für " + name + ", " + contactPersonName + " anrufen");
alert.setPositiveButton("Anrufen", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:"+contactPersonTelephone));
startActivity(callIntent);// this line throws the exception
}
});
alert.setNegativeButton("Abbrechen", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(v.getContext(), "Abbruch", Toast.LENGTH_SHORT).show();
}
});
alert.show();
}
}
The Strings are all there from appPrefs, i also tried with hardcoding a phonenumber just incase. the Alert works fine, but as soon as i hit the positive Button, the app crashes
I add the Listener like this:
bCall.setOnClickListener(new CallClickListener(getApplicationContext()));
I added the necessary Call permissions.
I'm fairly new to Android dev, what am I missing?
Do this.... make the context object that you passed in the constructor into a field variable. and change startActivity to context.startActivity. It will work then.
EDIT: Highlighting the full solution.
bCall.setOnClickListener(new CallClickListener(getApplicationContext()));
should be changed to YourActivityClass.this instead of getApplicationContext.
Start Activity in the same task does not work with a context object that is not an Activity. So you need to either change the context to Activity or you start the activity in a new task. Also without calling startActivity on the context provided to your constructor you were getting the NPE because your CallClickListerner has no context.
Use activity context. Also check if you have initialized bCall. If you have not you will get NullPointerException.
bCall.setOnClickListener(ActivityName.this);
Also check this link to know when to use activity context and when to use application context
When to call activity context OR application context?
Edit:
Make sure you have added permission in manifest file
<uses-permission android:name="android.permission.CALL_PHONE" />
For reference use the below. My Class extends Activity
Button b= (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v1) {
// TODO Auto-generated method stub
final View v = v1;
AlertDialog.Builder alert = new AlertDialog.Builder(v.getContext());
alert.setTitle("Anrufen");
alert.setMessage("Kontakt für " );
alert.setPositiveButton("Anrufen", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:8095992052"));
startActivity(callIntent);// this line throws the exception
}
});
alert.setNegativeButton("Abbrechen", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(v.getContext(), "Abbruch", Toast.LENGTH_SHORT).show();
}
});
alert.show();
}
});
I am creating a home automation app that has allows plugin views. I have been able to create a class as a sample plugin in a separate project (apk):
public class MyTestClass_IRDroidUIPlugIn extends Button implements IRDroidInterface{
Context mContext;
public MyTestClass_IRDroidUIPlugIn(Context context) {
super(context);
mContext = context;
setText("I was loaded dynamically! (1)");
setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// how do I show the dialog from here?
Activity.showDialog(1);
}}
);
}
public Dialog buildConfigDialog(int ID){
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setMessage("Click the Button...(1)")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
return builder.create();
}
}
I can load this class at run time and create an instance of it:
try {
final File filesDir = this.getFilesDir();
final File tmpDir = getDir("dex", 0);
final DexClassLoader classloader = new DexClassLoader( filesDir.getAbsolutePath()+"/testloadclass.apk",
tmpDir.getAbsolutePath(),
null, this.getClass().getClassLoader());
final Class<View> classToLoad =
(Class<View>) classloader.loadClass("com.strutton.android.testloadclass.MyTestClass_IRDroidUIPlugIn");
mybutton = (View) classToLoad.getDeclaredConstructor(Context.class).newInstance(this);
mybutton.setId(2);
main.addView((View)mybutton);
} catch (Exception e) {
e.printStackTrace();
}
setContentView(main);
}
protected Dialog onCreateDialog(int id) {
switch (id) {
case 1:
return ((IRDroidInterface) mybutton).buildConfigDialog(id);
}
return null;
}
I want the plugin to be able to show a configuration dialog. Is there a way I can pass the Activity object to this class so it can use .showDialog(ID). This would be ideal so that the dialog life cycle can be managed properly.
Thanks in advance.
Maybe I'm missing something, but why can't you do something like this?
public class MyTestClass_IRDroidUIPlugIn extends Button implements IRDroidInterface{
Activity mContext;
public MyTestClass_IRDroidUIPlugIn(Activity context) {
super(context);
mContext = context;
...
setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mContext.showDialog(1);
}}
);
.....
}
When you're creating this class, you're already passing Activity into this class - so just use it.