0

Im new to android programming. So here's the problem. I am currently using a php framework codeigniter to query my data from mysql. When i type the url in my browser i see my json data. But when i retrieving it in my android activity it returns null. Here is my code. php code

function getdrug(){
            $id = $_GET['letter'];
            //echo $_GET['letter'];
            header('Content-type: application/json');
            if($id == 'a'){
                $this->db->like('Generic_Name','A');
                $value['Drugs'] = $this->db->get('drugs')->result();
                echo json_encode($value);
            }
    }

my android activity

ListView lv;
Button btn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn = (Button)findViewById(R.id.button1);
    btn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            String URL = "http://emedteam-001-site1.ctempurl.com/emed/home/getdrug?letter=a";
            jsonobject = JSONfunctions.getJSONfromURL(URL);
            Toast.makeText(getApplicationContext(),URL + "\n" +jsonobject, Toast.LENGTH_LONG).show();   }
    });

my JSONfunctions

public class JSONfunctions {

    public static JSONObject getJSONfromURL(final String URL){
        InputStream is = null;
        String result = "";
        String params = "";

        JSONObject jArray = null;


        try{

            HttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
            HttpGet httpget = new HttpGet(URL);

            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

        }
        catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
        }
        //Convert
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();
            } catch (Exception e) {
                Log.e("log_tag", "Error converting result " + e.toString());
         }
        //parse json data
         try {

                jArray = new JSONObject(result);
                System.out.print(jArray);
            } catch (JSONException e) {
                Log.e("log_tag", "Error parsing data " + e.toString());
            }
        return jArray;

    }
}

here's the link of my url http://emedteam-001-site1.ctempurl.com/emed/home/getdrug?letter=a

Marc B
  • 356,200
  • 43
  • 426
  • 500

1 Answers1

0

HTTPClient is deprecated so you should avoid it. Look at this HttpClient is deprecated (android studio, Target=api 22)

This is my working function to get content from json

    public static JSONObject getJSONfromURL(final String URL){

        JSONObject jArray = null;
        try {
            //URL = "http://emedteam-001-site1.ctempurl.com/emed/home/getdrug?letter=a";
            URLConnection conn = new URL(URL).openConnection();
            conn.addRequestProperty("Accept", "application/json");
            conn.connect();
            InputStream is = conn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();

            String str = sb.toString();
            sb = null;
            jArray  = new JSONObject(str);                          
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jArray;  
    } 

EDITED: You need to call to this function inside AsyncTask to avoid How to fix android.os.NetworkOnMainThreadException?

ListView lv;
Button btn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn = (Button)findViewById(R.id.button1);
    btn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            new StackOverflowTask().execute();
        }
    });

    class StackOverflowTask extends AsyncTask<String, Void, JSONObject> {
        protected JSONObject doInBackground(String... urls) {
            try {
                JSONObject test = JSONfunctions.getJSONfromURL("http://emedteam-001-site1.ctempurl.com/emed/home/getdrug?letter=a");
                return test;
            } catch (Exception e) {
                return null;
            }
        }

        protected void onPostExecute(JSONObject test) {
            if(test != null)
                Toast.makeText(TestActivity.this, "Hello Stackoverflow ;)",Toast.LENGTH_SHORT).show();
    }
}

I hope it help!

Community
  • 1
  • 1
Gueorgui Obregon
  • 5,077
  • 3
  • 33
  • 57