代码之家  ›  专栏  ›  技术社区  ›  Fadly Dzil

AlertDialog.Builder从API请求中显示空值

  •  0
  • Fadly Dzil  · 技术社区  · 7 年前

    我有一个restapi,我自己用PHP构建。

    这是我的密码:

    import android.content.DialogInterface;
    import android.content.pm.PackageManager;
    import android.os.Build;
    import android.support.v4.app.ActivityCompat;
    import android.support.v4.content.ContextCompat;
    import android.support.v7.app.AlertDialog;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.widget.Toast;
    import com.android.volley.Request;
    import com.android.volley.RequestQueue;
    import com.android.volley.Response;
    import com.android.volley.VolleyError;
    import com.android.volley.toolbox.JsonObjectRequest;
    import com.android.volley.toolbox.Volley;
    import com.google.zxing.Result;
    import me.dm7.barcodescanner.zxing.ZXingScannerView;
    import org.json.JSONObject;
    
    
    
    public class InfoCoilActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {
        private static final int REQUEST_CAMERA = 1;
        private ZXingScannerView scannerView;
        private String responseResult;
    
        @Override
        public void handleResult(Result result) {
            final String scanResult = result.getText();
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Result Scan For Info Coil");
            builder.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    scannerView.resumeCameraPreview(InfoCoilActivity.this);
                }
            });
            builder.setMessage("Result " + handleRequestApi(scanResult));
            AlertDialog alert = builder.create();
            alert.show();
        }
    
        public String handleRequestApi(String textCode) {
            String URL = "http://my-web.com/api/morowali-coil/" + textCode;
            final RequestQueue requestQueue = Volley.newRequestQueue(this);
    
            JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
                    Request.Method.GET,
                    URL,
                    null,
                    new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {
                            responseResult = response.toString();
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            responseResult = error.toString();
                        }
                    }
            );
            requestQueue.add(jsonObjectRequest);
            return responseResult;
        }
    }
    

    请进来看看 builder.setMessage("Result " + handleRequestApi(scanResult)); 当我第一次扫描二维码时,我收到了一条信息

    Result null
    

    我试着在logcat中看到,在第一个镜头中,成功地得到如下json响应:

    10-17 14:07:01.492 11568-11568/com.dzil.myapplication E/Rest Response:: {"id":889,"coil_number":"QLZ18K01014A","planning_delivery":"WAREHOUSE","billet_number":"Y180908B03-4","width":0,"thickness":"0.00","grade":"S30403","size":"1.84*1250*C","actual_size":"1.85*1249","quantity":1,"nett":20930,"gross":21016,"customer":"IIS","contract_number":"IRNC18\/CC1137","procurement_contract_number":"","white_roll_number":"N1809100738","production_date":"2018-09-21","standard_eksekutif":"EN 10028-7","order_number":"ET18\/CC708001-IIS","unstuffing_plan":"2018-10-14","length":1143,"production_warehouse":"6#库","port":"Surabaya","vessel":null,"vessel_id":2,"urut":889,"lokasi":null,"lokasi_terakhir":null,"nama_file":"Copy of morowali-surabaya-example-format-data","created_by":"1","updated_by":"1","created_at":"2018-10-12 16:09:46","updated_at":"2018-10-12 16:09:46"}
    

    但当我在第二个镜头中再次尝试时,我得到上面那些类似json的json是很正常的

    Result {"id":889,"coil_number":"QLZ18K01014A","planning_delivery":"WAREHOUSE","billet_number":"Y180908B03-4","width":0,"thickness":"0.00","grade":"S30403","size":"1.84*1250*C","actual_size":"1.85*1249","quantity":1,"nett":20930,"gross":21016,"customer":"IIS","contract_number":"IRNC18\/CC1137","procurement_contract_number":"","white_roll_number":"N1809100738","production_date":"2018-09-21","standard_eksekutif":"EN 10028-7","order_number":"ET18\/CC708001-IIS","unstuffing_plan":"2018-10-14","length":1143,"production_warehouse":"6#库","port":"Surabaya","vessel":null,"vessel_id":2,"urut":889,"lokasi":null,"lokasi_terakhir":null,"nama_file":"Copy of morowali-surabaya-example-format-data","created_by":"1","updated_by":"1","created_at":"2018-10-12 16:09:46","updated_at":"2018-10-12 16:09:46"}
    

    请指教!

    4 回复  |  直到 7 年前
        1
  •  2
  •   marmor    7 年前

    handleRequestApi 是一个异步方法,意味着它返回 之前 从API中获取任何值。

    所以 return responseResult 将始终返回null的初始值。

    请参见: Asynchronous vs synchronous execution, what does it really mean?

        2
  •  2
  •   Bruno    7 年前

    你不能这样做,因为异步。第一个快照返回null,因为 handleRequestApi() 方法没有请求的响应。第二个镜头返回的东西,因为缓存。

    要正确使用异步,必须直接在 onResponse() 回拨。要显示警报对话框吗?做这样的事

    @Override
    public void onResponse(JSONObject response) {
        responseResult = response.toString();
        AlertDialog.Builder builder = new AlertDialog.Builder(InfoCoilActivity .this);
        builder.setTitle("Result Scan For Info Coil");
        builder.setPositiveButton("Continue", new DialogInterface.OnClickListener() 
        {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                scannerView.resumeCameraPreview(InfoCoilActivity.this);
            }
        });
        builder.setMessage("Result " + response);
        AlertDialog alert = builder.create();
        alert.show();
    }
    
        3
  •  1
  •   Aaron    7 年前

    由于函数 handleRequestApi(scanResult) 异步调用,因此它显示为null,因为 responseResult 在您的活动中,当时为空。

    要解决此问题,应仅在收到响应时创建对话框:

    new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle(...)
                .setPositiveButton(...)
                .setMessage(response.toString())
                .create();
            dialog.show();
        }
    }, ...
    
        4
  •  0
  •   Sina Khorshidian    7 年前

    此错误是由于使用截击和警报对话框时的异步性造成的。您可以创建如下代码所示的自定义界面:

    public interface VolleyResponseListener{
        void onVolleyResponse(String response);        
    }
    


    public class InfoCoilActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler, VolleyResponseListener {
        private static final int REQUEST_CAMERA = 1;
        private ZXingScannerView scannerView;
        private String responseResult;
        private VolleyResponseListener volleyResponseListener;
    
    public interface VolleyResponseListener{
        void onVolleyResponse(String response);        
    }
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            volleyResponseListener = (VolleyResponseListener) this;
    
            //... your codes...
    
        }
    
        @Override
        public void handleResult(Result result) {
    
            handleRequestApi(result.getText());
    
        }
    
        public void handleRequestApi(String textCode) {
            String URL = "http://my-web.com/api/morowali-coil/" + textCode;
            final RequestQueue requestQueue = Volley.newRequestQueue(this);
    
            JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
                    Request.Method.GET,
                    URL,
                    null,
                    new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {
                            volleyResponseListener.onVolleyResponse(response.toString());
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            volleyResponseListener.onVolleyResponse(error.toString());
                        }
                    }
            );
            requestQueue.add(jsonObjectRequest);
        }
    
        @Override
        public void onVolleyResponse(String response){
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Result Scan For Info Coil");
            builder.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    scannerView.resumeCameraPreview(InfoCoilActivity.this);
                }
            });
            builder.setMessage("Result " + response);
            AlertDialog alert = builder.create();
            alert.show();
        }
    
    }
    

    注意: implements onCreate .