我正在开发一个应用程序来查看列表视图。但是存在运行时错误 这是我的代码。我在运行时获得了代码文件和异常错误。
package com.example.official2.xoxo.activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.example.official2.xoxo.R;
import com.example.official2.xoxo.app.Config;
import com.example.official2.xoxo.helper.JSONParser;
import com.example.official2.xoxo.helper.JsonWebToken;
import com.example.official2.xoxo.helper.SQLiteHandler;
import com.example.official2.xoxo.helper.ServiceHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class Products extends AppCompatActivity{
private String TAG = Products.class.getSimpleName();
//Call the config class to get the url
public Config con = new Config();
private String url_details = con.getAllProducts();
//ArrayOption-->Array Adapter--> ListView
//List View:(Views: productlist.xml)
private ListView lv;
private ProgressDialog pDialog;
// CustomListAdapter adapter;
JSONParser jsonParser = new JSONParser();
ServiceHandler sh;
ArrayList<HashMap<String, String>> productList;
// URL to get contacts JSON
private static String url = "http://uat.fxhello.com/api/shop/products";
JsonWebToken jsonWebToken;
//JSON NODE NAMES
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "payload";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "product_name";
private static final String TAG_PRICE = "price";
private static final String TAG_PIC = "profileimage";
private SQLiteHandler db;
JSONArray contacts = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_products);
productList = new ArrayList<>();
lv = (ListView) findViewById(R.id.listViewProducts);
jsonWebToken = new JsonWebToken();
// String tok = jsonWebToken.getDefaults(getContext());
String tok = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjE3MDcsImlzcyI6Imh0dHA6XC9cL3VhdC5meGhlbGxvLmNvbVwvYXBpXC9hdXRoZW50aWNhdGUiLCJpYXQiOjE0ODIzNDMzMDMsImV4cCI6MTQ4MjQyOTcwMywibmJmIjoxNDgyMzQzMzAzLCJqdGkiOiI3NGQ5ZGIwNTA3NDc2NDAwNzc2MmYzODJiNGQxZmU4MCJ9.LF2Q8KUD7hoFjBJ4fsNjYS8rCzCevsZ4g0jukBK0lj0";
Log.d("Responsetoken", tok);
new Getproduct().execute();
//populateListView();
}
/**
* Async task class to get json by making HTTP call
*/
private class Getproduct extends AsyncTask<String, Void, JSONObject> {
private JSONObject json;
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
// pDialog = new ProgressDialog(Products.this);
//pDialog.setMessage("Loading Contacts. Please wait...");
//pDialog.setIndeterminate(false);
//pDialog.setCancelable(false);
//pDialog.show();
}
protected JSONObject doInBackground(String... args) {
String userID = args[0];
sh = new ServiceHandler(userID);
String jsondata = sh.makeServiceCall(url_details, ServiceHandler.POST, null);
// JSONObject json = jsonParser.makeHttpRequest(url_details,"GET");
System.out.println("jsondata" + jsondata);
if (jsondata != null)
Log.d("Create Response", jsondata);
else {
Toast.makeText(Products.this.getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();
}
try {
json = new JSONObject(jsondata);
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
@Override
protected void onPostExecute(JSONObject s) {
// dismiss the dialog after getting all products
// pDialog.dismiss();
System.out.println(productList);
try {
JSONArray products = json.getJSONArray(TAG_PRODUCT);
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
//Storing each json item in a variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String price = c.getString(TAG_PRICE);
// String image = c.getString(TAG_PIC);
//tmp hash map for single contact
HashMap<String, String> map = new HashMap<String, String>();
//adding each child node to HashMap => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_PRICE, price);
// map.put(TAG_PIC,image);
productList.add(map);
// adding contact to contact list
productList.add(map);
// Dismiss the progress dialog
//if (pDialog.isShowing())
// pDialog.dismiss();
ListAdapter adapter = new SimpleAdapter(
Products.this, productList,
R.layout.productlist, new String[]{TAG_ID, TAG_NAME,
TAG_PRICE}, new int[]{R.id.name,
R.id.email, R.id.mobile});
lv.setAdapter(adapter);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
}
}
}
ServiceHandler类文件。我使用此代码从服务处理程序
获取数据package com.example.official2.xoxo.helper;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
/**
* Created by Official 2 on 12/19/2016.
*/
public class ServiceHandler {
static InputStream is = null;
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
private String token;
private String refresh_url = "application/vnd.fxhello.v1+json";
public ServiceHandler() {
}
public ServiceHandler(String token) {
this.token = token;
}
/**
* Making service call
* @url - url to make request
* @method - http request method
* */
/**
* Making service call
* @url - url to make request
* @method - http request method
* @params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
String tok = token;
Log.d("Responsetoken", tok);
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("Authorization","Bearer "+tok);
httpGet.setHeader("Accept", refresh_url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
response = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error: " + e.toString());
}
return response;
}
public String makeADDCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
String tok = token;
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
httpPost.setHeader("Authorization","Bearer "+tok);
httpPost.setHeader("Accept", refresh_url);
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
String tok = token;
Log.d("Responsetoken", tok);
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("Authorization",tok);
httpGet.setHeader("Accept", refresh_url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
response = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error: " + e.toString());
}
return response;
}
}
我认为这是错误
FATAL EXCEPTION: AsyncTask #1
Process: com.example.official2.xoxo, PID: 30695
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
at com.example.official2.xoxo.activity.Products$Getproduct.doInBackground(Products.java:97)
at com.example.official2.xoxo.activity.Products$Getproduct.doInBackground(Products.java:95)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
这是服务器端值---------------------------
答案 0 :(得分:0)
您的联系人JsonArray为空。
for (int i = 0; i < contacts.length(); i++) {}
应该是
JSONArray products = json.getJSONArray(TAG_PRODUCT)
for (int i = 0; i < products.length(); i++) {}
答案 1 :(得分:0)
我认为doInBackground方法中的toast导致问题...因为在这个方法中你无法与UI线程通信... PreExecute和PostExecute方法都可以。
答案 2 :(得分:0)
您的stacktrace链接到:
target="_blank"
这与此行相对应:<a href="http://www.google.com" target="_blank">Click Here</a>
这一行是一个数组,它解释了ArrayIndexOutOfBoundsException
正是由于这个原因:
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
at com.example.official2.xoxo.activity.Products$Getproduct.doInBackground(Products.java:97)
at com.example.official2.xoxo.activity.Products$Getproduct.doInBackground(Products.java:95)
初始化getproduct时,你永远不会传递任何参数,因此数组索引为0,因此导致异常