Skip to content Skip to sidebar Skip to footer

Cannot Retrieve Data From Php Mysql To Android Activity

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

Solution 1:

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

publicstaticJSONObjectgetJSONfromURL(final String URL){

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

            String str = sb.toString();
            sb = null;
            jArray  = newJSONObject(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;

@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn = (Button)findViewById(R.id.button1);
    btn.setOnClickListener(newView.OnClickListener() {

        @OverridepublicvoidonClick(View v) {
            // TODO Auto-generated method stubnewStackOverflowTask().execute();
        }
    });

    classStackOverflowTaskextendsAsyncTask<String, Void, JSONObject> {
        protectedJSONObjectdoInBackground(String... urls) {
            try {
                JSONObject test = JSONfunctions.getJSONfromURL("http://emedteam-001-site1.ctempurl.com/emed/home/getdrug?letter=a");
                return test;
            } catch (Exception e) {
                returnnull;
            }
        }

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

I hope it help!

Post a Comment for "Cannot Retrieve Data From Php Mysql To Android Activity"