0

I have a showAlert method in my AddImages.java class following is it's implementation

//show Alert box
public void showAlert(String title, String message) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
    builder.setTitle(title);
    builder.setMessage(message);
    builder.setNeutralButton("Dismiss", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
    builder.show();
}

I want this method in my AddCateogory.java file so I called the method by using the new operator like follow

package com.example.lenovo.jdstudio;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.support.v7.app.AlertDialog;
import android.widget.Toast;


/**
 * A simple {@link Fragment} subclass.
 */
public class AddCategory extends Fragment {

    EditText mCategory;
    Button mSbtButton;
    public AddCategory() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_add_category, container, false);

        //initialise variable
        mCategory = (EditText) v.findViewById(R.id.edit_add_category);
        mSbtButton = (Button) v.findViewById(R.id.category_submit_button);

        //set clickEvent on the submit button
        mSbtButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(isValid())
                {
                    startAdding();
                }
                else{
                   //Method from the AddImages.java
                    new AddImages().showAlert("Error", "Please fill all the details");   
                }
            }
        });


        return v;
    }


    // Add categoty value to the database
    private void startAdding() {
    }


    // checks the field is empty or not
    private boolean isValid() {
        String category_value = mCategory.getText().toString().trim();
        if(!TextUtils.isEmpty(category_value)){
            return true;
        }
        return false;
    }

}

But it gives me error like follow

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.lenovo.jdstudio, PID: 20537
                  java.lang.NullPointerException
                      at android.support.v7.app.AlertDialog.resolveDialogTheme(AlertDialog.java:114)
                      at android.support.v7.app.AlertDialog$Builder.<init>(AlertDialog.java:294)
                      at com.example.lenovo.jdstudio.AddImages.showAlert(AddImages.java:168)
                      at com.example.lenovo.jdstudio.AddCategory$1.onClick(AddCategory.java:47)
                      at android.view.View.performClick(View.java:4463)
                      at android.view.View$PerformClick.run(View.java:18770)
                      at android.os.Handler.handleCallback(Handler.java:808)
                      at android.os.Handler.dispatchMessage(Handler.java:103)
                      at android.os.Looper.loop(Looper.java:193)
                      at android.app.ActivityThread.main(ActivityThread.java:5333)
                      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:828)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644)
                      at dalvik.system.NativeStart.main(Native Method)
Disconnected from the target VM, address: 'localhost:8604', transport: 'socket'

Since i am extending Fragment class already i can't extend AddImages.java. so what is the proper way to do the task.. Please help me to get rid of this

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115

2 Answers2

2

Try to pass the Context and make your method static

public static void showAlert(Context context, String title, String message) {
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setTitle(title);
    builder.setMessage(message);
    builder.setNeutralButton("Dismiss", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
    builder.show();
}

than call like this if your showAlert() method in your parent activity

(YouActivity)getActivity()).showAlert((getActivity(), "Title", "Message"); // pass the context

if your showAlert() in other class than use this

showAlert((getActivity(), "Title", "Message"); // pass the context
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
Goku
  • 9,102
  • 8
  • 50
  • 81
  • 1
    If the method is declared static, you can call it like `AddImages.showAlert(getActivity(), "Error", "Please fill all the details");` – Yuliwee Jan 06 '18 at 09:05
  • instead of `getActivity()` can i use the `getContext()` –  Jan 06 '18 at 09:13
  • @AakashBidlan yes you can use it – Goku Jan 06 '18 at 09:14
  • @Prem what Md.ibrahim khalil is saying does that right? –  Jan 06 '18 at 09:18
  • @AakashBidlan please read this https://stackoverflow.com/questions/7026507/why-are-static-variables-considered-evil – Goku Jan 06 '18 at 09:20
  • @AakashBidlan and this also https://stackoverflow.com/questions/2671496/java-when-to-use-static-methods – Goku Jan 06 '18 at 09:22
-2
((MainActivity)getActivity()).showAlert(); 

Dont use static.Its a very bad practice.Instead of this use above code.

  • can i know the reason ? –  Jan 06 '18 at 09:15
  • 1
    The code you proposed will not work. Also, static methods can be useful if used correctly. – Yuliwee Jan 06 '18 at 09:16
  • Yes, static methods are totally okay for Utility classes. Be careful otherwise. In this thread, there are some good answers when not to use it if you are interested: https://stackoverflow.com/questions/1766715/when-not-to-use-the-static-keyword-in-java – Yuliwee Jan 06 '18 at 09:33
  • there’s a bracket was missing.see the updated answer. i have added.and it will work. – Md.ibrahim khalil Jan 06 '18 at 11:49