我开始学习开发android应用程序(希望我能理解这项很棒的技术)。
我有一个REST API,可以使用PHP构建自己。
情况是,Android应用程序扫描QR码,然后将resultScan发送到我的Rest API。
这是我的代码:
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"}
请咨询!
答案 0 :(得分:2)
handleRequestApi
是一种异步方法,这意味着它会在从您的API获取任何值之前返回。
因此return responseResult
将始终返回null的初始值。
请参阅:Asynchronous vs synchronous execution, what does it really mean? 有关异步任务的更多信息
答案 1 :(得分:2)
由于异步,您不能这样做。因为handleRequestApi()
方法没有请求的响应,所以第一个镜头返回null。第二张照片由于缓存而返回某些内容。
要正确使用异步,您必须直接在
onResponse()
回调。您要显示AlertDialog吗?做这样的事情
@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();
}
答案 2 :(得分:1)
您的对话框是立即创建的,无需等待响应,因为函数handleRequestApi(scanResult)
是异步调用的,因此它显示为null,因为您活动中responseResult
的初始值当时为null。 / p>
要解决此问题,只应在对话框收到响应时创建对话框:
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle(...)
.setPositiveButton(...)
.setMessage(response.toString())
.create();
dialog.show();
}
}, ...
答案 3 :(得分:0)
此错误是由于使用齐射和警报对话框的异步性引起的。您可以创建如下代码的自定义界面:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-hello',
template: `<h2>Check Console for Output</h2>`,
})
export class HelloComponent implements OnInit {
constructor(private route:ActivatedRoute){}
ngOnInit(){
this.route.queryParams.subscribe((query)=>{
console.log(query);
console.log("MODE",query['MODE']);//output MODE:p
});
}
}
并在您的代码中使用它。
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
。