Json parsing in Android
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
</LinearLayout>
Json_ReadActivity :
public class Json_ReadActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String readTwitterFeed = readTwitterFeed();
try {
JSONArray jsonArray = new JSONArray(readTwitterFeed);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public String readTwitterFeed()
{
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet("Your URL");
try
{
HttpResponse response = client.execute(httpget);
StatusLine statusline = response.getStatusLine();
int statusCode = statusline.getStatusCode();
if(statusCode == 200)
{
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
}
else
{
Log.e(Json_ReadActivity.class.toString(), "Failed to download file");
}
}catch (ClientProtocolException e) {
// TODO: handle exception
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
AndroidMenifest.xml
<uses-permission android:name="android.permission.INTERNET" />
No comments:
Post a Comment