我通过AsyncTask执行此操作,但doInBackground无效。请告诉我这段代码中的错误,我是android编程的新手。还有其他办法吗?请告诉我正确的方法。
主要活动
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import org.json.JSONObject;
import java.util.ArrayList;
public class MainActivity extends ActionBarActivity {
ArrayAdapter<String> adapter;
ListView listv;
Context context;
ArrayList<String> data;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
data = new ArrayList<String>();
listv = (ListView) findViewById(R.id.listview);
context = this;
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, data);
listv.setAdapter(adapter);
Toast.makeText(this, "Loading Please Wait..", Toast.LENGTH_SHORT).show();
new AsyncCity().execute();
}
protected class AsyncCity extends AsyncTask<Void,JSONObject,ArrayList<cityTable>>
{
ArrayList<cityTable> cityTable=null;
@Override
protected ArrayList<cityTable> doInBackground(Void... params) {
RestAPI api = new RestAPI();
try {
JSONObject jsonObj = api.GetCity();
JsonParse parser = new JsonParse();
cityTable= parser.parseCity(jsonObj);
} catch (Exception e) {
// TODO Auto-generated catch block
}
return cityTable;
}
@Override
protected void onPostExecute(ArrayList<cityTable> cityTables) {
for (int i = 0; i < cityTables.size(); i++) {
data.add(cityTables.get(i).getCt_id() + " " + cityTables.get(i).getCt_name());
}
adapter.notifyDataSetChanged();
Toast.makeText(context,"Loading Completed",Toast.LENGTH_SHORT).show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
---------------------------------------------
//Json Parse
----------------------------------------
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Created by Abdurrehman Malik on 8/1/2015.
*/
public class JsonParse {
public JsonParse()
{
super();
}
ArrayList<cityTable>parseCity(JSONObject jsonObject)
{
ArrayList<cityTable> arrayList=new ArrayList<>();
try {
JSONArray jsonArray=jsonObject.getJSONArray("Value");
JSONObject jobj=null;
for(int i=0;i<jsonArray.length();i++)
{
jobj=jsonArray.getJSONObject(i);
arrayList.add(new cityTable(jobj.getInt("ct_id"), jobj.getString("ct_name")));
}
} catch (JSONException e) {
e.printStackTrace();
}
return arrayList;
}
}
------------------------
//RestAPI
------------------------
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
public class RestAPI {
private final String urlString = "http://pracwebservice.somee.com/Handler3.ashx";
private static String convertStreamToUTF8String(InputStream stream) throws IOException {
String result = "";
StringBuilder sb = new StringBuilder();
try {
InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[4096];
int readedChars = 0;
while (readedChars != -1) {
readedChars = reader.read(buffer);
if (readedChars > 0)
sb.append(buffer, 0, readedChars);
}
result = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
private String load(String contents) throws IOException {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(60000);
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStreamWriter w = new OutputStreamWriter(conn.getOutputStream());
w.write(contents);
w.flush();
InputStream istream = conn.getInputStream();
String result = convertStreamToUTF8String(istream);
return result;
}
private Object mapObject(Object o) {
Object finalValue = null;
if (o.getClass() == String.class) {
finalValue = o;
}
else if (Number.class.isInstance(o)) {
finalValue = String.valueOf(o);
} else if (Date.class.isInstance(o)) {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss", new Locale("en", "USA"));
finalValue = sdf.format((Date)o);
}
else if (Collection.class.isInstance(o)) {
Collection<?> col = (Collection<?>) o;
JSONArray jarray = new JSONArray();
for (Object item : col) {
jarray.put(mapObject(item));
}
finalValue = jarray;
} else {
Map<String, Object> map = new HashMap<String, Object>();
Method[] methods = o.getClass().getMethods();
for (Method method : methods) {
if (method.getDeclaringClass() == o.getClass()
&& method.getModifiers() == Modifier.PUBLIC
&& method.getName().startsWith("get")) {
String key = method.getName().substring(3);
try {
Object obj = method.invoke(o, null);
Object value = mapObject(obj);
map.put(key, value);
finalValue = new JSONObject(map);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return finalValue;
}
public JSONObject GetCity() throws Exception {
JSONObject result = null;
JSONObject o = new JSONObject();
JSONObject p = new JSONObject();
o.put("interface","RestAPI");
o.put("method", "GetCity");
o.put("parameters", p);
String s = o.toString();
String r = load(s);
result = new JSONObject(r);
return result;
}
}
----------------------
//cityTable
----------------------
/**
* Created by Abdurrehman Malik on 8/1/2015.
*/
public class cityTable {
int ct_id;
String ct_name;
public cityTable(int ct_id, String ct_name)
{
super();
this.ct_id=ct_id;
this.ct_name=ct_name;
}
public cityTable()
{
super();
this.ct_id=0;
this.ct_name=null;
}
public int getCt_id()
{
return ct_id;
}
public String getCt_name()
{
return ct_name;
}
public void setCt_id(int ct_id)
{
this.ct_id=ct_id;
}
public void setCt_name(String ct_name)
{
this.ct_name=ct_name;
}
}
Reconstruct Branch:
08-01 18:35:37.166 11908-11908 / com.example.abdurrehmanmalik.webprac3 D / OpenGLRenderer:启用调试模式0 08-01 18:35:37.296 11908-11908 / com.example.abdurrehmanmalik.webprac3 D / AndroidRuntime:关闭VM 08-01 18:35:37.296 11908-11908 / com.example.abdurrehmanmalik.webprac3 W / dalvikvm:threadid = 1:线程退出时未捕获异常(组= 0x41751d58) 08-01 18:35:37.296 11908-11908 / com.example.abdurrehmanmalik.webprac3 E / AndroidRuntime:FATAL EXCEPTION:main 过程:com.example.abdurrehmanmalik.webprac3,PID:11908 显示java.lang.NullPointerException at com.example.abdurrehmanmalik.webprac3.MainActivity $ AsyncCity.onPostExecute(MainActivity.java:67) at com.example.abdurrehmanmalik.webprac3.MainActivity $ AsyncCity.onPostExecute(MainActivity.java:40) 在android.os.AsyncTask.finish(AsyncTask.java:632) 在android.os.AsyncTask.access $ 600(AsyncTask.java:177) 在android.os.AsyncTask $ InternalHandler.handleMessage(AsyncTask.java:645) 在android.os.Handler.dispatchMessage(Handler.java:102) 在android.os.Looper.loop(Looper.java:136) 在android.app.ActivityThread.main(ActivityThread.java:5426) at java.lang.reflect.Method.invokeNative(Native Method) 在java.lang.reflect.Method.invoke(Method.java:515) 在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:1268) 在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084) 在dalvik.system.NativeStart.main(本地方法)
答案 0 :(得分:0)
那有点混乱......
我可以告诉你,onPostExecute()
中的崩溃是NullPointerException。当您尝试从cityTables
获取值时,您没有检查null。可能是因为你没有正确地解析它。
如果您记录JSON回复和cityTables
。