Android - 从Fragment显示AlertDialog期间出错

时间:2017-03-21 16:04:20

标签: java android object reference null

我正在尝试发送和接收数据,但我有这个错误:

FATAL EXCEPTION: main
Process: smaa.smaa, PID: 4051
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.Context.getTheme()' on a null object reference
at android.support.v7.app.AlertDialog.resolveDialogTheme(AlertDialog.java:113)
at android.support.v7.app.AlertDialog$Builder.<init>(AlertDialog.java:291)
at smaa.smaa.BackgroundT.onPreExecute(BackgroundT.java:46)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:613)
at android.os.AsyncTask.execute(AsyncTask.java:560)
at smaa.smaa.FirstFragment.onClick(FirstFragment.java:44)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22260)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

这是我的片段:

public class FirstFragment extends Fragment implements View.OnClickListener {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_first, container, false);
        Button btn1 = (Button)v.findViewById(R.id.btn1);
        btn1.setOnClickListener(this);
        return v;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn1:
                String method = "see";
                BackgroundT backgroundT = new BackgroundT(this);
                backgroundT.execute(method);
                break;
        }
    }
}

我的BackgroundTask:

public class BackgroundT extends AsyncTask<String,Void,String> {
    AlertDialog alertDialog;
    Context ctx;
    String response = "";

    private Context applicationContext;
    private Context activity;

    public BackgroundT(Context ctx) {
        this.ctx = ctx;
    }

    public BackgroundT(FirstFragment firstFragment) {
        this.ctx = ctx;
    }


    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        alertDialog = new AlertDialog.Builder(ctx).create();
        alertDialog.setTitle("Ver Tickets");
    }

    @Override
    protected String doInBackground(String... params) {
        String see_url = "https://smaa.000webhostapp.com/androidver.php";

        String method = params[0];

        if (method.equals("see")) {
            String login_name = params[1];
            String login_pass = params[2];
            String test = "test";
            try {
                URL url = new URL(see_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);

                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));

                String data = URLEncoder.encode("test", "UTF-8") + "=" + URLEncoder.encode(test, "UTF-8");

                bufferedWriter.write(data);
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();

                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));


                String line = "";

                while ((line = bufferedReader.readLine()) != null) {
                    response += line;
                }

                bufferedReader.close();
                inputStream.close();

                httpURLConnection.disconnect();

                return response;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {

        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(String result) {
        Toast.makeText(ctx, response, Toast.LENGTH_LONG).show();
    }
}

我知道问题出现在Context或ctx中,但我不知道在哪里,我已经使用过这样的东西而且之前有用,所以我现在不知道是什么问题,这是一个工作版本:

BackgroundTask:http://pastebin.com/UnxaSV2X

MainActivity:http://pastebin.com/rk5jufBc

---编辑---

感谢@ rafsanahmad007,这是我修复的内容:

片段代码:

String method = "see";
BackgroundT backgroundT = new BackgroundT(getActivity());
backgroundT.execute(method);
break;

BackgroundTask代码:

public BackgroundT(FragmentActivity activity) {
    this.ctx = activity;
}

还有一个错误,我后来在这里解决了:

String login_name = params[1];
String login_pass = params[2];

这给了我一个错误,因为我没有使用它,谢谢大家。

2 个答案:

答案 0 :(得分:0)

public BackgroundT(FirstFragment firstFragment) {
    this.ctx = ctx;
}

注意ctx = ctx,因此它为null并且在构造警报时失败

答案 1 :(得分:0)

您需要“活动”上下文才能在AlertDialog

中显示Fragment

而不是;

BackgroundT backgroundT = new BackgroundT(this);
backgroundT.execute(method);

试试这个:

BackgroundT backgroundT = new BackgroundT(getActivity());
backgroundT.execute(method);

修改

同时编辑构造函数:

public BackgroundT(FragmentActivity activity) {
    this.ctx = activity;
}