用户导航到此页面后发生的第一件事是应用程序使用远程数据库中的状态列表填充列表视图。然后用户选择一个状态,应用程序返回数据库并获取该州的县名单。 状态加载很好,问题是countys不加载。在日志中,它显示页面返回一个空数组。如果我只是转到页面http://photosbychristian.com/ems/get_countys.php?state=PA 它工作正常。我不确定问题是因为没有错误被抛出,并且第一次获得状态时工作正常。
这是我的代码:
package com.example.hospitals;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class Add extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
private ProgressDialog cDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
JSONParser jParserCo = new JSONParser();
ArrayList<HashMap<String, String>> statesList;
ArrayList<HashMap<String, String>> countyList;
// urls
private static String url_states = "http://photosbychristian.com/ems/get_states.php";
String url_countys;
// JSON Node names for states
private static final String TAG_STATES = "states";
private static final String TAG_TB_NAME = "tbname";
private static final String TAG_NAME = "name";
private static final String TAG_ABBR = "Abbr";
//JSON Node names for countys
private static final String TAG_COUNTYS = "countys";
private static final String TAG_NAME_COUNTY = "name";
// JSONArrays
JSONArray states = null;
JSONArray countys = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
//path.setText("");
// Hashmap for ListView
statesList = new ArrayList<HashMap<String, String>>();
countyList = new ArrayList<HashMap<String, String>>();
// Loading states in Background Thread
new LoadAllStates().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// getting values from selected ListItem
String abbr = ((TextView) view.findViewById(R.id.abbr)).getText().toString();
String cf = ((TextView) view.findViewById(R.id.comingFrom)).getText().toString();
TextView path = (TextView)findViewById(R.id.path);
Log.d("Coming From",cf);
if (cf == "1"){//countys
path.append(abbr + " > ");
url_countys = "http://photosbychristian.com/ems/get_countys.php?state="+abbr;
Log.d("url", url_countys);
new LoadAllCountys().execute();
}else if(cf == "2"){//citys
path.append(abbr + " > ");
}else if (cf == "3"){//hospitals
path.append(abbr);
}
}
});
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllStates extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Add.this);
pDialog.setMessage("Loading states. Please wait.");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting all staets from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_states, "GET", params);
// Check your log cat for JSON reponse
Log.d("All States: ", json.toString());
try {
// products found
// Getting Array of Products
states = json.getJSONArray(TAG_STATES);
// looping through All Products
for (int i = 0; i < states.length(); i++) {
JSONObject c = states.getJSONObject(i);
// Storing each json item in variable
String table = c.getString(TAG_TB_NAME);
String name = c.getString(TAG_NAME);
String abbr = c.getString(TAG_ABBR);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_TB_NAME, table);
map.put(TAG_NAME, name);
map.put(TAG_ABBR, abbr);
map.put("ComingFrom", "1");
// adding HashList to ArrayList
statesList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
Add.this,
statesList,
R.layout.hospital_items,
new String[] { TAG_TB_NAME, TAG_ABBR, TAG_NAME, "ComingFrom"},
new int[] { R.id.id, R.id.abbr, R.id.name, R.id.comingFrom }
);
// updating listview
setListAdapter(adapter);
}
});
}
}
class LoadAllCountys extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
cDialog = new ProgressDialog(Add.this);
cDialog.setMessage("Loading countys. Please wait.");
cDialog.setIndeterminate(false);
cDialog.setCancelable(false);
cDialog.show();
}
/**
* getting all staets from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject jsonCo = jParserCo.makeHttpRequest(url_countys, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Countys: ", jsonCo.toString());
try {
// products found
// Getting Array of Products
countys = jsonCo.getJSONArray(TAG_COUNTYS);
// looping through All Products
for (int i = 0; i < countys.length(); i++) {
JSONObject c = countys.getJSONObject(i);
// Storing each json item in variable
String name = c.getString(TAG_NAME_COUNTY);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_NAME_COUNTY, name);
map.put("ComingFrom", "2");
// adding HashList to ArrayList
countyList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
cDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
Add.this,
countyList,
R.layout.hospital_items,
new String[] {TAG_NAME, "ComingFrom"},
new int[] { R.id.name, R.id.comingFrom }
);
// updating listview
setListAdapter(adapter);
}
});
}
}
}
此外,一旦我在用户选择一个县之后想出这个,列表视图将填充城市和医院,所以如果有更好的方法,我愿意学习。
答案 0 :(得分:0)
我不确定我是否正确理解了你的问题。但还是......
您可以将适配器的数据集更改为列表视图并进行刷新。这样,列表视图将开始显示新的数据项集。
在列表视图的onItemClick中,您可以执行以下操作:
mAdapter.setListData(mSubMenu);
mAdapter.notifyDataSetChanged();
你的mSumMenu可以是县的arraylist。
答案 1 :(得分:0)
这样的事对我有用。我首先下载文件,然后使用它创建json对象:
mJsonString = downloadFileFromInternet(urls[0]);
if(mJsonString == null)
return false;
JSONObject jObject = null;
jObject = new JSONObject(mJsonString);
----
private String downloadFileFromInternet(String url)
{
if(url == null /*|| url.isEmpty() == true*/)
new IllegalArgumentException("url is empty/null");
StringBuilder sb = new StringBuilder();
InputStream inStream = null;
try
{
url = urlEncode(url);
URL link = new URL(url);
inStream = link.openStream();
int i;
int total = 0;
byte[] buffer = new byte[8 * 1024];
while((i=inStream.read(buffer)) != -1)
{
if(total >= (1024 * 1024))
{
return "";
}
total += i;
sb.append(new String(buffer,0,i));
}
}catch(Exception e )
{
e.printStackTrace();
return null;
}catch(OutOfMemoryError e)
{
e.printStackTrace();
return null;
}
return sb.toString();
}
private String urlEncode(String url)
{
if(url == null /*|| url.isEmpty() == true*/)
return null;
url = url.replace("[","");
url = url.replace("]","");
url = url.replaceAll(" ","%20");
return url;
}