Okay I have went through tons of examples on PARSing my JSON results, with no luck. I have the below JSON example I don't want status info or geoLocation right now. I just want to use stations object and pick some things from the array to display in my ListView as a list. I don't understand any of the do开发者_开发知识库cumentation out there.
Would someone be able to provide a simple example on how read the JSON and put it to a ListView. This would be very helpful. I don't really have any code made up since none of it really worked for me.
{
"status": {
"error": "NO",
"code": 200,
"description": "none",
"message": "Request ok"
},
"geoLocation": {
"city_id": "147",
"city_long": "Saint-Laurent",
"region_short": "QC",
"region_long": "Quebec",
"country_long": "Canada",
"country_id": "43",
"region_id": "35"
},
"stations": [
{
"country": "Canada",
"reg_price": "N\/A",
"mid_price": "N\/A",
"pre_price": "N\/A",
"diesel_price": "N\/A",
"address": "3885, Boulevard de la C\u00f4te-Vertu",
"diesel": "0",
"id": "33862",
"lat": "45.492367",
"lng": "-73.710915",
"station": "Shell",
"logo": "http:\/\/www.mygasfeed.com\/img\/station-logo\/logo-shell.png",
"region": "Quebec",
"city": "Saint-Laurent",
"reg_date": "N\/A",
"mid_date": "N\/A",
"pre_date": "N\/A",
"diesel_date": "N\/A",
"distance": "1.9km"
}
]
First parse your JSON object like so:
String str_json = "your json string";
try {
JSONObject obj = new JSONObject(str_json);
JSONArray stations = obj.getJSONArray("stations");
//etc etc...
} catch (JSONException e) {
e.printStackTrace();
}
Then parse this JSONArray into an ArrayList of custom Station objects that you have created, eg:
public class Station {
public String country;
public int reg_price;
// etc etc...
}
Put items from the JSONArray into your ArrayList:
ArrayList<Station> stationsArrList = new ArrayList<Station>();
int len = stations.size();
for ( int i = 0; i < len; i++ ){
JSONObject stationObj = stations.getJSONObject(i);
Station station = new Station();
for ( int j = 0; j < stationObj.len(); j++ ){
//add items from stationObj to station
}
stationsArrList.add(station);
}
Then create an adapter (assuming you want more than two pieces of info displayed):
public class StationListAdapter extends BaseAdapter {
private static ArrayList<Station> stationArrayList;
private LayoutInflater inflator;
public StationListAdapter(Context context, ArrayList<Station> results) {
stationArrayList = results;
inflator = LayoutInflater.from(context);
}
public int getCount() {
if (stationArrayList == null)
return 0;
else
return stationArrayList.size();
}
public Object getItem(int position) {
try {
return stationArrayList.get(position);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflator.inflate(R.layout.list_item_station, null);
holder = new ViewHolder();
holder.country = (TextView) convertView.findViewById(R.id.station_listview_item_one);
holder.reg_price = (TextView) convertView.findViewById(R.id.station_listview_item_two);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.country.setText(stationArrayList.get(position).getCountry());
holder.reg_price.setText( stationArrayList.get(position).getRegPrice());
return convertView;
}
static class ViewHolder {
TextView country;
TextView reg_price;
//etc
}
}
In the adapter, you'll be using a listview xml layout that you will have defined for each of the list rows.
Finally, you get the reference to the list and add the data on the main activity code:
stationList = (ListView) findViewById(R.id.station_list_view);
stationListAdapter = new StationListAdapter(this, stationsArrList);
stationList.setAdapter(stationListAdapter);
Here's an example of how you would parse the array and display it in the listview. I didn't include the xml but it is pretty simple to describe the listview and multi-line result containing the txt fields for country and address (or whatever):
String[] from = new String[] {"row_1", "row_2"};
int[] to = new int[] { R.id.country, R.id.address};
List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
try {
JSONObject obj = new JSONObject(jsonString);
JSONArray stations = obj.getJSONArray("stations");
Log.i(TAG,"Number of entries " + stations.length());
for (int j = 0; j < stations.length(); j++) {
JSONObject jsonObject = stations.getJSONObject(j);
HashMap<String, String> map = new HashMap<String, String>();
map.put("row_1", jsonObject.getString("country"));
map.put("row_2", jsonObject.getString("address"));
fillMaps.add(map);
}
} catch (Exception e) {
e.printStackTrace();
}
SimpleAdapter adapter = new SimpleAdapter(context, fillMaps, R.layout.result, from, to);
mListView.setAdapter(adapter);
public class JSONParsingExampleActivity extends Activity {
/** Called when the activity is first created. */
private ArrayList<String> id;
private ArrayList<String> name;
private ArrayList<String> email;
private ArrayList<String> address;
private ArrayList<String> gender;
private ArrayList<String> mobile;
private ArrayList<String> home;
private ArrayList<String> office;
ListView view;
ProgressDialog mDialog=null; // Thread code
private Runnable viewOrders; // Thread code
private Thread thread1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
id=new ArrayList<String>();
name=new ArrayList<String>();
email=new ArrayList<String>();
address=new ArrayList<String>();
gender=new ArrayList<String>();
mobile=new ArrayList<String>();
home=new ArrayList<String>();
office=new ArrayList<String>();
view = (ListView)findViewById(R.id.listview);
mDialog=new ProgressDialog(this); // Thread code
mDialog.setMessage("Loading....");
viewOrders =new Runnable() // Thread code
{
public void run() // Thread code
{
Json_function();
runOnUiThread(returnRes);
}
};
thread1=new Thread(null,viewOrders,"Bacground");
thread1.start();
mDialog.show();
}
private Runnable returnRes=new Runnable() // Thread code
{
@Override
public void run() // Thread code
{
mDialog.cancel();
for(int i=0;i<id.size();i++)
{
System.out.println("==========================");
System.out.println("id : - " +id.get(i));
System.out.println("name : - " +name.get(i));
System.out.println("email : - " +email.get(i));
System.out.println("address : - " +address.get(i));
System.out.println("gender : - " +gender.get(i));
System.out.println("mobile : - " +mobile.get(i));
System.out.println("home : - " +home.get(i));
System.out.println("office : - " +office.get(i));
}
ArrayAdapter<String> adapter= new ArrayAdapter<String>(JSONParsingExampleActivity.this, android.R.layout.simple_list_item_1, name);
view.setAdapter(new CustomAdapter(JSONParsingExampleActivity.this));
}
};
private void Json_function()
{
String result=null;
try
{
result=getDataFromWebService("http://api.androidhive.info/contacts/");
System.out.println("length old--> " +result);
}
catch(Exception e)
{
}
try
{
JSONObject json_data=new JSONObject(result);
JSONArray json_array=json_data.getJSONArray("contacts");
System.out.println("json array length : - " +json_array.length());
for(int i=0;i<json_array.length();i++)
{
json_data=json_array.getJSONObject(i);
id.add(json_data.getString("id"));
name.add(json_data.getString("name"));
email.add(json_data.getString("email"));
address.add(json_data.getString("address"));
gender.add(json_data.getString("gender"));
String str= json_data.getString("phone");
JSONObject json_data1 = new JSONObject(str);
mobile.add(json_data1.getString("mobile"));
home.add(json_data1.getString("home"));
office.add(json_data1.getString("office"));
}
}
catch(Exception e1)
{
e1.printStackTrace();
}
}
public static String getDataFromWebService(String strUrl)
{
StringBuffer strBuffer=new StringBuffer();
InputStream is=null;
try
{
System.out.println("getdata from web service url:--> " +strUrl);
HttpClient httpclient=new DefaultHttpClient();
HttpPost httppost=new HttpPost(strUrl);
HttpResponse httpresponse=httpclient.execute(httppost);
HttpEntity httpentity=httpresponse.getEntity();
is=httpentity.getContent();
int in=httpresponse.getStatusLine().getStatusCode();
System.out.println("Response code:--> " +in);
}
catch(Exception e)
{
Log.e("log_tag", "Eroor in http connection" +e.toString());
}
try
{
int ch;
while((ch=is.read())!=-1)
strBuffer.append((char)ch);
is.close();
}
catch(Exception e)
{
e.printStackTrace();
}
return strBuffer.toString();
}
public class CustomAdapter extends BaseAdapter {
private Context mContext;
Application app;
private LayoutInflater inflater=null;
public CustomAdapter(Context c) {
mContext = c;
inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return id.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.list, null);
TextView txt=(TextView)vi.findViewById(R.id.txtview_id);
TextView txt1=(TextView)vi.findViewById(R.id.txtview_name);
TextView txt2=(TextView)vi.findViewById(R.id.txtview_email);
TextView txt3=(TextView)vi.findViewById(R.id.txtview_address);
TextView txt4=(TextView)vi.findViewById(R.id.txtview_gender);
TextView txt5=(TextView)vi.findViewById(R.id.txtview_mobile);
TextView txt6=(TextView)vi.findViewById(R.id.txtview_home);
TextView txt7=(TextView)vi.findViewById(R.id.txtview_office);
txt.setText("Id : " + id.get(position));
txt1.setText("Name : " + name.get(position));
txt2.setText("Email : " + email.get(position));
txt3.setText("Address : " + address.get(position));
txt4.setText("Gender : " + gender.get(position));
txt5.setText("Mobile : " + mobile.get(position));
txt6.setText("Home : " + home.get(position));
txt7.setText("Office : " + office.get(position));
return vi;
};
}
}
精彩评论