如何通过php从远程数据库获取数据到android studio

时间:2015-11-04 12:07:00

标签: php json android-studio

    @Override
    public void onClick(View v) {
        Log.d("Onclick","Loaded");
        name=txt1.getText().toString();
        new task().execute(name);
    }

    class task extends AsyncTask<String,String,Void>
    {

        private ProgressDialog progressDialog=new
           ProgressDialog(MainActivity.this);
        InputStream is=null;
        String result="";
        protected void onPreExcute()
        {
            Log.d("PreExecute","Etered");
            progressDialog.setMessage("Fetching data...");
            progressDialog.show();
            progressDialog.setOnCancelListener(new
            DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    task.this.cancel(true);
                }
            });
        }

        @Override
        protected Void doInBackground(String... params) {
            Log.d("doinBackground","Etered");
            String url_select="myhostsite";
            HttpClient httpClient=new DefaultHttpClient();
            HttpPost httpPost=new HttpPost(url_select);

            ArrayList<NameValuePair> param=new ArrayList<NameValuePair>();
            try {
                httpPost.setEntity(new UrlEncodedFormEntity(param));
                HttpResponse httpResponse=httpClient.execute(httpPost);
                HttpEntity httpEntity=httpResponse.getEntity();
                is=httpEntity.getContent();
                Log.d("Entity",""+is);
            }catch (Exception e)
            {
                Log.e("log_tag", "Error in http connection" + e.toString());
                Toast.makeText(MainActivity.this,"Please Try
           Again",Toast.LENGTH_SHORT).show();
            }
            try {
                BufferedReader br=new BufferedReader(new
        InputStreamReader(is,"UTF-8"),8);
                StringBuilder sb=new StringBuilder();
                String line=null;
                while((line=br.readLine())!=null)
                {
                    sb.append(line+"\n");
                }
                is.close();
                result=sb.toString();
                Log.d("result:","Etered"+result);
            }catch (Exception e)
            {
                Log.e("log_tag", "Error converting result" + e.toString());
            }
            return null;
        }
        protected void onPostExecute(Void v)
        {
            Log.d("PostExecute","Etered");

            try {

                JSONArray array=new JSONArray(result);
                for(int i=0;i<array.length();i++)
                {
                    JSONObject jsonObject=null;
                    jsonObject=array.getJSONObject(i);
     //                    String id=jsonObject.getString("id");
                    Log.d("result:",""+jsonObject);
                    String name=jsonObject.getString("name");
                    Log.d("name",""+name);
                    String db_detail="";
                    if(txt1.getText().toString().equalsIgnoreCase(name)){
                        db_detail=jsonObject.getString("pass");
                        txtvw1.setText(db_detail);;
                    }
                }
                this.progressDialog.dismiss();
            }catch (Exception e){
                Log.e("log_tag","ERRor Parsing data"+e.toString());
            }
        }
    }
  }

/服务器端编码

 <?php
 $servername = "localhost";
 $username = "root";
 $password = "";
 $dbname="mydb";

 // Create connection
 $conn = new mysqli($servername, $username, $password,$dbname);

 // Check connection
 if ($conn->connect_error) {
     die("Connection failed: " . $conn->connect_error);
 } 
 $sql = "SELECT * FROM myinfo";
 $result = $conn->query($sql);

 if ($result->num_rows > 0) {
     // output data of each row
     while($row = $result->fetch_assoc()) {
        $out[]=$row;
     }
    echo json_encode($out);
 } else {
     echo "0 results";
 }
 ?>

当我将网页转换为数组时未正确转换 php的结果就像在android studio中一样

<html><body>
<script type="text/javascript" src="/aes.js" ></script>
<script>function toNumbers(d){var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))});return e}function toHex(){for(var d=[],d=1==arguments.length&&arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;f<d.length;f++)e+=(16>d[f]?"0":"")+d[f].toString(16);return e.toLowerCase()}var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("a7c12a54aa6355be951e558d434cfe2e");document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/";location.href="http://www.tamilarasu.byethost15.com/demo.php?ckattempt=1";</script>
<noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support
</noscript>
</body></html>

错误是

E/log_tag: ERRor Parsing dataorg.json.JSONException: Value <html><body><script of type java.lang.String cannot be converted to JSONArray.

1 个答案:

答案 0 :(得分:0)

您确定在应用中启用了Javascript吗?还是Internet权限?

http://developer.android.com/guide/webapps/webview.html#UsingJavaScript