Android Java: AlertDialog method called from another class causes null pointer exception - java

I'm trying to call a method from another class which then calls an AlertDialog method, and I've tried many things but it always causes a null pointer exception. The calling class is running a web server, and I have a RecyclerView list on the activity class containing the method being called. here's some code from the activity class with AlertDialog:
public class ListClass extends AppCompatActivity {
private WebSvr server;
private static final int PORT = 8080;
private androidx.appcompat.widget.Toolbar toolbar;
private ListView lv;
private CustomAdapter customAdapter;
public ArrayList<EditModel> editModelArrayList;
public static String[] newList = new String[20];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_server_screen);
toolbar = (androidx.appcompat.widget.Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
startWebServer();
customAdapter = new CustomAdapter(this, editModelArrayList);
lv.setAdapter(customAdapter);
}
public static boolean listUpdated;
public void updateList() {
listUpdated = false;
Runnable r = new Runnable() {
#Override
public void run() {
for (int i = 0; i < 20; i++) {
if (CustomAdapter.editModelArrayList.get(i).getEditTextValue() != "") {
newList[i] = CustomAdapter.editModelArrayList.get(i).getEditTextValue();
} else {
if (!showNotification) {
runOnUiThread(new Runnable() {
#Override
public void run() {
showNullFieldNotification(); // <------------- CALLING THIS
}
});
showNotification = true;
}
}
}
listUpdated = true;
}
};
Thread thread = new Thread(r);
thread.start();
}
boolean showNotification = false;
public void showNullFieldNotification() {
new AlertDialog.Builder(ListClass.this)
.setTitle("Warning, some fields are empty")
.setNegativeButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
showNotification = false;
}
}).show();
}
public static boolean returnListUpdated() {
return listUpdated;
}
...
}
And here's the code from my web server class:
public class WebSvr extends NanoHTTPD {
public ListClass ListClass = new ListClass();
public WebSvr(int port){
super(port);
}
#Override
public Response serve(String uri, Method method,
Map<String, String> header,
Map<String, String> parameters,
Map<String, String> files) {
ListClass.updateList(); // <--------------- THE METHOD CALLED
while (!ListClass.returnListUpdated()) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
String strResponse = Arrays.toString(ListClass.returnString());
return newFixedLengthResponse(strResponse);
}
}
It always causes null pointer exception on this line:
new AlertDialog.Builder(ListClass.this)
and where the method is called in ListClass:
showNullFieldNotification();
Error message:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.espressif.iot_esptouch_demo, PID: 18217
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:152)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:157)
at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:224)
at android.app.AlertDialog$Builder.<init>(AlertDialog.java:454)
at com.myProject.ListClass.showNullFieldNotification(ListClass.java:177)
at com.myProject.ListClass$4.run(ListClass.java:193)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6665)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:772)
If I call showNullFieldNotification() in ListClass onCreate() or from the options menu it works no problem, but when called from the WebSvr class it always causes the exception.
For context on the AlertDialog I've tried ListClass.this, getApplicationContext(), getBaseContext()... I've tried to save a context in onCreate as getApplicationContext() and use that.
I've tried to use the solution from this question to get context but that didn't work either. Would really appreciate any help.
EDIT: Forgot to mention that I had also tried to build the alert in this way:
public void showNullFieldNotification2() {
AlertDialog.Builder alert = new AlertDialog.Builder(ListClass.this);
alert.setTitle("Warning, some fields detected as being empty or having \"0\" as value");
alert.setNegativeButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
showNotification = false;
}
});
AlertDialog dialog = alert.create();
dialog.show();
}

you forgot create Alert Dialog so it null, not the context
Android simple alert dialog

Got the solution from here in answer from Dan Bray. Needed to use a static context.
Since you are calling from outside of an activity, you'll need to save the context in activity class:
public static Context context;
And inside onCreate:
context = this;
To show notification:
new Handler(Looper.getMainLooper()).post(new Runnable(){
#Override
public void run(){
new AlertDialog.Builder(context)
.setTitle("Warning, some fields are empty")
.setNegativeButton("OK",new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialogInterface,int i){
dialogInterface.cancel();
showNotification=false;
}
}).show();
}
});
The methods called in the activity class must also be public static.

Related

How can I solve Singelton is NULL problem [duplicate]

This question already has answers here:
Wait Firebase async retrieve data in Android
(2 answers)
How to wait for Firebase Task to complete to get result as an await function
(2 answers)
Firebase (android) not returning the reference for an Object
(1 answer)
getContactsFromFirebase() method return an empty list
(1 answer)
Closed 1 year ago.
I'm trying to make a student registration system and I keep these students in firestore. I don't want it to add student with same number when adding student and for this, I created a singleton class. This singleton class has a flag value. I used this flag to provide control if there is a student with the same number in the firestore.
but it always returns null. I don't understand.
I'm just sharing the necessary codes.
My add student class
private ActivityOgrenciEkleBinding binding;
private FirebaseFirestore mFirestore = FirebaseFirestore.getInstance();
private LinkedHashMap<String,String> linkedHashMap;
private OgrenciyiKontrolEt ogrenciyiKontrolEt;
Singleton singleton;
public void init(){
linkedHashMap = new LinkedHashMap<>();
singleton = Singleton.getInstance();
btn_Ogrenci_EKLE();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityOgrenciEkleBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
init();
}
public void btn_Ogrenci_EKLE(){
binding.btnEkleOgrenci.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
String email_ogr = binding.emailOgrenci.getText().toString();
String ad_ogr = binding.isimOgrenci.getText().toString();
String soyisim_ogr = binding.soyisimOgrenci.getText().toString();
String no_ogr = binding.numaraOgrenci.getText().toString();
String parola_ogr = binding.sifreOgrenci.getText().toString();
ogrenciyiKontrolEt = new
OgrenciyiKontrolEt(no_ogr,OgrenciEkleActivity.this);// I
//created object from
//control class to check students
if(email_ogr.equals("") || ad_ogr.equals("") || soyisim_ogr.equals("") || no_ogr.equals("") || parola_ogr.equals("")){
AlertDialog.Builder builder = new AlertDialog.Builder(OgrenciEkleActivity.this);
builder.setTitle("UYARI !");
builder.setMessage("Boş alan bırakmayınız !");
builder.setIcon(R.drawable.warningicon);
builder.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.show();
}
else{
ogrenciyiKontrolEt.OGR_KONTROL();
System.out.println("singleton get flag"+singleton.getflag()); //singleton returns null here and and it never
//goes into the if loop
if("100".equals(singleton.getflag())){
AlertDialog.Builder builder = new AlertDialog.Builder(OgrenciEkleActivity.this);
builder.setIcon(R.drawable.warningicon);
builder.setMessage(no_ogr+" numaralı öğrenci zaten kayıtlı lütfen farklı bir numara giriniz.");
builder.setTitle("UYARI");
builder.setPositiveButton("TAMAM", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.show();
}
else{
linkedHashMap.put("name",ad_ogr);
linkedHashMap.put("lastname",soyisim_ogr);
linkedHashMap.put("number",no_ogr);
linkedHashMap.put("email",email_ogr);
linkedHashMap.put("password",parola_ogr);
mFirestore.collection("Students").add(linkedHashMap).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(#NonNull DocumentReference documentReference) {
Toast toast = Toast.makeText(OgrenciEkleActivity.this,"Öğrenci başaralı bir şekilde eklendi.",Toast.LENGTH_LONG);
toast.show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast toast = Toast.makeText(OgrenciEkleActivity.this,"Öğrenci eklerken bir hata ile karşılaşıldı.",Toast.LENGTH_LONG);
toast.show();
}
});
}
}
}
});
}
Control class that I created to control students
public class OgrenciyiKontrolEt {
protected String ogrenci_no;
protected String firestore_ogr_no;
protected FirebaseFirestore firebaseFirestoreDb = FirebaseFirestore.getInstance();
public Context context;
Singleton singleton = Singleton.getInstance();
public OgrenciyiKontrolEt(String ogr_no,Context context){
this.ogrenci_no = ogr_no;
this.context = context;
}
public void OGR_KONTROL(){
firebaseFirestoreDb.collection("Students")
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(#NonNull QuerySnapshot queryDocumentSnapshots) {
List<DocumentSnapshot> snapshotList = queryDocumentSnapshots.getDocuments();
for(DocumentSnapshot snapshot: snapshotList ) {
firestore_ogr_no = snapshot.getString("number");
if(firestore_ogr_no.equals(ogrenci_no)) {
singleton.setflag("100"); //If there is a student with the same
number, I set the flag in the singleton to 100.
}
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast toast = Toast.makeText(context,"Bir hata ile karşılaşıldı.",Toast.LENGTH_LONG);
toast.show();
}
});
}
}
My singleton class
public class Singleton {
**EDIT**
private String flag="1";
**EDIT**
private static Singleton singleton;
private Singleton() {
}
public String getflag() {
return flag;
}
public void setflag(String flag) {
this.flag = flag;
}
public static Singleton getInstance() {
if (singleton == null) {
singleton = new Singleton();
}
return singleton;
}
}
Your flag is not initialized when you call it, Either set something as default value or initialize in constructor like
private Singleton() {
this.flag = "";
}
or call your setFlag before first occurrence of getFalg

