簡體   English   中英

使用Android PHP JSON遠程連接到MySQL數據庫?

[英]Remote connection to a mysql database with android php json?

我正在嘗試使用具有HTTP連接的android應用程序連接到mysql數據庫,然后檢索JSONArray來掃描查詢結果。 這是代碼:

public class MyActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);

        new JSONfunction().execute();
    }

    private class JSONfunction extends AsyncTask<Void,Void,JSONArray> {

        private JSONArray getJSONfromURL(String url) {
            InputStream is = null;
            String result = "";
            JSONArray jArray = null;


            // Download JSON data from URL
            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(url);
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();

            } catch (Exception e) {
                Log.e("log_tag", "Error in http connection " + e.toString());
            }

            // Convert response to string
            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();
                jArray=new JSONArray(result);
            } catch (Exception e) {
                Log.e("log_tag", "Error converting result " + e.toString());
            }


            return jArray;
        }



        @Override
        protected JSONArray doInBackground(Void... voids) {
            JSONArray jArray=getJSONfromURL("http://192.168.1.5/ConnectData/index.php");
            return jArray;
        }

        protected void onPostExecute(JSONArray result) {
            TextView prova = (TextView)findViewById(R.id.txtProva);
            try {

                JSONObject rec = result.getJSONObject(1);
                prova.setText(rec.getString("first_name"));

            }
            catch(JSONException e){
                Log.e("log_tag", "Error parsing data " + e.toString());
            }
        }
    }

在執行while時出現錯誤。 經過2或3個周期的循環后,應用程序崩潰了。 你能幫我什么忙嗎?

[編輯]

我收到此錯誤:11-28 20:42:19.006 27688-27702 / com.example.marco.provadatabase E / log_tag:轉換結果org.json.JSONException時出錯:值!DOC。類型的java.lang.String無法轉換為JSONArray

[編輯2]

好的,我理解了這個問題。 現在我要面對一個新的。 今天再次嘗試執行代碼,但是現在我在這條線HttpResponse response = httpclient.execute(httppost);上收到超時異常。 (昨天工作正常,我沒有做任何更改)。 這不是URL問題,因為如果我將其放在瀏覽器中,它將可以正常工作。

您的響應類型為String,應將其轉換為JSONObject

這是問題所在

result = sb.toString();
            jArray=new JSONArray(result);

您正在嘗試獲取響應字符串的jsonarray,我相信它的根目錄沒有jsonarray。 能否請您分享請求的回復。

對於您的超時問題

在我的示例中,設置了兩個超時。 連接超時拋出“ java.net.SocketTimeoutException:套接字未連接”,套接字超時拋出“ java.net.SocketTimeoutException:操作超時”。

HttpGet httpGet = new HttpGet(url);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used. 
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT) 
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse response = httpClient.execute(httpGet);

如果要設置任何現有HTTPClient的參數(例如DefaultHttpClient或AndroidHttpClient),則可以使用函數setParams()。

httpClient.setParams(httpParameters);

希望它可以為您清除一切:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM