尝试连接到服务器时带有异步任务的进度条

Posted

技术标签:

【中文标题】尝试连接到服务器时带有异步任务的进度条【英文标题】:Progressbar with Async Task while trying to connect to server 【发布时间】:2020-03-13 02:24:00 【问题描述】:

我想在 AsyncTask 类的 doInbackground 方法执行后台任务时显示进度对话框,但问题是当我的服务器关闭(Wamp 服务器关闭)时,它在尝试与服务器连接时不显示进度对话框。 请在这方面提供帮助。

主类:

import android.app.AlertDialog;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.concurrent.ExecutionException;

public class MainActivity extends AppCompatActivity

    Button btnSubmitOrder;
    EditText edDealerID;
    EditText edProductID;
    EditText edQuantity;
    String stDealerID;
    String stProductID;
    String stQuantity;
    String stUnit;
    String stDate;
    String stTime;
    String stStatus;
    ProgressBar edProgress;

    Date currentDate = Calendar.getInstance().getTime();

    DatabaseSQLite objDatabaseSqlite;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        Date objDate = Calendar.getInstance().getTime();
        SimpleDateFormat df = new SimpleDateFormat("dd/MMM/yyyy");
        stDate = df.format(objDate);

        SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");
        stTime = sdf.format(objDate);

        final Spinner dropdown = findViewById(R.id.edit_unit);
        String[] items = new String[]"Box", "Packets";
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, items);
        dropdown.setAdapter(adapter);

        objDatabaseSqlite = new DatabaseSQLite(this);

        btnSubmitOrder = findViewById(R.id.btn_submitorder);
        edDealerID = findViewById(R.id.edit_dealerid);
        edProductID = findViewById(R.id.edit_productid);
        edQuantity = findViewById(R.id.edit_quantity);
        edProgress = findViewById(R.id.ed_progress);
        btnSubmitOrder.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                stDealerID = edDealerID.getText().toString();
                stProductID = edProductID.getText().toString();
                stQuantity = edQuantity.getText().toString();
                stUnit = dropdown.getSelectedItem().toString();
                stStatus = "Pending";
                BackgroundTask objBackground = new BackgroundTask(MainActivity.this);
                try 
                    String response = objBackground.execute(stDealerID, stProductID, stQuantity, stUnit, stDate, stTime, stStatus).get();
                 catch (ExecutionException e) 
                    e.printStackTrace();
                 catch (InterruptedException e) 
                    e.printStackTrace();
                
            
        );
    


BackgroundTask 类:

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

/**
 * Created by Saffi on 3/17/2016.
 */
public class BackgroundTask extends AsyncTask<String,Void,String> 

    private String response = "";
    private ProgressDialog dialog;
    Context ctx;

    BackgroundTask(Context ctx)
    
        this.ctx = ctx;
    

    @Override
    protected void onPreExecute() 
        dialog = new ProgressDialog(ctx);
        dialog.setMessage("Progress start");
        dialog.show();
    

    protected String doInBackground(String... params) 
        String sendInvoice = "http://10.0.2.2/YounasTraders/SendInvoice.php";
        String dealerId = params[0];
        String productId = params[1];
        String quantity = params[2];
        String unit = params[3];
        String date = params[4];
        String time = params[5];
        String status = params[6];
        try 
            URL objurl = new URL(sendInvoice);
            HttpURLConnection objhttpurlconnection = (HttpURLConnection) objurl.openConnection();
            objhttpurlconnection.setRequestMethod("POST");
            objhttpurlconnection.setDoOutput(true);
            objhttpurlconnection.setDoInput(true);
            OutputStream objos = objhttpurlconnection.getOutputStream();
            BufferedWriter objbuffwrite = new BufferedWriter(new OutputStreamWriter(objos, "UTF-8"));

            String data = URLEncoder.encode("dealer_id", "UTF-8") +"="+URLEncoder.encode(dealerId, "UTF-8")+"&"+
                    URLEncoder.encode("product_id", "UTF-8")+"="+URLEncoder.encode(productId, "UTF-8")+"&"+
                    URLEncoder.encode("quantity", "UTF-8")+"="+URLEncoder.encode(quantity, "UTF-8")+"&"+
                    URLEncoder.encode("unit", "UTF-8")+"="+URLEncoder.encode(unit, "UTF-8")+"&"+
                    URLEncoder.encode("date", "UTF-8")+"="+URLEncoder.encode(date, "UTF-8")+"&"+
                    URLEncoder.encode("time", "UTF-8")+"="+URLEncoder.encode(time, "UTF-8")+"&"+
                    URLEncoder.encode("status", "UTF-8")+"="+URLEncoder.encode(status, "UTF-8");
            objbuffwrite.write(data);
            objbuffwrite.flush();
            objbuffwrite.close();
            objos.close();

            InputStream objis = objhttpurlconnection.getInputStream();
            objis.close();
            objhttpurlconnection.disconnect();

            response = "Order Sent Successfully";

            return response;

         catch (MalformedURLException e) 
            e.printStackTrace();
         catch (IOException e) 
            e.printStackTrace();
        

        response = "Order Not Sent Successfully";
        return response;
    

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

    @Override
    protected void onPostExecute(String value) 
        dialog.dismiss();
    

