activity_main.xml
MainActivity.java
package com.datasnap.restfulclient; import java.io.IOException; import java.util.ArrayList; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.widget.ArrayAdapter; import android.widget.ListView; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); try { this.bindListView(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } private void bindListView() throws ClientProtocolException, IOException, JSONException{ ArrayListlist=this.GetPersonList(); ArrayAdapter arrayAdapter = new ArrayAdapter (this,android.R.layout.simple_list_item_1, list); final ListView listView1=(ListView)this.findViewById(R.id.listView1); listView1.setAdapter(arrayAdapter); } private ArrayList GetPersonList() throws ClientProtocolException, IOException, JSONException{ ArrayList list=new ArrayList (); String json=this.getDataFromRest("http://192.168.0.16:8080/datasnap/rest/TServerMethods1/GetPersonList"); JSONObject jsonObject=new JSONObject(json); JSONArray arrayLevel1=jsonObject.getJSONArray("result"); JSONArray arrayLevel2=(JSONArray)arrayLevel1.get(0); for(int I=0; I< arrayLevel2.length(); I++){ JSONObject items=(JSONObject)arrayLevel2.getJSONObject(I); String firstName=items.get("firstname").toString(); String lastName=items.get("lastname").toString(); list.add(firstName+" "+lastName); } return list; } private String getDataFromRest(String httpUrl) throws ClientProtocolException,IOException{ HttpClient httpClient=new DefaultHttpClient(); HttpGet httpMethod=new HttpGet(httpUrl.toString()); httpMethod.setHeader("Content-type", "application/json"); HttpResponse httpResponse=httpClient.execute(httpMethod); int status=httpResponse.getStatusLine().getStatusCode(); if (status==200){ HttpEntity entity=httpResponse.getEntity(); String data=EntityUtils.toString(entity); return data; }else{ return null; } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }
AndroidManifest.xml dosyasına çift tıklayıp gelen ekrandan "Permissions" sekmesinden "android.permission.INTERNET" değerini ekliyorsunuz. Ekledikten sonra AndroidManifest.xml dosyasının içeriği aşağıdaki gibi olacaktır.
AndroidManifest.xml
İyi Çalışmalar.
Hiç yorum yok:
Yorum Gönder