我如何在 AsyncTask 中应用 alertDialog 作为服务器响应

Posted

技术标签:

【中文标题】我如何在 AsyncTask 中应用 alertDialog 作为服务器响应【英文标题】:How i can apply alertDialog as server response in AsyncTask 【发布时间】:2018-04-23 09:03:34 【问题描述】:

我正在尝试通过cPanel Hosting 将我的项目app 与在线数据库连接起来。我使用了AlertDialog.BuildersetOnClickListener, 用于显示服务器的响应,但似乎我遇到了一些错误,任何答案将不胜感激谢谢

这是我的 java 文件。

//Calling my AsyncTask
@Override
 public void onClick(View view) 
 view.setEnabled(false);
 Intent launchactivity = new Intent(MainActivity.this,MainActivity.class);
 startActivity(launchactivity);

            tvscancontent = tvScanContent.getText().toString();
            tvscanformat = tvScanFormat.getText().toString();
            BackgroundTask backgroundTask = new BackgroundTask();
            backgroundTask.execute(tvscancontent,tvscanformat);
            finish();

            showShowView2();
           // displaynotification();

        

    );

private class BackgroundTask extends AsyncTask<String,Void,String>  // i got crash here

        Context context;
        String add_info_url;
        private Object activity;




        public BackgroundTask() 

        

        @Override
        protected void onPreExecute() 


            add_info_url = "http://www.d48.asia/shan/index.php";

            progressDialog = new ProgressDialog(MainActivity.this);
            progressDialog.setTitle("Processing...");
            progressDialog.setMessage("Authenticating...");
            progressDialog.setCancelable(false);
            progressDialog.setIndeterminate(true);
            progressDialog.setProgressStyle(progressDialog.STYLE_SPINNER);
            progressDialog.show();



        

        @Override
        protected String doInBackground(String... args) 

            String tvscancontent = args[0];
            String tvscanformat = args[1];
            String response = "";
            String line = "";

            try 
                URL url = new URL(add_info_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
                String data_string = URLEncoder.encode("tvscancontent", "UTF-8") + "=" + URLEncoder.encode(tvscancontent, "UTF-8")+ "&" +
                        URLEncoder.encode("tvscanformat", "UTF-8") + "=" + URLEncoder.encode(tvscanformat, "UTF-8");
                bufferedWriter.write(data_string);
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));

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


            return null;


        

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

        

     //Server response
        @Override
        protected void onPostExecute(final String result) 
            //Toast toast =Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG);
            //toast.setGravity(Gravity.CENTER ,0,0);
            //toast.show();
                AlertDialog.Builder alert = new AlertDialog.Builder(context); // also i got crash here
                    alert.setTitle("Third Wheel Response");
                    alert.setMessage(result);
                    alert.setCancelable(false);
                    alert.setPositiveButton("ok", new DialogInterface.OnClickListener() 
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) 
                          dialogInterface.cancel();
                        
                    );
                    AlertDialog dialogs = alert.create();
                    dialogs.show();


                if (progressDialog != null) 
                    progressDialog.dismiss();
                    SaveData.setEnabled(true);

                

错误:

11-10 08:40:23.174 4815-4815/com.thethirdwheelproject.thirdwheel E/androidRuntime: FATAL EXCEPTION: main 进程:com.thethirdwheelproject.thirdwheel,PID:4815 android.view.WindowManager$BadTokenException: 无法添加窗口——令牌android.os.BinderProxy@bc0afcf 无效;您的活动正在运行吗? 在 android.view.ViewRootImpl.setView(ViewRootImpl.java:678) 在 android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:342) 在 android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93) 在 android.app.Dialog.show(Dialog.java:316) 在 com.thethirdwheelproject.thirdwheel.MainActivity$BackgroundTask.onPostExecute(MainActivity.java:489) 在 com.thethirdwheelproject.thirdwheel.MainActivity$BackgroundTask.onPostExecute(MainActivity.java:389) 在 android.os.AsyncTask.finish(AsyncTask.java:660) 在 android.os.AsyncTask.-wrap1(AsyncTask.java) 在 android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:677) 在 android.os.Handler.dispatchMessage(Handler.java:102) 在 android.os.Looper.loop(Looper.java:154) 在 android.app.ActivityThread.main(ActivityThread.java:6077) 在 java.lang.reflect.Method.invoke(本机方法) 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 11-10 08:40:23.733 1334-1334/? E/EGL_emulation: tid 1334: eglCreateSyncKHR(1901): 错误 0x3004 (EGL_BAD_ATTRIBUTE)

