如何使用android studio和phpmyadmin(wampserver)将数据插入数据库?

时间:2016-09-09 04:06:46

标签: android phpmyadmin

我是android的新手。我正在使用android studio 1.0.1和phpmyadmin(wampserver)。我想创建一个应用程序,它会在按钮点击时将学生详细信息添加到数据库中。我的页面将包含Rollno,名称,Degree,Course.On添加按钮单击这些数据必须插入数据库libraryapp下的student表。我已经创建了数据库和学生表,但是不知道数据库连接.Plzzz帮帮我..谢谢提前..

2 个答案:

答案 0 :(得分:1)

我有一个类似的例子来保存用户名和密码,尝试根据你的想法进行修改。这个过程非常相似。

//Layout of Activity
<?xml version="1.0" encoding="utf-8"?>
<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:padding="2dp"
tools:context="com.test.test.ScreenOne">


<EditText
    android:layout_width="240dp"
    android:layout_height="wrap_content"
    android:id="@+id/etUsername"
    android:layout_marginTop="150dp"
    android:hint="username"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true" />

<EditText
    android:layout_width="240dp"
    android:layout_height="wrap_content"
    android:id="@+id/etPassword"
    android:hint="password"
    android:layout_below="@+id/etUsername"
    android:layout_centerHorizontal="true" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Save"
    android:id="@+id/bSave"
    android:layout_below="@+id/bLogin"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="42dp" />
</RelativeLayout> 

Activity有1个按钮和2个EditText,Save按钮将数据保存在服务器中:

package com.test.test;

import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;

import java.util.HashMap;
import java.util.Map;

public class ScreenOne extends AppCompatActivity {

private static final String URL_SAVE = "http://IP_ADDRESS/save.php";
private EditText username;
private EditText password;
Button save;
String name;
String pass;

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

    username = (EditText) findViewById(R.id.etUsername);
    password = (EditText) findViewById(R.id.etPassword);

    (save = (Button) findViewById(R.id.bSave)).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            saveRequest();
        }
    });
}

private void saveRequest() {
    name = username.getText().toString().trim();
    pass = password.getText().toString().trim();
    final ProgressDialog mDialog = new ProgressDialog(this);
    mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    mDialog.setMessage("Loading...");
    mDialog.show();

    StringRequest request = new StringRequest(Request.Method.POST, URL_SAVE,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    mDialog.dismiss();
                    Toast.makeText(ScreenOne.this, response, Toast.LENGTH_LONG).show();
                    username.setText("");
                    password.setText("");
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    mDialog.dismiss();
                    Toast.makeText(ScreenOne.this, "Something went wrong", Toast.LENGTH_LONG).show();
                }
            }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> key = new HashMap<>();
            key.put("username", name);
            key.put("password", pass);
            return key;
        }
    };

    NetworkCalls.getInstance().addToRequestQueue(request);
}

Volley请求的Singleton类:

import android.content.Context;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

/**
 * Created by W4R10CK on 13-09-2016.
 */
public class NetworkCalls {
    private RequestQueue requestQueue;
    private static Context context;

    private static NetworkCalls ourInstance = new NetworkCalls();

    public static NetworkCalls getInstance() {
        return ourInstance;
    }

    private NetworkCalls() {
    }

    public RequestQueue getRequestQueue(){
        requestQueue = Volley.newRequestQueue(context.getApplicationContext());
        return requestQueue;
    }

    public <T> void addToRequestQueue(Request<T> request){
        getRequestQueue().add(request);
    }
}

调用服务器的API:

 //conn.php for connection (file one)
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db_name = "hello";

$con = new mysqli($host,$user,$pass,$db_name);

if($con -> connect_error){
echo "Connection error";
}   


//save.php(file two)
<?php
$username = $_POST['username'];
$password = $_POST['password'];
require_once('conn.php');

$sql = "INSERT INTO user (username, password) VALUES ('$username','$password')";

if($con -> query($sql) === TRUE) {
echo "User added";
}
//$con -> close();
?>
?>

最后在localhost 用户中创建一个名为 hello 的数据库,其中包含2个字段用户名密码。< / p>

答案 1 :(得分:0)

正如您所说,首先您必须创建PHP / Java API以与数据库通信。在Android中你必须使用网络电话,例如“凌空”。使用凌空进行网络通话非常简单而且很酷。我建议您阅读一些教程:Registration via Volley (WampServer)