如何调用另一个类的方法?

时间:2018-01-06 09:00:21

标签: java android android-fragments nullpointerexception android-alertdialog

我的showAlert课程中有一个AddImages.java方法,以下是它的实现

//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();
}

我想在AddCateogory.java文件中使用此方法,因此我使用 new 运算符调用该方法,如关注

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;
    }

}

但它给我一个错误,如关注

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'

因为我正在扩展Fragment类,所以我无法扩展AddImages.java。那么完成任务的正确方法是什么..请帮我摆脱这个

2 个答案:

答案 0 :(得分:2)

尝试传递Context并制作方法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();
}
如果你的父活动中的showAlert()方法

,请按照这样的方式调用
(YouActivity)getActivity()).showAlert((getActivity(), "Title", "Message"); // pass the context

如果您的showAlert()在其他课程中使用此

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

答案 1 :(得分:-2)

((MainActivity)getActivity()).showAlert(); 

不要使用static.Its是一种非常糟糕的做法。而不是使用上面的代码。