【问题讨论】:

发布您的错误日志 你的上下文变量为空!! 【参考方案1】:

您的上下文变量未初始化

删除您的context 变量并改用MainActivity.this

试试这个方法

@Override
 public void onClick(View view) 
 view.setEnabled(false);
            tvscancontent = tvScanContent.getText().toString();
            tvscanformat = tvScanFormat.getText().toString();
            BackgroundTask backgroundTask = new BackgroundTask();
            backgroundTask.execute(tvscancontent,tvscanformat);
            showShowView2();
           // displaynotification();

        

    );

【讨论】:

我仍然得到这个错误先生 private class BackgroundTask extends AsyncTask // 我在这里崩溃了 dialogs.show(); //这里也是 如何调用BackgroundTask类? @ShanMichaelReyes 我运行你的代码它工作正常!!如何调用你的 AsyncTask ? 看看我的更新帖子先生,我已经发布了我如何调用我的 AsyncTask 希望您能帮助我,谢谢先生 为什么在调用BackgroundTask后完成()活动?【参考方案2】:

在构造函数中设置上下文, 像下面的东西

public BackgroundTask(Context context) 
    this.context = context;

【讨论】:

你是如何将上下文传递给你的 AsyncTask 类的? 我只是在我的 AsyncTask 类先生中分配上下文变量 但我将上下文更改为 MainActivity.this,代码有效。所以你可能有其他错误导致这种情况。发布你的错误日志和代码你如何执行你的 asynctask 类。 android.os.BinderProxy@bc0afcf 无效;您的活动正在运行吗? MainActivity 完成了???你可以检查你的代码如何以及何时调用你的 asynctask,或者你在调用 asynctask 时是否完成 MainActivity? 看看我的更新帖子先生,我已经发布了我如何调用我的 AsyncTask 希望您能帮助我,谢谢先生【参考方案3】:
        //Calling my AsyncTask
@Override
        public void onClick(View view) 
            view.setEnabled(false);

            tvscancontent = tvScanContent.getText().toString();
            tvscanformat = tvScanFormat.getText().toString();
            BackgroundTask backgroundTask =new BackgroundTask();
            backgroundTask.execute(tvscancontent,tvscanformat);

            showShowView2();
           // displaynotification();

        

    );

//将数据插入数据库进程 私有类 BackgroundTask 扩展 AsyncTask

    String add_info_url;


    public BackgroundTask() 

    

    @Override
    protected void onPreExecute() 

        add_info_url = "http://www.d48.asia/shan/index.php";

        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setTitle("Authentication Process");
        progressDialog.setMessage("Loading....");
        progressDialog.setCancelable(false);
        progressDialog.setIndeterminate(true);
        progressDialog.setProgressStyle(progressDialog.STYLE_SPINNER);
        progressDialog.show();

    

    @Override
    protected String doInBackground(String... args) 

        String tvscancontent = args[0];
        String tvscanformat = args[1];
        String response = "";
        String line = "";

        try 
            URL url = new URL(add_info_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String data_string = URLEncoder.encode("tvscancontent", "UTF-8") + "=" + URLEncoder.encode(tvscancontent, "UTF-8")+ "&" +
                    URLEncoder.encode("tvscanformat", "UTF-8") + "=" + URLEncoder.encode(tvscanformat, "UTF-8");
            bufferedWriter.write(data_string);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));

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

        return null;

    

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

    

    @Override
    protected void onPostExecute(final String result) 
        super.onPostExecute(result);
                alert = new AlertDialog.Builder(MainActivity.this);
                alert.setTitle(" Third Wheel Response");
                alert.setMessage(result);
                alert.setCancelable(false);
                alert.setPositiveButton("Thanks", new DialogInterface.OnClickListener() 
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) 
                        Intent launchactivity = new Intent(MainActivity.this,MainActivity.class);
                        startActivity(launchactivity);


                    
                );
                AlertDialog dialogs = alert.create();
                dialogs.show();

            if (progressDialog != null) 
                progressDialog.dismiss();
                SaveData.setEnabled(true);

            


    

【讨论】:

以上是关于我如何在 AsyncTask 中应用 alertDialog 作为服务器响应的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Android 中运行 AsyncTask?

在 Android 中,如何从 AsyncTask 更改 TextView? [复制]

我可以在 sencha 应用程序(Android)中使用 android AsyncTask

如何实现 Asynctask 在 ArrayAdapter 中加载图像

如何在 RecyclerView 和 AsyncTask 中禁用按钮

如何正确使用 AsyncTask? [关闭]