Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Apr 28th, 2012  |  syntax: None  |  size: 12.03 KB  |  hits: 22  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Android: JSON to ListView
  2. import java.util.ArrayList;
  3. import java.util.List;
  4.  
  5. import org.apache.http.NameValuePair;
  6. import org.apache.http.message.BasicNameValuePair;
  7. import org.json.JSONArray;
  8. import org.json.JSONException;
  9. import org.json.JSONObject;
  10.  
  11. import android.app.Activity;
  12. import android.os.Bundle;
  13. import android.view.LayoutInflater;
  14. import android.view.View;
  15. import android.view.ViewGroup;
  16. import android.widget.ArrayAdapter;
  17. import android.widget.ImageView;
  18. import android.widget.ListView;
  19. import android.widget.TextView;
  20. import android.widget.Toast;
  21.  
  22. public class PlacesActivity extends Activity {
  23.  
  24. List<Places> model = new ArrayList<Places>();
  25. PlacesAdapter adapter = new PlacesAdapter();
  26.  
  27.  
  28. @SuppressWarnings("static-access")
  29. @Override
  30. public void onCreate(Bundle savedInstanceState) {
  31.     ListView lv = (ListView) findViewById(R.id.placesListView);
  32.     super.onCreate(savedInstanceState);
  33.     setContentView(R.layout.places);
  34.  
  35.     ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
  36.     postParameters.add(new BasicNameValuePair("request","request_for_places"));
  37.  
  38.     String response = null;
  39.  
  40.     try{
  41.         response = CustomHttpClient.executeHttpPost("http://www.test.com/requestPlaces.php", postParameters);
  42.         String res = response;
  43.  
  44.         try{
  45.             JSONArray arr = new JSONArray(res);
  46.             for(int i = 0; i < arr.length(); i++)
  47.             {
  48.                 JSONObject jsonObj = arr.getJSONObject(i);
  49.                 Places newPlace = new Places();
  50.                 newPlace.setPlace(jsonObj.optString("placeID"),jsonObj.optString("placeName"),jsonObj.optString("placeType"),jsonObj.optString("placeLat"),jsonObj.optString("placeLng"),jsonObj.optString("placePict"));
  51.                 model.add(newPlace);
  52.             }
  53.  
  54.         }catch(JSONException e){
  55.             Toast.makeText(getApplicationContext(), "Error : JSONException!", Toast.LENGTH_LONG).show();
  56.         }
  57.  
  58.         lv.setAdapter(adapter);
  59.  
  60.  
  61.     }catch(Exception e){
  62.         Toast.makeText(getApplicationContext(), e+"", Toast.LENGTH_LONG).show();
  63.     }
  64. }
  65.  
  66. class PlacesAdapter extends ArrayAdapter<Places>
  67. {
  68.     PlacesAdapter()
  69.     {
  70.         super(PlacesActivity.this,android.R.layout.simple_list_item_1,model);
  71.     }
  72.  
  73.     public View getView(int position, View convertView, ViewGroup parent)
  74.     {
  75.         View row = convertView;
  76.         PlaceHolder holder = null;
  77.  
  78.         if(row == null)
  79.         {
  80.             LayoutInflater inflater = getLayoutInflater();
  81.             row = inflater.inflate(R.layout.row, parent,false);
  82.             holder = new PlaceHolder(row);
  83.         }
  84.         else
  85.         {
  86.             holder = (PlaceHolder)row.getTag();
  87.         }
  88.  
  89.         holder.populateFrom(model.get(position));
  90.  
  91.         return row;
  92.     }
  93. }
  94.  
  95. static class PlaceHolder{
  96.  
  97.     private TextView placeName = null;
  98.     private TextView placeType = null;
  99.     private ImageView icon = null;
  100.  
  101.     PlaceHolder(View row){
  102.         placeName = (TextView)row.findViewById(R.id.placeName);
  103.         placeType =  (TextView)row.findViewById(R.id.placeType);
  104.         icon = (ImageView)row.findViewById(R.id.icon);
  105.     }
  106.  
  107.     void populateFrom(Places p){
  108.         placeName.setText(p.getPlaceName());
  109.         placeType.setText(p.getType());
  110.  
  111.         if(p.getType().equals("Education")){
  112.             icon.setImageResource(R.drawable.ball_red);
  113.         }
  114.         else if (p.getType().equals("Leisure")){
  115.             icon.setImageResource(R.drawable.ball_yellow);
  116.         }
  117.         else{
  118.             icon.setImageResource(R.drawable.ball_green);
  119.         }
  120.  
  121.         }
  122.     }
  123. }
  124.        
  125. [{"placeID":"p0001","placeName":"INTI International University","placeType":"Education","placeLat":"2.813997","placeLng":"101.758229","placePict":"http://test.com/placesImage/inti_iu.JPG"},
  126. {"placeID":"p0002","placeName":"Nilai International College","placeType":"Education","placeLat":"2.814179","placeLng":"101.7700107","placePict":"http://test.com/placesImage/nilai_uc.jpg"}]
  127.        
  128. public class Places{
  129.  
  130. private static String placeName;
  131. private static String placeImg;
  132. private static String placeLat;
  133. private static String placeLng;
  134. private static String placeType;
  135. private static String placeID;
  136.  
  137. public Places()
  138. {
  139.    placeID = "";
  140. }
  141.  
  142.  
  143. //set method
  144. public static void setPlace(String place_id, String place_name, String place_type, String place_lat, String place_lng, String place_img) {
  145.     Places.placeName = place_name;
  146.     Places.placeID = place_id;
  147.     Places.placeImg = place_img;
  148.     Places.placeLat = place_lat;
  149.     Places.placeLng = place_lng;
  150.     Places.placeType = place_type;
  151. }
  152.  
  153.  
  154.  
  155. //get methods
  156. public static String getPlaceName(){
  157.     return placeName;
  158. }
  159.  
  160. public static String getPlaceID(){
  161.     return placeID;
  162. }
  163.  
  164. public static String getImg(){
  165.     return placeImg;
  166. }
  167.  
  168. public static String getLat(){
  169.     return placeLat;
  170. }
  171.  
  172. public static String getLng(){
  173.     return placeLng;
  174. }
  175.  
  176. public static String getType(){
  177.     return placeType;
  178. }
  179.  
  180. }
  181.        
  182. 02-17 17:10:03.595: W/System.err(1994): java.lang.NullPointerException
  183. 02-17 17:10:03.615: W/System.err(1994):     at  com.application.fyp.PlacesActivity.onCreate(PlacesActivity.java:50)
  184. 02-17 17:10:03.615: W/System.err(1994):     at  android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1072)
  185. 02-17 17:10:03.615: W/System.err(1994):     at  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1836)
  186. 02-17 17:10:03.615: W/System.err(1994):     at      android.app.ActivityThread.startActivityNow(ActivityThread.java:1692)
  187. 02-17 17:10:03.625: W/System.err(1994):     at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:127)
  188. 02-17 17:10:03.625: W/System.err(1994):     at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:339)
  189. 02-17 17:10:03.625: W/System.err(1994):     at     android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:656)
  190. 02-17 17:10:03.625: W/System.err(1994):     at android.widget.TabHost.setCurrentTab(TabHost.java:326)
  191. 02-17 17:10:03.625: W/System.err(1994):     at android.widget.TabHost$2.onTabSelectionChanged(TabHost.java:132)
  192. 02-17 17:10:03.625: W/System.err(1994):     at android.widget.TabWidget$TabClickListener.onClick(TabWidget.java:458)
  193. 02-17 17:10:03.625: W/System.err(1994):     at android.view.View.performClick(View.java:2533)
  194. 02-17 17:10:03.625: W/System.err(1994):     at android.view.View$PerformClick.run(View.java:9320)
  195. 02-17 17:10:03.635: W/System.err(1994):     at android.os.Handler.handleCallback(Handler.java:587)
  196. 02-17 17:10:03.635: W/System.err(1994):     at android.os.Handler.dispatchMessage(Handler.java:92)
  197. 02-17 17:10:03.635: W/System.err(1994):     at android.os.Looper.loop(Looper.java:150)
  198. 02-17 17:10:03.635: W/System.err(1994):     at android.app.ActivityThread.main(ActivityThread.java:4385)
  199. 02-17 17:10:03.635: W/System.err(1994):     at java.lang.reflect.Method.invokeNative(Native Method)
  200. 02-17 17:10:03.635: W/System.err(1994):     at java.lang.reflect.Method.invoke(Method.java:507)
  201. 02-17 17:10:03.635: W/System.err(1994):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:849)
  202. 02-17 17:10:03.635: W/System.err(1994):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:607)
  203. 02-17 17:10:03.645: W/System.err(1994):     at dalvik.system.NativeStart.main(Native Method)
  204.        
  205. adapter.add(newPlace);
  206.        
  207. adapter = new PlacesAdapter();
  208.        
  209. List<Places> model = new ArrayList<Places>();
  210.        
  211. List<Places> model = new ArrayList<Places>();
  212. PlacesAdapter adapter = new PlacesAdapter();
  213.        
  214. List<Places> model = new ArrayList<Places>();
  215. PlacesAdapter adapter;
  216.        
  217. ListView lv = (ListView) findViewById(R.id.placesListView);
  218. super.onCreate(savedInstanceState);
  219. setContentView(R.layout.places);
  220.        
  221. super.onCreate(savedInstanceState);
  222. setContentView(R.layout.places);
  223. ListView lv = (ListView) findViewById(R.id.placesListView);
  224.        
  225. lv.setAdapter(adapter);
  226.        
  227. adapter = new PlacesAdapter();
  228. lv.setAdapter(adapter);
  229.        
  230. public class MainActivity extends Activity {
  231.  
  232. List<Places> model;
  233. PlacesAdapter adapter;
  234.  
  235. @Override
  236. public void onCreate(Bundle savedInstanceState) {
  237.     super.onCreate(savedInstanceState);
  238.     setContentView(R.layout.main);
  239.     ListView lv = (ListView) findViewById(R.id.listView1);
  240.  
  241.     model = new ArrayList<Places>();
  242.     adapter = new PlacesAdapter();
  243.     try {
  244.         List<NameValuePair> pairs = new ArrayList<NameValuePair>();
  245.         pairs.add(new BasicNameValuePair("whatever", "XXXX"));
  246.         JSONArray jArray = connectToServer("http://www.example.com/get.php", pairs);
  247.         try {
  248.             for (int i = 0; i < jArray.length(); i++) {
  249.                 JSONObject jsonObj = jArray.getJSONObject(i);
  250.                 Places newPlace = new Places();
  251.                 Places.setPlace(jsonObj.optString("name"),
  252.                         jsonObj.optString("name"),
  253.                         jsonObj.optString("name"),
  254.                         jsonObj.optString("name"),
  255.                         jsonObj.optString("name"),
  256.                         jsonObj.optString("name"));
  257.                 model.add(newPlace);
  258.             }
  259.  
  260.         } catch (JSONException e) {
  261.             Toast.makeText(getApplicationContext(),
  262.                     "Error : JSONException!", Toast.LENGTH_LONG).show();
  263.         }
  264.  
  265.         lv.setAdapter(adapter);
  266.  
  267.     } catch (Exception e) {
  268.         Toast.makeText(getApplicationContext(), e + "", Toast.LENGTH_LONG)
  269.                 .show();
  270.     }
  271. }
  272.  
  273. class PlacesAdapter extends ArrayAdapter<Places> {
  274.     PlacesAdapter() {
  275.         super(MainActivity.this, android.R.layout.simple_list_item_1, model);
  276.     }
  277.  
  278.     public View getView(int position, View convertView, ViewGroup parent) {
  279.         View row = convertView;
  280.         PlaceHolder holder = null;
  281.  
  282.         if (row == null) {
  283.             LayoutInflater inflater = getLayoutInflater();
  284.             row = inflater.inflate(R.layout.row, parent, false);
  285.             holder = new PlaceHolder(row);
  286.         } else {
  287.             holder = (PlaceHolder) row.getTag();
  288.         }
  289.  
  290.         holder.populateFrom(model.get(position));
  291.  
  292.         return row;
  293.     }
  294. }
  295.  
  296. static class PlaceHolder {
  297.  
  298.     private TextView placeName = null;
  299.     private TextView placeType = null;
  300.     private ImageView icon = null;
  301.  
  302.     PlaceHolder(View row) {
  303.         placeName = (TextView) row.findViewById(R.id.textView1);
  304.         placeType = (TextView) row.findViewById(R.id.textView1);
  305.         icon = (ImageView) row.findViewById(R.id.imageView1);
  306.     }
  307.  
  308.     void populateFrom(Places p) {
  309.         placeName.setText(Places.getPlaceName());
  310.         placeType.setText(Places.getType());
  311.  
  312.         if (Places.getType().equals("Education")) {
  313.             icon.setImageResource(R.drawable.ic_launcher);
  314.         } else if (Places.getType().equals("Leisure")) {
  315.             icon.setImageResource(R.drawable.ic_launcher);
  316.         } else {
  317.             icon.setImageResource(R.drawable.ic_launcher);
  318.         }
  319.  
  320.     }
  321. }
  322.  
  323. public static JSONArray connectToServer(String address, List<NameValuePair> valuePairs) {
  324.     HttpClient httpclient = new DefaultHttpClient();
  325.     HttpPost httppost = new HttpPost(address);
  326.     try {          
  327.         httppost.setEntity(new UrlEncodedFormEntity(valuePairs));
  328.         HttpResponse response = httpclient.execute(httppost);
  329.         HttpEntity entity = response.getEntity();
  330.         InputStream is = entity.getContent();
  331.         BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF8"),8);
  332.         StringBuilder sb = new StringBuilder();
  333.         sb.append(reader.readLine() + "n");
  334.         String line="0";
  335.         while ((line = reader.readLine()) != null) {
  336.             sb.append(line + "n");
  337.         }
  338.         is.close();
  339.         String result = sb.toString();
  340.         JSONArray array = new JSONArray(result);
  341.         return array;
  342.     } catch(Exception e){
  343.         Log.e("log_tag", "Error converting result "+e.toString());
  344.         return null;
  345.     }
  346. }
  347. }
  348.        
  349. holder = (PlaceHolder)row.getTag();
  350.        
  351. if(row == null)
  352.      {
  353.         LayoutInflater inflater = getLayoutInflater();
  354.         row = inflater.inflate(R.layout.row, parent,false);
  355.         holder = new PlaceHolder(row);
  356.        }
  357.        
  358. if(row == null)
  359.      {
  360.         LayoutInflater inflater = getLayoutInflater();
  361.         row = inflater.inflate(R.layout.row, parent,false);
  362.         holder = new PlaceHolder(row);
  363.       row.setTag(holder);}