Interstitial Ad returns a null value

I programmed an app named "Trumple Run" for android. Like the name says it is a Jump & Run game and I want to release it soon. Before that I would like to implement Interstitial Ads from AdMob. I followed the official guide for the implementation of Ads but the app always crashes when I tried to show the add. Here is some code from my MainActivity (info: I cut out code which is not relevant for the issue; the method addzeigen() is called from another class)
public class Main_activity extends Activity {
private InterstitialAd mInterstitial;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); //Fullscreen
DisplayMetrics metrics = getResources().getDisplayMetrics(); //Display größe herausfinden
V.Bildbreite = metrics.widthPixels;
V.Bildhöhe = metrics.heightPixels;
addladen();
V.v = new View(this);
setContentView(V.v);
}
public void addladen(){
mInterstitial = new InterstitialAd(this);
mInterstitial.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
AdRequest request = new AdRequest.Builder().build();
mInterstitial.loadAd(request);
}
public void addzeigen(){
if(mInterstitial.isLoaded()){
mInterstitial.show();
addladen();
}
}
I looked at the StackTrace to find the reason for the issue and this two lines indicated that the interstitial is not yet instantiated (returning a null value).
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.google.android.gms.ads.InterstitialAd.isLoaded()' on a null object reference
Because of that I added a null checker in my addladen() method to prevent a crash.
public void addzeigen(){
if(mInterstitial != null && mInterstitial.isLoaded()){
mInterstitial.show();
addladen();
}
}
But why is my Interstitial object null? Did I not instantiate it in the right way in my addladen() method? I already searched for a long time in the internet but found no solution and asked the AdMob support but they said I should ask here because it is an implementation problem. How do I have to modify my code to make sure that my Interstitial is not null? I would be really happy if you could help me.
create application to when open app, add immidiate load
public class MyApplication extends Application {
public InterstitialAd mInterstitialAd;
private AppOpenManager appOpenAdManager;
private Activity currentActivity;
private int check = 0;
public AdLoader adLoader;
#Override
public void onCreate() {
super.onCreate();
MobileAds.initialize(
this,
new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(
#NonNull InitializationStatus initializationStatus) {
}
});
appOpenAdManager = new AppOpenManager();
loadInterstitial(AD_UNIT_ID_INTERSTITIAL_ADS);
}
public void loadInterstitial(String id) {
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(
this,
id,
adRequest,
new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
mInterstitialAd = interstitialAd;
interstitialAd.setFullScreenContentCallback(
new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
mInterstitialAd = null;
}
#Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
// Called when fullscreen content failed to show.
// Make sure to set your reference to null so you don't
// show it a second time.
mInterstitialAd = null;
}
#Override
public void onAdShowedFullScreenContent() {
}
});
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
mInterstitialAd = null;
}
});
}
}
then you create class check exception happen when load and open app
public class LoadInterstitialAds {
private static LoadInterstitialAds instance;
private InterstitialAd mInterstitialAd;
public static LoadInterstitialAds getInstance() {
if (instance == null) {
return new LoadInterstitialAds();
}
return instance;
}
public void openAdsThenOpenActivity(Activity activity, InterstitialAdsListener listener) {
Application application = activity.getApplication();
if (application instanceof MyApplication) {
LoadInterstitialAds.this.mInterstitialAd = ((MyApplication) application).mInterstitialAd;
if (LoadInterstitialAds.this.mInterstitialAd != null) {
LoadInterstitialAds.this.mInterstitialAd.show(activity);
LoadInterstitialAds.this.mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
listener.onStartActivity();
((MyApplication) application).loadInterstitial(AD_UNIT_ID_INTERSTITIAL_ADS);
}
#Override
public void onAdFailedToShowFullScreenContent(#NonNull AdError adError) {
((MyApplication) application).loadInterstitial(AD_UNIT_ID_INTERSTITIAL_ADS);
listener.onStartActivity();
}
});
} else {
((MyApplication) application).loadInterstitial(AD_UNIT_ID_INTERSTITIAL_ADS);
listener.onStartActivity();
}
}
}
}
create interface listener tothe convenience of calling
public interface InterstitialAdsListener {
void onStartActivity();
}
and finally, run this code at any where you want to show
LoadInterstitialAds loadInterstitialAds = LoadInterstitialAds.getInstance();
loadInterstitialAds.openAdsThenOpenActivity(getActivity(), ()->{
// your process
});

