Android访问远程mysql数据库

时间:2014-04-01 18:12:34

标签: java php android mysql

我一直在尝试使用多个示例通过Android应用程序访问远程服务器(digitalocean)。目前我在解析URL中的数据时遇到错误,我不是100%确定原因。你能帮帮我吗,代码如下。

java代码:

public class MainActivity extends Activity {
 TextView txt1,txt2,txt3;
 public void onCreate(Bundle savedInstanceState)
 {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  new task().execute();
 }

class task extends AsyncTask<String, String, Void>
{
 private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
    InputStream is = null ;
    String result = "";
    protected void onPreExecute() {
       progressDialog.setMessage("Fetching data...");
       progressDialog.show();
       progressDialog.setOnCancelListener(new OnCancelListener() {
 @Override
  public void onCancel(DialogInterface arg0) {
  task.this.cancel(true);
    }
 });
     }
    @Override
    protected Void doInBackground(String... params) {
      String url_select = "http://server1.chris.waszczuk/webservice/select.php";

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

     //read content
     is =  httpEntity.getContent();     

     } catch (Exception e) {

     Log.e("log_tag", "Error in http connection "+e.toString());
     }
    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
     StringBuilder sb = new StringBuilder();
     String line = "";
     while((line=br.readLine())!=null)
     {
        sb.append(line+"\n");
     }
      is.close();
      result=sb.toString();    

       } catch (Exception e) {
        // TODO: handle exception
        Log.e("log_tag", "Error converting result "+e.toString());
       }

      return null;

     }
    protected void onPostExecute(Void v) {

  // ambil data dari Json database
  try {
   JSONArray Jarray = new JSONArray(result);
   for(int i=0;i<Jarray.length();i++)
   {
   JSONObject Jasonobject = null;
   txt1 = (TextView)findViewById(R.id.txt1);
   txt2 = (TextView)findViewById(R.id.txt2);
   txt3 = (TextView)findViewById(R.id.txt3);

   Jasonobject = Jarray.getJSONObject(i);

   //get an output on the screen
   String no = Jasonobject.getString("no// this should be same in the table field name");
   String name = Jasonobject.getString("name");
   String birthday = Jasonobject.getString("birthday");

      txt1.setText(no);
      txt2.setText(name);
      txt3.setText(birthday);

   }
   this.progressDialog.dismiss();

  } catch (Exception e) {
   // TODO: handle exception
   Log.e("log_tag", "Error parsing data "+e.toString());
  }
}
}
}

XML代码:(互联网权限在清单中(无需上传))

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout android:layout_height="wrap_content"
     android:layout_width="wrap_content"
     android:orientation="horizontal"
     android:layout_marginTop="10dp">

    <TextView android:layout_height="wrap_content"
     android:layout_width="wrap_content"
     android:text="Id Number:"
     android:textStyle="bold"
     android:gravity="center"
     android:textSize="15dp"
     android:layout_marginLeft="15dp" />

    <TextView android:layout_height="wrap_content"
      android:layout_width="wrap_content"   
      android:id="@+id/txt1"
      android:layout_marginLeft="20dp"/>
     </LinearLayout>

     <LinearLayout android:layout_height="wrap_content"
      android:layout_width="wrap_content"
      android:orientation="horizontal"
      android:layout_marginTop="10dp">

     <TextView android:layout_height="wrap_content"
      android:layout_width="wrap_content"
      android:text=" userName:"
      android:textStyle="bold"
      android:gravity="center"
      android:textSize="15dp"
      android:layout_marginLeft="35dp"/>

     <TextView android:layout_height="wrap_content"
      android:layout_width="wrap_content"     
      android:id="@+id/txt2"
      android:layout_marginLeft="20dp"/>
     </LinearLayout>

     <LinearLayout android:layout_height="wrap_content"
      android:layout_width="wrap_content"
      android:orientation="horizontal"
      android:layout_marginTop="10dp">

     <TextView android:layout_height="wrap_content"
      android:layout_width="wrap_content"
      android:text="Password: "
      android:textStyle="bold"
      android:gravity="center"
      android:textSize="15dp"
      android:layout_marginLeft="75dp"/>

     <TextView android:layout_height="wrap_content"
      android:layout_width="wrap_content"    
      android:id="@+id/txt3"
      android:layout_marginLeft="20dp"/>

    </LinearLayout>
</LinearLayout>

php文件(选择后跟连接(密码已删除):

<?php
include_once("connection.php");
$sqlString = "select * from registration  ";
$rs = mysql_query($sqlString);

if($rs)
{
   while($objRs = mysql_fetch_assoc($rs))
   {
      $output[] = $objRs;
   }
   echo json_encode($output);
}

mysql_close();
?>



  <?php
    mysql_connect("localhost","root","");
    mysql_select_db("fantasyfootball");
    ?>

编辑:logcat响应可能也有用:

04-01 14:01:21.730: I/dalvikvm(814): threadid=3: reacting to signal 3
04-01 14:01:22.740: W/dalvikvm(814): threadid=3: spin on suspend #1 threadid=11 (pcf=0)
04-01 14:01:22.740: D/dalvikvm(814): Temporarily moving tid 829 to fg (was 0)
04-01 14:01:22.740: D/dalvikvm(814): Temporarily raised priority on tid 829 (10 -> 0)
04-01 14:01:22.750: W/dalvikvm(814): threadid=3: spin on suspend resolved in 1018 msec
04-01 14:01:22.750: D/dalvikvm(814): Restored policy of 829 to 0
04-01 14:01:22.760: D/dalvikvm(814): Restored priority on 829 to 10
04-01 14:01:23.190: I/Choreographer(814): Skipped 41 frames!  The application may be doing too much work on its main thread.
04-01 14:01:23.200: I/dalvikvm(814): Wrote stack traces to '/data/anr/traces.txt'
04-01 14:01:24.250: I/Choreographer(814): Skipped 30 frames!  The application may be doing too much work on its main thread.
04-01 14:01:25.430: I/Choreographer(814): Skipped 34 frames!  The application may be doing too much work on its main thread.
04-01 14:01:25.840: E/log_tag(814): Error in http connection java.net.UnknownHostException: Unable to resolve host "server1.chris.waszczuk": No address associated with hostname
04-01 14:01:25.840: E/log_tag(814): Error converting result java.lang.NullPointerException: lock == null
04-01 14:01:25.950: I/Choreographer(814): Skipped 33 frames!  The application may be doing too much work on its main thread.
04-01 14:01:25.990: E/log_tag(814): Error parsing data org.json.JSONException: End of input at character 0 of 
04-01 14:01:26.440: I/Choreographer(814): Skipped 46 frames!  The application may be doing too much work on its main thread.

更新:将login_url更改为服务器的IP地址后,会出现新的解析错误。

新网址:

String url_select = "http://95.85.22.140/webservice/select.php";

错误:

04-01 14:19:26.206: E/log_tag(1037): Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONArray

任何帮助都会非常感谢。

1 个答案:

答案 0 :(得分:1)

根据我的评论中的建议,String url_select = "http://server1.chris.waszczuk/webservice/select.php";是错误的。基本上,除非您拥有自己的DNS服务器并且所有流量都通过它,否则server1.chris.waszczuk是一个错误的DNS名称。

如果您在本地网络中运行此功能,我建议您使用服务器的私有IP地址。这样您就可以使用以下内容获取您的网址:

http://192.168.1.X/webservice/select.php

如果您将其作为远程服务器运行,请改用有效的DNS。