【问题讨论】:

【参考方案1】:

问题是您正在使用 .get 方法在主线程上执行任务

第一个改变你的 AsyncTask 任务包括这个回调接口在完成你的 HTTP 请求后调用它

公共类 BackgroundTask 扩展 AsyncTask

    private CallBack callBack;

    public CallBack getCallBack() 
        return callBack;
    

    public void setCallBack(CallBack callBack) 
        this.callBack = callBack;
    

    private String response = "";
    private ProgressDialog dialog;
    Context ctx;

    BackgroundTask(Context ctx)
    
        this.ctx = ctx;
    

    @Override
    protected void onPreExecute() 
        dialog = new ProgressDialog(ctx);
        dialog.setMessage("Progress start");
        dialog.show();
    

    protected String doInBackground(String... params) 
        String sendInvoice = "http://10.0.2.2/YounasTraders/SendInvoice.php";
        String dealerId = params[0];
        String productId = params[1];
        String quantity = params[2];
        String unit = params[3];
        String date = params[4];
        String time = params[5];
        String status = params[6];
        try 
            URL objurl = new URL(sendInvoice);
            HttpURLConnection objhttpurlconnection = (HttpURLConnection) objurl.openConnection();
            objhttpurlconnection.setRequestMethod("POST");
            objhttpurlconnection.setDoOutput(true);
            objhttpurlconnection.setDoInput(true);
            OutputStream objos = objhttpurlconnection.getOutputStream();
            BufferedWriter objbuffwrite = new BufferedWriter(new OutputStreamWriter(objos, "UTF-8"));

            String data = URLEncoder.encode("dealer_id", "UTF-8") +"="+URLEncoder.encode(dealerId, "UTF-8")+"&"+
                    URLEncoder.encode("product_id", "UTF-8")+"="+URLEncoder.encode(productId, "UTF-8")+"&"+
                    URLEncoder.encode("quantity", "UTF-8")+"="+URLEncoder.encode(quantity, "UTF-8")+"&"+
                    URLEncoder.encode("unit", "UTF-8")+"="+URLEncoder.encode(unit, "UTF-8")+"&"+
                    URLEncoder.encode("date", "UTF-8")+"="+URLEncoder.encode(date, "UTF-8")+"&"+
                    URLEncoder.encode("time", "UTF-8")+"="+URLEncoder.encode(time, "UTF-8")+"&"+
                    URLEncoder.encode("status", "UTF-8")+"="+URLEncoder.encode(status, "UTF-8");
            objbuffwrite.write(data);
            objbuffwrite.flush();
            objbuffwrite.close();
            objos.close();

            InputStream objis = objhttpurlconnection.getInputStream();
            objis.close();
            objhttpurlconnection.disconnect();

            response = "Order Sent Successfully";

            return response;

         catch (MalformedURLException e) 
            e.printStackTrace();
         catch (IOException e) 
            e.printStackTrace();
        

        response = "Order Not Sent Successfully";
        return response;
    

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

    @Override
    protected void onPostExecute(String value) 
        dialog.dismiss();
        if(callBack != null)
            callBack.onResult(value);

    

    public interface CallBack
        void onResult(String value);
    

您的异步任务的第二次更改执行,在回调中获取结果

  BackgroundTask objBackground = new BackgroundTask(MainActivity.this);
        objBackground.setCallBack(new BackgroundTask.CallBack() 
            @Override
            public void onResult(String value) 
                //get here your response
            
        );
        objBackground.execute(stDealerID, stProductID, stQuantity, stUnit, stDate, stTime, stStatus);

【讨论】:

非常感谢。再次感谢您。

以上是关于尝试连接到服务器时带有异步任务的进度条的主要内容,如果未能解决你的问题,请参考以下文章

当片段视图加载是异步任务的一部分时,如何在片段加载之前显示进度条?

android:异步任务asyncTask介绍及异步任务下载图片(带进度条)

如何使用界面更新异步任务中的进度条

如何在异步任务中更新进度栏

我如何在我的异步任务类中使用圆形旋转进度条

如何关闭带有异步任务的进度对话框并避免“您的活动是不是运行错误?”