我在使这段代码工作时遇到了很多问题。 我的主要活动是使用ZXing扫描条形码,然后我想获取该扫描的结果并用它查询我的API。我知道我必须使用AsyncTask来做到这一点,但我之前从未使用过,而且我遇到了很多麻烦。我的目标是在AsyncTask中查询API,然后使用生成的JSON字符串更新我的upcTxt TextView元素。我在ReadJSON代码中接下来要做什么?
这是我的主要活动代码:
public class Barcode extends Activity implements OnClickListener {
private Button scanBtn;
private TextView formatTxt, contentTxt, upcTxt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_barcode);
scanBtn = (Button)findViewById(R.id.scan_button);
formatTxt = (TextView)findViewById(R.id.scan_format);
contentTxt = (TextView)findViewById(R.id.scan_content);
upcTxt = (TextView)findViewById(R.id.upc);
scanBtn.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.barcode, menu);
return true;
}
public void onClick(View v){
//respond to clicks
if(v.getId()==R.id.scan_button){
//scan
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//retrieve scan result
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
//we have a result
String scanResult = scanningResult.getContents();
String scanFormat = scanningResult.getFormatName();
formatTxt.setText("FORMAT: " + scanFormat);
contentTxt.setText("CONTENT: " + scanResult);
new ReadJSON().execute(new String[] {scanResult});
} else {
Toast toast = Toast.makeText(getApplicationContext(), "No scan data received!", Toast.LENGTH_LONG);
toast.show();
}
}}
这是我的ReadJSON代码:
public class ReadJSON extends AsyncTask<String, Void, Void> {
private String content;
private TextView upcTxt;
private String url;
@Override
protected Void doInBackground(String... scanResult) {
url = "REDACTED";
content = "";
HttpClient Client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url + scanResult[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
try {
content = Client.execute(httpget, responseHandler);
// Update upcTxt here
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
提前谢谢。
更新:每当我尝试在手机上运行代码时,我都可以正常扫描条形码,但一旦尝试访问该URL,程序就会崩溃。
logcat的:
01-18 17:26:44.731: E/AndroidRuntime(24876): at com.peter.barcodetest.ReadJSON.doInBackground(ReadJSON.java:30)
01-18 17:26:44.731: E/AndroidRuntime(24876): at com.peter.barcodetest.ReadJSON.doInBackground(ReadJSON.java:1)
01-18 17:26:46.473: D/CrashAnrDetector(376): processName: com.peter.barcodetest
01-18 17:26:46.473: D/CrashAnrDetector(376): broadcastEvent : com.peter.barcodetest data_app_crash
01-18 17:26:46.913: D/PackageBroadcastService(26662): Received broadcast action=android.intent.action.PACKAGE_REPLACED and uri=com.peter.barcodetest
01-18 17:26:55.122: I/ActivityManager(376): Process com.peter.barcodetest (pid 24876) (adj 13) has died.
答案 0 :(得分:1)
我将您的代码更改为:
仅编辑ReadJSON
AsyncTask(已编辑)
public class ReadJSON extends AsyncTask<String, Integer, String> {
private String content;
private TextView upcTxt;
private String url;
private static final String TAG = "ReadJSON";
String s = "";
Context context;
ReadJSONCallBack callback;
public ReadJSONTask (Context context, ReadJSONCallBack cb) {
super();
this.callback = cb;
this.context = context;
}
@Override
protected String doInBackground(String... scanResult) {
url = "REDACTED";
HttpClient Client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url + scanResult[0]);
try {
HttpResponse response = Client.execute(httpget);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
InputStream in = response.getEntity().getContent();
Log.d(TAG, "Got response");
InputStreamReader inputStreamReader = new InputStreamReader(in);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}
Log.d(TAG, "Content: " + stringBuilder.toString());
return stringBuilder.toString();
// Update upcTxt here
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
protected void onPostExecute(String result) {
callback.setString(s);
}
// method for parsing JSON object
public String parseJSONObject(String output) {
try {
JSONArray jArray = new JSONArray(output);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
String id = jObject.getString("id");
String customer = jObject.getString("name");
String description = jObject.getString("description");
Long time = (Long) jObject.get("timeAsDate");
// do something
}
} catch (JSONException e) {
}
return description;
}
}