Terminating timer in android

I am a begineer in android app development, i have stoptimertask function in my mainactivity, and a button stop in another activity. What i want to do is when i press this stop button from my 2nd activity(which is maps.class), i want the stoptimertask to stop i.e. stop the tasks. However the app crashes.
Here is my code of mainactivity.java
public class MainActivity extends FragmentActivity{
protected static final int CONTACT_PICKER_RESULT = 0;
int count=0;
Timer timer;
TimerTask timerTask;
final Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startTimer();
sendSMSMessage();
Intent toAnotherActivity = new Intent(MainActivity.this, maps.class);
startActivityForResult(toAnotherActivity, 0);
}
});
}
public void startTimer() {
timer = new Timer();
initializeTimerTask();
if(radioBtnten.isChecked()==true)
timer.schedule(timerTask, 5000, 10000);
// if(radioBtn2.isSelected()==true)
else if(radioBtnone.isChecked()==true)
timer.schedule(timerTask, 5000, 1000);
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "your message has been sent, the message(s) sent are:-"+count++,Toast.LENGTH_LONG).show();
sendSMSMessage();
}
});
}
};
}
public void stoptimertask(View v)
{
//stop the timer, if it's not already null
Toast.makeText(getApplicationContext(), "Stop button pressed",Toast.LENGTH_LONG).show();
if (timer != null)
{
timer.cancel();
timer = null;
count = 0;
}
MainActivity.this.finish();
}
}
Here is the maps.java(2nd activity)
public class maps extends FragmentActivity implements LocationListener {
MainActivity call=new MainActivity();
GoogleMap googleMap;
Button stop;
Timer timer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//show error dialog if GoolglePlayServices not available
if (!isGooglePlayServicesAvailable()) {
finish();
}
setContentView(R.layout.maps);
stop = (Button)findViewById(R.id.stop);
stop.setOnClickListener(new View.OnClickListener()
{
public void onClick(View aView)
{
Intent toAnotherActivity = new Intent(aView.getContext(), MainActivity.class);
startActivityForResult(toAnotherActivity, 0);
Toast.makeText(getApplicationContext(), "Stop button pressed",Toast.LENGTH_LONG).show();
maps.this.finish();
call.stoptimertask(aView);
}
});
here is the logcat
FATAL EXCEPTION: main
Process: com.example.textmessage, PID: 19869
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:105)
at com.example.textmessage.MainActivity.stoptimertask(MainActivity.java:167)
at com.example.textmessage.maps$1.onClick(maps.java:49)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
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)
Best use for this kind of scenario is Singleton pattern.
MainActivity.java
public class MainActivity extends FragmentActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeTools();
// Find reference of "sendBtn" with "findViewById" or other stuff
sendBtn.setOnClickListener(
new View.OnClickListener()
{
#Override
public void onClick(View v)
{
startTimer();
}
});
// Rest of your code
}
private void initializeTools()
{
// Give context to Timers instance
Timers.getInstance().giveContext(this);
}
private void startTimer()
{
// Starts the timer when you click on "sendBtn"
Timers.getInstance().startTimers();
}
}
Timers.java
public class Timers
{
private final ScheduledExecutorService scheduledExecutorService;
private final Runnable myTask;
private ScheduledFuture<?> futureTask;
private int count = 0;
private Context _context;
private static volatile Timers _timers;
private Timers()
{
super();
// Your "futureTask manager"
scheduledExecutorService = Executors.newScheduledThreadPool(5);
// Good use is to instanciate task since it won't change on runtime
myTask = new Runnable()
{
#Override
public void run()
{
// Your code to run after the delay has expired
Toast.makeText(_context, "your message has been sent, the message(s) sent are:-" + count++, Toast.LENGTH_LONG).show();
// Same as the whole example, you should use the Singleton pattern to handle communications thanks to the Singleton class "Communicator"
Communicator.getInstance().sendSMSMessage();
}
};
}
// Allow only one instance of the class running. Anyone can get reference of the class with the static function Timers.getInstance();
public static Timers getInstance()
{
if (Timers._timers == null)
{
synchronized (Timers.class)
{
if (Timers._timers == null)
{
Timers._timers = new Timers();
}
}
}
return Timers._timers;
}
// For Toasts and other useful stuff
public void giveContext(Context context)
{
this._context = context;
}
// Stop the timer
public void stopTimer()
{
if (futureTask != null)
{
futureTask.cancel(true);
}
}
// Starts the task to happen in 10 seconds
public void startTimers()
{
futureTask = scheduledExecutorService.schedule(myTask, 10, TimeUnit.SECONDS);
}
}
And inside any class of your application, use Timers.getInstance().stopTimer(); to stop the timer and Timers.getInstance().startTimer(); to start it again.
Did you try?
mTimer = new Runnable() {
#Override
public void run() {
**return;**

Dialog fire non-static methods in main activity

I have a dialog that adds items to a listview, and when an item is added I need to reset the list adapter (because if not things get weird).
I read here that I can create an event listener and listen to it in the main activity. I tried doing so but it gives me errors.
AddMovieDialog.java:
public class AddMovieDialog extends DialogFragment {
private OnFinishListener onFinishListener;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
builder.setView(inflater.inflate(R.layout.add_movie_dialog, null))
.setTitle("Add a movie")
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// stuff
if (!movieName.isEmpty()) {
// stuff
if (AddMovieDialog.this.onFinishListener != null)
AddMovieDialog.this.onFinisheListener.finish();
}
}
});
// Create the AlertDialog object and return it
return builder.create();
}
public void setOnFinishListener(OnFinishListener listener) {
this.onFinishListener = listener;
}
public interface OnFinishListener {
void finish();
}
}
In the MainActivity:
AddMovieDialog addMovieDialog = new AddMovieDialog();
addMovieDialog.setOnFinishListener(new OnFinishListener() {
public void finish() {
}
});
But it gives me a compilation error: "The method setOnFinishListener(new OnFinishListener(){}) is undefined for the type AddMovieDialog"
You need to call a method which is non-static using the object. You can't call it using just the class name.
Change to this
AddMovieDialog addMovieDialog = new AddMovieDialog();
addMovieDialog .setOnFinishListener(new OnFinishListener() {
public void finish() {
}
});
Also shouldn't
if (AddMovieDialog.this.onCloseListener != null)
AddMovieDialog.this.onCloseListener.finish();
be
if (AddMovieDialog.this.onFinishListener != null)
AddMovieDialog.this.onFinishListener.finish();
EDIT
Seem your import statement in MainActivity is wrong. It should be something like com.yourpackagename.AddMovieDialog.OnFinishListener

