Android Open Source - MotorIndia Retrivejson

From Project

Back to project page MotorIndia.


The source code is released under:

GNU General Public License

If you think the Android project MotorIndia listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package spider.motorindia;
//from w  ww  . j a  v  a  2  s . c  o m


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import android.os.AsyncTask;

public class Retrivejson extends AsyncTask<String, Void, JSONArray> {

  //i define the callback interface
  public interface MyCallbackInterface {
    //its supposed to send the JSON object on request completed
    public void onRequestCompleted(JSONArray result);

  private MyCallbackInterface mCallback;

  public Retrivejson(MyCallbackInterface callback) {
    mCallback = callback;

  public JSONArray getJSONFromUrl(String url) {
    DefaultHttpClient   httpclient = new DefaultHttpClient(new BasicHttpParams());
    HttpPost httppost = new HttpPost(url);
    // Depends on your web service
    httppost.setHeader("Content-type", "application/json");
    InputStream inputStream = null;
    String result = null;
    try {
      HttpResponse response = httpclient.execute(httppost);           
      HttpEntity entity = response.getEntity();

      inputStream = entity.getContent();
      // JSON is UTF-8 by default BECAUSE I DIDNT USE THIS METHOD to try to fix issue #5
      BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
      StringBuilder sb = new StringBuilder();

      String line = null;
      while ((line = reader.readLine()) != null)
        sb.append(line + "\n");
      result = sb.toString();
    } catch (Exception e) { 
      // Oops
    finally {
      try{if(inputStream != null)inputStream.close();}catch(Exception squish){}

    try {
      return new JSONArray(result);
    } catch (JSONException e) {
      // TODO Auto-generated catch block
    return null;  

  protected JSONArray doInBackground(String... params) {
    // this accepts multiple strings as argument the first string is fed into the function getJSONFromUrl where the whole "Work" takes place
    String url = params[0];
    return getJSONFromUrl(url);

  protected void onPostExecute(JSONArray result) {
    //So that i have the JSON array ready to use, i use the call back to send it to the '' ;)

Java Source Code List