无法从php mysql中检索数据到android活动

时间:2016-01-26 20:03:39

标签: android mysql json codeigniter

我是Android编程新手。所以这就是问题所在。 我目前正在使用php框架codeigniter从mysql查询我的数据。当我在浏览器中输入网址时,我会看到我的json数据。但是当我在我的android活动中检索它时,它返回null。 这是我的代码。 php代码

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);
            }
    }

我的机器人活动

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();   }
    });

我的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;

    }
}

这是我的网址http://emedteam-001-site1.ctempurl.com/emed/home/getdrug?letter=a

的链接

1 个答案:

答案 0 :(得分:0)

不推荐使用HTTPClient,因此您应该避免使用它。看看这个HttpClient is deprecated (android studio, Target=api 22)

这是我从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;  
    } 

已编辑:您需要在AsyncTask中调用此函数以避免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();
    }
}

我希望它有所帮助!