To execute AsyncTask from onClick(DialogInterface dialog)

Currently I have two java class, 1 with AsyncTask and another one is with extend DialogFragment.
I would like to call CreateGroupTask(AsyncTask) in ChooseAddContact java class.
I have tried several recommended ways to execute the AsyncTask java but all failed.
Any recommendation or solution to that?
public class ChooseAddContact extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.pick_add)
.setItems(R.array.contact_array, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == 0){
AddContactDialog dialog2 = new AddContactDialog();
dialog2.show(getFragmentManager(), "AddContactDialog");
} else if (which == 1){
**How should I CALL it here??
//new CreateGroupTask().execute();
//makegroup = new CreateGroupTask();
//makegroup.execute();
}**
}
});
return builder.create(); }
}
And
public class CreateGroupTask extends AsyncTask<Void, Void, String> {
private Context mContext;
private ProgressDialog pd;
public CreateGroupTask() {
}
public CreateGroupTask(Context mContext) {
super();
this.mContext = mContext;
}
#Override
protected void onPreExecute() {
pd = ProgressDialog.show(mContext, null, "Creating group...");
}
#Override
protected String doInBackground(Void... params) {
String chatId = ServerUtilities.create();
if (chatId == null) return null;
try {
...
} catch (SQLException sqle) {}
return chatId;
}
#Override
protected void onCancelled() {
pd.dismiss();
}
#Override
protected void onPostExecute(String result) {
pd.dismiss();
if (result != null) {
Toast.makeText(mContext, "Group created " + result, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(mContext, "Group creation failed. Please retry later.", Toast.LENGTH_LONG).show();
}
}
}
In Dialog Fragment
To Start the async task you need context. In dialog Fragment you can get the context by calling getActivity(); or else you can get the context or activity reference in onAttach() lifecycle method of dialog fragment. Already parametrized constructor is there better to remove zero parametrized constructor.
new CreateGroupTask(getActivity()).execute();
(OR)
private Activity activity;
onAttach(Activity activity){
this.activity=activity;
//store this activity reference
}
//Then Call
new CreateGroupTask(activity).execute();
You can create an object of the class CreateGroupTask and execute wherever you want.
CreateGroupTask createGroupTask = new CreateGroupTask();
then
` if (which == 0){ AddContactDialog dialog2 = new AddContactDialog();
dialog2.show(getFragmentManager(), "AddContactDialog");
} else if (which == 1){
createGroupTask.execute();
// Or new CreateGroupTask().execute();
}`
try this and tell us if any error
What you are missing in AsyncTask is Context. you are using mContext in below code
pd = ProgressDialog.show(mContext, null, "Creating group...");
but you are not initializing that object in default constructor.
Use getActivity while calling task
new CreateGroupTask(getActivity()).execute();
Also remove following constructor from your code
public CreateGroupTask() {
}

Categories

Resources