这是我的代码,我们在MainActivity中使用..我在MainActivity中使用以下代码,但它显示空指针异常。
public class MainActivity extends ListActivity {
// URL to get contacts JSON
private static String url = "https://swastianalytics.herokuapp.com/api/v1/fw_f/?access_token=2xbvwsIlD5gQgoSsqqb3wKiW0soLrqUSVoBBOzcxED9A1D9WFP5M6HGBQlX5aroV";
// JSON Node names
private static final String TABLE_INFO = "fw_f";
private static final String TAG_FIELDWORKER_ID = "fieldworkerid";
private static final String TAG_FW_NAME = "fw_name";
private static final String TAG_FACILITY_ID = "facility_id";
private static final String TAG_FACILITY_NAME = "facility_name";
private static final String TAG_FS_MENTOR_ID = "fs_mentor_id";
private static final String TAG_FS_MENTOR_NAME = "fs_mentor_name";
private static final String TAG_STATE_ID = "state_id";
private static final String TAG_STATE_NAME = "state_name";
private static final String TAG_REGION_ID = "region_id";
private static final String TAG_REGION_NAME = "region_name";
private static final String TAG_NATIONAL_ID = "national_id";
private static final String TAG_NATIONAL_NAME = "national_name";
private static final String TAG_TOTAL_MEMBERS = "total_members";
private static final String TAG_POSITIVE_MEMBERS = "positive_members";
private static final String TAG_ELIGIBLE_FOR_ART = "eligible_for_art";
private static final String TAG_MEMBERS_ON_ART = "members_on_art";
private static final String TAG_LOST_TO_FOLLOW_UP = "lost_to_follow_up";
private static final String TAG_MEM_NOT_MET_COUNT = "mem_not_met_count";
private static final String TAG_VULNERABLE_COUNT = "vulnerable_count";
private static final String TAG_ID_ZERO = "id_zero";
private static final String TAG_ID_ONE = "id_one";
private static final String TAG_ID_TWO = "id_two";
private static final String TAG_TOP_SCHEMES_ZERO = "top_schems_zero";
private static final String TAG_TOP_SCHEMES_ONE = "top_schems_one";
private static final String TAG_TOP_SCHEMES_TWO = "top_schems_two";
private static final String TAG_SCHEMES_ZERO = "schems_zero";
private static final String TAG_SCHEMES_ONE = "schems_one";
private static final String TAG_SCHEMES_TWO = "schems_two";
private static final String TAG_INCIDENTS_EXTREME = "incidents_extreme";
private static final String TAG_INCIDENTS_FOLLOW = "incidents_follow";
private static final String TAG_INCIDENTS_OPENED = "incidents_opened";
private static final String TAG_INCIDENTS_SEVERITY = "incidents_severity";
private static final String TAG_MEM_1_INCIDENT_WEEK = "mem_1_incident_week";
private static final String TAG_MEM_FLS_NOT_COMPLETE = "mem_fls_not_complete";
private static final String TAG_MEM_FPS_NOT_COMPLETE = "mem_fps_not_complete";
private static final String TAG_MEM_NO_BANK_ACC_PO = "mem_no_bank_acc_po";
private static final String TAG_MEM_NO_3MON_SAVINGS = "mem_no_3mon_savings";
private static final String TAG_MEM_NO_SAVINGS = "mem_no_savings";
private static final String TAG_MEM_NO_INSURANCE = "mem_no_insurance";
private static final String TAG_MEM_NO_INVESTMENT = "mem_no_investment";
private static final String TAG_MEM_DUE = "mem_due";
private static final String TAG_MEM_CHAMPIONS = "mem_champions";
private static final String TAG_DUE_COUNT = "due_count";
private static final String TAG_OVERDUE_COUNT = "overdue_count";
private static final String TAG_MEM_CHAMPIONS_PROPOSED = "mem_champions_proposed";
private static final String TAG_MEM_CHAMPIONS_APPROVED = "mem_champions_approved";
private static final String TAG_ID = "id";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
// Calling async task to get json
new GetTable().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetTable extends AsyncTask<Void, Void, Void> {
// Hashmap for ListView
ArrayList<HashMap<String, String>> tableList;
ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
WebRequest webreq = new WebRequest();
// Making a request to url and getting response
String jsonStr = webreq.makeWebServiceCall(url, WebRequest.GET);
Log.d("Response: ", "> " + jsonStr);
tableList = ParseJSON(jsonStr);
// JSONArray jsonArray=jsonStr.makeWebSer(url);
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, tableList,
R.layout.list_item, new String[]{TAG_FIELDWORKER_ID,
TAG_FW_NAME,TAG_FACILITY_ID,TAG_FACILITY_NAME}, new int[]{
R.id.fieldworkerid, R.id.fw_name,R.id.facility_id,
R.id.facility_name});
setListAdapter(adapter);
}
}
private ArrayList<HashMap<String, String>> ParseJSON(String json) {
if (json != null) {
try {
// Hashmap for ListView
ArrayList<HashMap<String, String>> tableList = new ArrayList<HashMap<String, String>>();
// JSONObject jsonObj = new JSONObject(json);
// Getting JSON Array node
JSONArray tableFields = new JSONArray(TABLE_INFO);
// looping through All tableFields
for (int i = 0; i < tableFields.length(); i++) {
//c=new JSONObject();
JSONObject c = tableFields.getJSONObject(i);
//JSONObject c=(JSONObject)tableFields.get(i);
String fieldworkerid = c.getString(TAG_FIELDWORKER_ID);
String fw_name = c.getString(TAG_FW_NAME);
String facility_id = c.getString(TAG_FACILITY_ID);
String facility_name = c.getString(TAG_FACILITY_NAME);
Log.d(TAG_FIELDWORKER_ID,fieldworkerid);
Log.d(TAG_FW_NAME,fw_name);
Log.d(TAG_FACILITY_ID,facility_id);
Log.d(TAG_FACILITY_NAME,facility_name);
/* String fs_mentor_id = c.getString(TAG_FS_MENTOR_ID);
String fs_mentor_name = c.getString(TAG_FS_MENTOR_NAME);
String state_id = c.getString(TAG_STATE_ID);
String state_name = c.getString(TAG_STATE_NAME);
String region_id = c.getString(TAG_REGION_ID);
String region_name = c.getString(TAG_REGION_NAME);
String national_id = c.getString(TAG_NATIONAL_ID);
String national_name = c.getString(TAG_NATIONAL_NAME);
String total_members = c.getString(TAG_TOTAL_MEMBERS);
String positive_members = c.getString(TAG_POSITIVE_MEMBERS);
String eligible_for_art = c.getString(TAG_ELIGIBLE_FOR_ART);
String members_on_art = c.getString(TAG_MEMBERS_ON_ART);
String lost_to_follow_up = c.getString(TAG_LOST_TO_FOLLOW_UP);
String mem_not_met_count = c.getString(TAG_MEM_NOT_MET_COUNT);
String vulnerable_count = c.getString(TAG_VULNERABLE_COUNT);
String id_zero = c.getString(TAG_ID_ZERO);
String id_one = c.getString(TAG_ID_ONE);
String id_two = c.getString(TAG_ID_TWO);
String top_schems_zero = c.getString(TAG_TOP_SCHEMES_ZERO);
String top_schems_one = c.getString(TAG_TOP_SCHEMES_ONE);
String top_schems_two = c.getString(TAG_TOP_SCHEMES_TWO);
String schems_zero = c.getString(TAG_SCHEMES_ZERO);
String schschems_one = c.getString(TAG_SCHEMES_ONE);
String schems_two = c.getString(TAG_SCHEMES_TWO);
String incidents_extreme = c.getString(TAG_INCIDENTS_EXTREME);
String incidents_follow = c.getString(TAG_INCIDENTS_FOLLOW);
String incidents_opened = c.getString(TAG_INCIDENTS_OPENED);
String incidents_severity = c.getString(TAG_INCIDENTS_SEVERITY);
String mem_1_incident_week = c.getString(TAG_MEM_1_INCIDENT_WEEK);
String mem_fls_not_complete = c.getString(TAG_MEM_FLS_NOT_COMPLETE);
String mem_fps_not_complete = c.getString(TAG_MEM_FPS_NOT_COMPLETE);
String mem_no_bank_acc_po = c.getString(TAG_MEM_NO_BANK_ACC_PO);
String mem_no_3mon_savings = c.getString(TAG_MEM_NO_3MON_SAVINGS);
String mem_no_savings = c.getString(TAG_MEM_NO_SAVINGS);
String mem_no_insurance = c.getString(TAG_MEM_NO_INSURANCE);
String mem_no_investment = c.getString(TAG_MEM_NO_INVESTMENT);
String mem_due = c.getString(TAG_MEM_DUE);
String mem_champions = c.getString(TAG_MEM_CHAMPIONS);
String due_count = c.getString(TAG_DUE_COUNT);
String overdue_count = c.getString(TAG_OVERDUE_COUNT);
String mem_champions_proposed = c.getString(TAG_MEM_CHAMPIONS_PROPOSED);
String mem_champions_approved = c.getString(TAG_MEM_CHAMPIONS_APPROVED);
String id = c.getString(TAG_ID);*/
/* // Phone node is JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);*/
// tmp hashmap for single table
HashMap<String, String> table = new HashMap<String, String>();
// adding each child node to HashMap key => value
table.put(TAG_FIELDWORKER_ID, fieldworkerid);
table.put(TAG_FW_NAME, fw_name);
table.put(TAG_FACILITY_ID, facility_id);
table.put(TAG_FACILITY_NAME, facility_name);
// adding table to tablelist
tableList.add(table);
}
return tableList;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
return null;
}
}
}
这是http代码......
public class WebRequest {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
//Constructor with no parameter
public WebRequest() {
}
/**
* Making web service call
*
* @url - url to make request
* @requestmethod - http request method
*/
public String makeWebServiceCall(String url, int requestmethod) {
return this.makeWebServiceCall(url, requestmethod, null);
}
/**
* Making service call
*
* @url - url to make request
* @requestmethod - http request method
* @params - http request params
*/
public String makeWebServiceCall(String urladdress, int requestmethod, HashMap<String, String> params) {
URL url;
String response = "";
try {
url = new URL(urladdress);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setDoInput(true);
conn.setDoOutput(true);
if (requestmethod == POST) {
conn.setRequestMethod("POST");
} else if (requestmethod == GET) {
conn.setRequestMethod("GET");
}
if (params != null) {
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
writer.write(result.toString());
writer.flush();
writer.close();
os.close();
}
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
response = "";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
}
这是在logcat中显示的错误....
04-26 05:54:40.534 5884-5884 / com.example.converbiz.apidemo E / AndroidRuntime:FATAL EXCEPTION:main 显示java.lang.NullPointerException 在android.widget.SimpleAdapter.getCount(SimpleAdapter.java:93) 在android.widget.ListView.setAdapter(ListView.java:462) 在android.app.ListActivity.setListAdapter(ListActivity.java:265) at com.example.converbiz.apidemo.MainActivity $ GetTable.onPostExecute(MainActivity.java:134) at com.example.converbiz.apidemo.MainActivity $ GetTable.onPostExecute(MainActivity.java:86) 在android.os.AsyncTask.finish(AsyncTask.java:631) 在android.os.AsyncTask.access $ 600(AsyncTask.java:177) 在android.os.AsyncTask $ InternalHandler.handleMessage(AsyncTask.java:644) 在android.os.Handler.dispatchMessage(Handler.java:99) 在android.os.Looper.loop(Looper.java:137) 在android.app.ActivityThread.main(ActivityThread.java:5041) at java.lang.reflect.Method.invokeNative(Native Method) 在java.lang.reflect.Method.invoke(Method.java:511) 在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:793) 在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 在dalvik.system.NativeStart.main(本地方法)
答案 0 :(得分:0)
您可以替换以下代码并检查
// Hashmap for ListView
ArrayList<HashMap<String, String>> tableList;
ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
tableList= new ArrayList<HashMap<String, String>> ;
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
WebRequest webreq = new WebRequest();
// Making a request to url and getting response
String jsonStr = webreq.makeWebServiceCall(url, WebRequest.GET);
Log.d("Response: ", "> " + jsonStr);
tableList = ParseJSON(jsonStr);
// JSONArray jsonArray=jsonStr.makeWebSer(url);
return null;
}
答案 1 :(得分:0)
我认为 setListAdapter()中存在问题。
您从 GetTable 类调用 setListAdapter(adapter); 。
因此,请尝试从MainActivity类的onCreate()调用 setListAdapter()。