JsonGetterActivity.java
Dosyayı İndir
package com.godoro.androidclients;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONObject;
import java.io.*;
import java.net.*;
public class JsonGetterActivity extends Activity {
private TextView outputView ;
private String uri="http://echo.jsontest.com/id/123/name/Telefon";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_json_getter);
outputView= (TextView) findViewById(R.id.outputView);
}
public void onClickDownload(View view) {
Toast.makeText(this, "İndiriliyor", Toast.LENGTH_LONG).show();
Runnable runnable=new Runnable() {
public void run() {
downloadContent();
}
};
Thread thread=new Thread(runnable);
thread.start();
}
private void downloadContent(){
try {
String content = get(uri);
handleContent(content);
} catch (Exception e) {
handleException(e);
}
}
private void handleContent(final String content) throws Exception{
JSONObject object=new JSONObject(content);
final String id=object.getString("id");
final String name=object.getString("name");
Runnable runnable=new Runnable() {
public void run() {
outputView.setText(" Kimlik : "+id+"\r\n"
+" Ad : "+name);
}
};
runOnUiThread(runnable);
}
private void handleException(final Exception e){
Runnable runnable=new Runnable() {
public void run() {
Log.e(e.getClass().getName(), e.getMessage());
outputView.setText("HATA "+e.getClass().getName()+" "+e.getMessage());
}
};
runOnUiThread(runnable);
}
private static String get(String address) throws IOException {
URL url = new URL(address);
URLConnection connection = url.openConnection();
InputStream in = connection.getInputStream();
String result = read(in);
return result;
}
private static String read(InputStream in)
throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line).append("\r\n");
}
in.close();
return builder.toString();
}
}
Dosyayı İndir