我试图通过我的Android应用程序

时间:2018-02-13 11:38:45

标签: php android sql

这里是android代码

public class MainActivity extends AppCompatActivity {

 String ServerURL = "http://portal15.unaux.com/get_data.php";

 EditText qr_code, desc,price ;

 Button button;

 String Tempqr, Tempdesc,Tempprice ;


  @Override

  protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

 qr_code=(EditText) findViewById(R.id.code);

 desc=(EditText) findViewById(R.id.resource);

 price=(EditText) findViewById(R.id.price);

 button=(Button) findViewById(R.id.button);
 button.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View view) {
         Getdata();
         insertdata(Tempqr,Tempdesc,Tempprice);
     }
    // converting input data to string
    public void Getdata(){

        Tempqr = qr_code.getText().toString();
        Tempdesc=desc.getText().toString();
        Tempprice = price.getText().toString();

    }

     public void insertdata(final String code, final String description,final String price){

         class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
             @Override
             protected String doInBackground(String... params) {

                 String qrHolder = code;
                 String descHolder = description ;
                 String priceHolder=price;

                 List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

                 nameValuePairs.add(new BasicNameValuePair("code", qrHolder));
                 nameValuePairs.add(new BasicNameValuePair("description", descHolder));
                 nameValuePairs.add(new BasicNameValuePair("price", priceHolder));
                 try {
                     HttpClient httpClient = new DefaultHttpClient();

                     HttpPost httpPost = new HttpPost(ServerURL);

                     httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                     HttpResponse httpResponse = httpClient.execute(httpPost);

                     HttpEntity httpEntity = httpResponse.getEntity();


                 } catch (ClientProtocolException e) {

                 } catch (IOException e) {

                 }
                 return "Data Inserted Successfully";
             }

             @Override
             protected void onPostExecute(String result) {

                 super.onPostExecute(result);

                 Toast.makeText(MainActivity.this, "Data Submit Successfully", Toast.LENGTH_SHORT).show();

             }
         }

         SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();

         sendPostReqAsyncTask.execute(code,description,price);
     }
 });
 }

}

数据没有在mysql数据库中上传,但是我的手机上显示的是toast,表示数据已成功上传但数据没有上传到服务器上。

这是我的PHP代码

<?php include 'DatabaseConfig.php'; 
$con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName); 
$code = $_POST['code']; 
$details = $_POST['description']; 
$price=$_POST['price']; 
$Sql_Query="INSERT INTO item_details (item_code, item_details, Item_price) 
VALUES(' $code ',' $details ',' $price')"; 
if(mysqli_query($con,$Sql_Query)) { 
    echo 'Data Submitted Successfully'; 
} 
else { 
    echo 'Try Again'; 
} 
mysqli_close($con); ?>

1 个答案:

答案 0 :(得分:0)

简单易用方式将数据注册(保存)到数据库中

public class MainActivity extends AppCompatActivity {

private EditText etFullName, etUserName, etPassword, etPhone, etEmail;
private Button clickbut;

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

    etFullName = (EditText) findViewById(R.id.etFullName);
    etUserName = (EditText) findViewById(R.id.etUserName);
    etPassword = (EditText) findViewById(R.id.etPassword);
    etPhone = (EditText) findViewById(R.id.etPhone);
    etEmail = (EditText) findViewById(R.id.etEmail);
    /*clickbut=(Button)findViewById(R.id.Show);
    clickbut.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            launch();
        }
    });*/
}

public void signup(View v) {
    String fullName = etFullName.getText().toString();
    String userName = etUserName.getText().toString();
    String passWord = etPassword.getText().toString();
    String phoneNumber = etPhone.getText().toString();
    String emailAddress = etEmail.getText().toString();

    Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show();
    new SignupActivity(this).execute(fullName, userName, passWord, phoneNumber, emailAddress);

    etFullName.setText("");//clear all the fields after button click
    etUserName.setText("");
    etPassword.setText("");
    etPhone.setText("");
    etEmail.setText("");
}

/*public void launch(){
    new Show_details(this).execute();
    Intent intent=new Intent(this,ShowActvity.class);
    startActivity(intent);
}*/

}

上面是mainActivity,用于获取用户数据并将其传递给AsyncTask类(这里是SignupActivity.java)

public class SignupActivity extends AsyncTask<String,Void,String >{

private Context context;
public SignupActivity(Context context){
    this.context =context;
}

@Override
protected String doInBackground(String... arg0) {
    String fullName = arg0[0];
    String userName = arg0[1];
    String passWord = arg0[2];
    String phoneNumber = arg0[3];
    String emailAddress = arg0[4];

    String link;
    String data;
    BufferedReader bufferedReader;
    String result;
    try {
        data = "?fullname=" + URLEncoder.encode(fullName, "UTF-8");
        data += "&username=" + URLEncoder.encode(userName, "UTF-8");
        data += "&password=" + URLEncoder.encode(passWord, "UTF-8");
        data += "&phonenumber=" + URLEncoder.encode(phoneNumber, "UTF-8");
        data += "&emailaddress=" + URLEncoder.encode(emailAddress, "UTF-8");

        link = "http://192.168.43.212/signup.php" + data;
        URL url = new URL(link);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();

        bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
        result = bufferedReader.readLine();
        return result;
    } catch (Exception e) {
        return new String("Exception: " + e.getMessage());
    }
}

@Override
protected void onPostExecute(String result) {

    if (result.equals("Registration Successfull")) {
        Toast.makeText(context, "Data inserted successfully. Signup successful.", Toast.LENGTH_SHORT).show();
    }
    else {
        Toast.makeText(context, "Registration Unsuccessfull", Toast.LENGTH_SHORT).show();
    }
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
}

}

这里我使用GET方法,signup.php文件将值传递给signup.php:

<?php
 $con=mysqli_connect("localhost","rohan","rohan","singup");
 mysqli_connect_errno($con);

 $fullName = $_GET['fullname'];
 $userName = $_GET['username'];
 $passWord = $_GET['password'];
 $phoneNumber = $_GET['phonenumber'];
 $emailAddress = $_GET['emailaddress'];

 $result = mysqli_query($con,"INSERT INTO user (fullname, username, 
 password, phone, email) VALUES ('$fullName', '$userName', '$passWord', '$phoneNumber', '$emailAddress')");


if($result == true) {
    echo "Registration Successfull";
}
else{
    echo "Registration Unsuccessfull";
}

mysqli_close($con);?>

为了在MainActivity中调用singup方法,我在MainActivity的布局文件(.xml)中给出了onClick value to(singup)按钮

<Button
android:id="@+id/btnSignup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="signup"
android:text="Sign up" />

我希望这会对你有所帮助,并建议不要使用Asynctask进行Http调用,而是使用另一个像Volley和Retrofit来轻松快速地连接......