使用android连接到远程数据库的URL

时间:2013-09-09 04:21:22

标签: php android json

我是Android开发的新手。我想连接到cpanel中的远程数据库并根据用户名和密码显示数据。这些是我到目前为止的代码

登录表单android xml代码

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/txt_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/Password"
        android:layout_below="@+id/Password"
        android:layout_marginTop="18dp"
        android:ems="10"
        android:inputType="textPassword" />

    <TextView
        android:id="@+id/Username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="28dp"
        android:text="Enter your username"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/Password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/txt_username"
        android:layout_below="@+id/txt_username"
        android:layout_marginTop="30dp"
        android:text="Enter your password"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/txt_username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/Username"
        android:layout_below="@+id/Username"
        android:layout_marginTop="16dp"
        android:ems="10"
        android:inputType="textPersonName" />

    <Button
        android:id="@+id/btn_log"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/txt_password"
        android:layout_below="@+id/txt_password"
        android:layout_marginTop="20dp"
        android:text="Login"
        android:textColor="@android:color/background_light" />

     <Button
        android:id="@+id/btn_cancel"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/btn_log"
        android:layout_below="@+id/btn_log"
        android:layout_marginTop="20dp"
        android:text="Cancel"
        android:textColor="@android:color/background_light" />


</RelativeLayout>

这是我上面xml布局的java代码

package com.example.remotedb1;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

    public static final String strURL = "http://cyberi-tech.com/khacheb/sig1.php";

      StringBuilder sb=null;

      TextView  inlog;
      TextView inpass;
      Button log;
      Button cancel;

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

        inlog = (TextView)findViewById(R.id.txt_username);
        inpass = (TextView)findViewById(R.id.txt_password);
        log = (Button)findViewById(R.id.btn_log);
        cancel = (Button)findViewById(R.id.btn_cancel);


        log.setOnClickListener(new OnClickListener() {

          @Override
          public void onClick(View v) {
            InputStream is = null;
            String result = "";

            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("username", inlog.getText().toString()));
            nameValuePairs.add(new BasicNameValuePair("password", inpass.getText().toString()));

            try{
              HttpClient httpclient = new DefaultHttpClient();
              HttpPost httppost = new HttpPost(strURL);
              httppost.setEntity(new  UrlEncodedFormEntity(nameValuePairs));
              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());
            }

            // Convertion de la requête en 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();
            }
            catch(Exception e){
              Log.e("log_tag", "Error converting result " + e.toString());
            }

            try{
              JSONArray jArray = new JSONArray(result);
              for(int i=0;i<jArray.length();i++){
                JSONObject json_data = jArray.getJSONObject(i);
                Log.i("log_tag","cin: "+json_data.getInt("cin")+
                  ", accountNb: "+json_data.getString("accountNb")+
                  ", username: "+json_data.getString("username")+
                  ", password: "+json_data.getString("password")
                );
              }
            }
            catch(JSONException e){         
              Log.e("log_tag", "Error parsing data " + e.toString());
            }       
          }
        });

        cancel.setOnClickListener(new OnClickListener() {
          @Override
          public void onClick(View v) {
            finish();   
          }
        });



    }


}

这是我的php文件

<?php
/**
* Database config variables
*/
$username = isset($_POST['username']) ? $_POST['username'] : '';  
$password = isset($_POST['password']) ? $_POST['password'] : ''; 

if(strlen($username) && strlen($password)) {

mysql_connect("localhost","allround_root","ravi12345");//this is my cpanel database,username,password.
mysql_select_db("allround_db");

$username = mysql_real_escape($username);
$password = mysql_real_escape($password);

$query = mysql_query("SELECT cin,accountNb,username , password FROM users WHERE    username = ‘$username’ AND password = ‘$password’");  
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
while($row=mysql_fetch_assoc($query)) 
{
  $output[]=$row;
}
print(json_encode($output));
mysql_close();
}
 //end of if
?>

Sir / Madem我的任务是

有字符串网址“http://cyberi-tech.com/khacheb/sig1.php”。我无法理解我将这个php文件存储在我的cpanel中的位置?

“cyberi-tech.com”也指代-hostname “sig1.php”是指-my php文件 但我无法理解“khacheb”是指?所以请帮助我。

谢谢。

1 个答案:

答案 0 :(得分:0)

khacheb指的是您的网络服务器根目录中包含sig1.PHP文件的文件夹。您应该通过AsyncTask将代码放在一个单独的线程中连接到PHP文件,这里也是一个实现示例example of asynctask。我希望这能帮助你。