douqian2334 2014-04-01 18:12
浏览 86
已采纳

Android访问远程mysql数据库

I've been trying, using multiple examples, to access a remote server (digitalocean) through an android application. Currently i'm getting an error with parsing the data from the URL and i'm not 100% sure why. Could you help me out, the code is below.

java code:

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+"
");
     }
      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 code: (internet permission is in the manifest (no need to upload))

<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 files(select followed by connection(password removed):

<?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");
    ?>

Edit: The logcat responses may be of use aswell:

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.

Update: After changing the login_url to the IP Address of the server, a new parsing error appears.

New url:

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

error:

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

Any help would be great thanks.

  • 写回答

1条回答 默认 最新

  • dou44364983 2014-04-01 18:20
    关注

    As suggested in my comment, the String url_select = "http://server1.chris.waszczuk/webservice/select.php"; is wrong. Basically, unless you have an own DNS server and all your traffic goes through it, server1.chris.waszczuk is a bad DNS name.

    If you're running this within a local network, I'd suggest using your server's private IP address. This way you'll have your URL with something like this:

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

    If you're running it as a remote server, use the valid DNS instead.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题