NetworkingAndroidHttpClientActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
import java.io.IOException; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.BasicResponseHandler; import android.app.Activity; import android.net.http.AndroidHttpClient; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class NetworkingAndroidHttpClientActivity extends Activity { private TextView mTextView = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mTextView = (TextView) findViewById(R.id.textView1); final Button loadButton = (Button) findViewById(R.id.button1); loadButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { new HttpGetTask().execute(); } }); } private class HttpGetTask extends AsyncTask<Void, Void, String> { // Get your own user name at http://www.geonames.org/login private static final String USER_NAME = "indrawdev"; private static final String URL = "http://api.geonames.org/earthquakesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username=" + USER_NAME; AndroidHttpClient mClient = AndroidHttpClient.newInstance(""); @Override protected String doInBackground(Void... params) { HttpGet request = new HttpGet(URL); ResponseHandler<String> responseHandler = new BasicResponseHandler(); try { return mClient.execute(request, responseHandler); } catch (ClientProtocolException exception) { exception.printStackTrace(); } catch (IOException exception) { exception.printStackTrace(); } return null; } @Override protected void onPostExecute(String result) { if (null != mClient) mClient.close(); mTextView.setText(result); } } } |
main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/load_data_string" > </Button> <ScrollView android:id="@+id/scrollView1" android:layout_width="match_parent" android:layout_height="wrap_content" > <TextView android:id="@+id/textView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="24sp" > </TextView> </ScrollView> </LinearLayout> |