从数据库检索数据的响应延迟给了我空值

时间:2018-11-12 23:21:04

标签: android

我这样声明变量“ title”:

static String title;

title应该出现在警报生成器中。当我显示警报生成器时,它第一次给我(标题)一个空值,而第二次给我一个真实值。

我在handleResult(Result结果)中实现两个方法后创建了一个构建器

  1. getAttName()
  2. update()

每个人都应该与数据库建立连接(来自不同的表和不同的PHP函数)。另外,我需要按此顺序实施 如何解决这个问题?

package com.example.lenovo.tactic4;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
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.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.zxing.Result;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
import static android.Manifest.permission.CAMERA;



import android.content.Intent;

public class ScanActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler{
    private static final int REQUEST_CAMERA = 1;
    private ZXingScannerView scannerView;
    String Attendee_ID;
    InputStream is=null;
    String result=null;
    String line=null;
    private static int camId = Camera.CameraInfo.CAMERA_FACING_BACK;
    int code;
    boolean updateFinish = false;
    public String eventID,subevent_ID;
    String attendeeName;
    private String URL_Scan_Update="http://192.168.1.5/phpApp/updateScanApp.php";
    String URL_AttendeeName= "http://192.168.1.5/phpApp/getAttNameApp.php?Attendee_ID=";
    static String title ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan);

        eventID = getIntent().getExtras().getString("eventID","");
        subevent_ID = getIntent().getExtras().getString("eventIdSubSelect","");
        scannerView = new ZXingScannerView(this);
        setContentView(scannerView);

        int currentApiVersion = Build.VERSION.SDK_INT;

        if(currentApiVersion >=  Build.VERSION_CODES.M)
        {
            if(checkPermission())
            {
                // Toast.makeText(getApplicationContext(), "Permission already granted!", Toast.LENGTH_LONG).show();
            }
            else
            {
                requestPermission();
            }
        }
    }

    private boolean checkPermission()
    {
        return (ContextCompat.checkSelfPermission(getApplicationContext(), CAMERA) == PackageManager.PERMISSION_GRANTED);
    }

    private void requestPermission()
    {
        ActivityCompat.requestPermissions(this, new String[]{CAMERA}, REQUEST_CAMERA);
    }

    @Override
    public void onResume() {
        super.onResume();

        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion >= android.os.Build.VERSION_CODES.M) {
            if (checkPermission()) {
                if(scannerView == null) {
                    scannerView = new ZXingScannerView(this);
                    setContentView(scannerView);
                }
                scannerView.setResultHandler(this);
                scannerView.startCamera();
            } else {
                requestPermission();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        scannerView.stopCamera();
    }
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CAMERA:
                if (grantResults.length > 0) {

                    boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                    if (cameraAccepted){
                        Toast.makeText(getApplicationContext(), "Permission Granted, Now you can access camera", Toast.LENGTH_LONG).show();
                    }else {
                        Toast.makeText(getApplicationContext(), "Permission Denied, You cannot access and camera", Toast.LENGTH_LONG).show();
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            if (shouldShowRequestPermissionRationale(CAMERA)) {
                                showMessageOKCancel("You need to allow access to both the permissions",
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                                    requestPermissions(new String[]{CAMERA},
                                                            REQUEST_CAMERA);
                                                }
                                            }
                                        });
                                return;
                            }
                        }
                    }
                }
                break;
        }
    }

    private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
        new android.support.v7.app.AlertDialog.Builder(ScanActivity.this)
                .setMessage(message)
                .setPositiveButton("OK", okListener)
                .setNegativeButton("Cancel", null)
                .create()
                .show();
    }

    @Override
    public void handleResult(Result result) {

        Attendee_ID = result.getText();
      //  Log.d("QRCodeScanner", result.getText());
       // Log.d("QRCodeScanner", result.getBarcodeFormat().toString());
        getAttName();
        update(eventID,Attendee_ID,subevent_ID);
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {

            finish();
        }
    });

    builder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            Intent intent = new Intent(ScanActivity.this, PrintActivity.class);
            intent.putExtra("event_ID", eventID);
            intent.putExtra("Attendee_ID", Attendee_ID);
            startActivity(intent);
        }
    });
        builder.setMessage(title + "\n" + "do you want to print?");
    builder.create().show();


    }

    private void update( final String event_ID ,final String Attendee_ID ,final String subevent_ID) {

        RequestQueue queue = Volley.newRequestQueue(this);

        StringRequest postRequest = new StringRequest(Request.Method.POST, URL_Scan_Update,
                new Response.Listener<String>()
                {
                    @Override
                    public void onResponse(String response) {

                        Log.d("Update: ",""+response);

                        try {
                            JSONObject jsonObject = new JSONObject(response);

                            if(jsonObject.getInt("value")==1){

                                 title = "welcome " +attendeeName +" login successful ";
                            }
                            else {

                                title = "welcome " +attendeeName +" you already login ";

                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // error
                        Toast.makeText(ScanActivity.this,"Error",Toast.LENGTH_LONG).show();
                    }
                }
        ) {
            @Override
            protected Map<String, String> getParams()
            {
                Map<String, String>  params = new HashMap<String, String>();
                params.put("event_ID", event_ID);
                params.put("Attendee_ID", Attendee_ID);
                params.put("subevent_ID", subevent_ID);

                return params;
            }
        };
        queue.add(postRequest);

    }
    private void getAttName(){
        StringRequest stringRequest = new StringRequest(Request.Method.GET,
                URL_AttendeeName+Attendee_ID,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        try {
                            JSONObject jObj = new JSONObject(response);
                            attendeeName = jObj.getString("name");

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        if(error != null){

                            Toast.makeText(getApplicationContext(), "Something went wrong.", Toast.LENGTH_LONG).show();
                        }
                    }
                }

        );

        MySingleton.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
    }

    public void onPointerCaptureChanged(boolean hasCapture) {

    }

}

1 个答案:

答案 0 :(得分:0)

当您在<td> {{$participant->vt_avg}}, @if($participant->vt_avg > 85) x @else y @endif </td> 内调用update()时,将启动一个新的异步网络调用,并在handleResult()上更新标题。 但是这里要注意的是,网络调用发生在后台线程上,当调用完成时,您会在活动中收到onResponse()方法回调。

要解决此问题,

  1. 您必须从onResponse()删除警报对话框调用
  2. 并从handleResult()方法内部调用警报对话框

编辑:

示例:

onResponse()

(仍然可能存在一些简单的错误,例如变量命名或访问,请尝试解决它们,因为我没有完整的代码)