我正在开发一个Android应用程序,需要使用mysql
向php
db发布和获取数据。现在我正在尝试将用户注册到应用程序。我创建了2个php
类连接和 insertUser 。使用Postman,我可以成功地将数据插入数据库。但是,当我尝试使用手机时,它会崩溃。我的代码构建没有错误,直到我按SignUp
按钮它工作正常。我无法看到我犯错误的地方。请帮忙。
我添加了我的依赖项。
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
compile 'com.squareup.okhttp:okhttp:2.0.0'
Connection.php用于连接我的localhost XAMPP Phpmyadmin。
<?php
class Connection{
function getConnection(){
$host = "localhost";
$username = "root";
$password = "root";
$dbname = "activityplanner_db";
try{
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
}catch (PDOException $e){
echo "ERROR CONNECTIONF : " . $e->getMessage();
}
}
}
?>
insertUser.php,用于将用户信息插入数据库。
<?php
require_once('Connection.php');
class insertUser{
function startInsertUser(){
$connection = new Connection();
$conn = $connection->getConnection();
//array for json response
$response = array();
$Lastname = $_POST['LastName'];
$Firstname = $_POST['FirstName'];
$Email = $_POST['User_Email'];
$Mobilephone = $_POST['MobilePhone'];
$Ssn = $_POST['SSN'];
$Password = $_POST['User_Password'];
$City = $_POST['User_City'];
$JobTittle = $_POST['User_Job'];
$BirthDate = $_POST['User_BirthDate'];
$Gender = $_POST['Gender'];
if($Lastname == '' || $Firstname == '' || $Email == '' || $Mobilephone == '' || $Ssn == '' || $Password == '' || $City == '' || $JobTittle == '' ||
$BirthDate == ''){
echo 'All fields required';
}
try{
if(isset($Email) && isset($Ssn)){
$sqlInsert = "INSERT INTO user (LastName, FirstName, User_Email, MobilePhone, SSN, User_Password,
User_City, User_Job, User_BirthDate, Gender) VALUES ('$Lastname', '$Firstname', '$Email', '$Mobilephone', '$Ssn', '$Password',
'$City','$JobTittle', '$BirthDate', '$Gender')";
$conn->exec($sqlInsert);
}
}catch (PDOException $e){
echo "Error while inserting ".$e->getMessage();
}
//cek is the row was inserted or not
if($sqlInsert){
//success inserted
$response["success"] = 1;
$response["message"] = "User successful inserted!";
echo json_encode($response);
}else{
//failed inserted
$response["success"] = 0;
$response["message"] = "Failed while insert data";
echo json_encode($response);
}
}
}
$insert = new insertUser();
$insert->startInsertUser();;
?>
LoggingInterceptors
。java查看进程显示数据的输出。如果有错误,则此类文件知道错误的原因。 Ť
public class LoggingInterceptors implements Interceptor{
@Override
public Response intercept(Chain chain) throws IOException{
Request request = chain.request();
long t1 = System.nanoTime();
String requestLog = String.format("Sending request %s on %s%n%s",
request.url(), chain.connection(), request.headers());
if (request.method().compareToIgnoreCase("post") == 0){
requestLog = "\n" + requestLog + "\n" + bodyToString(request);
}
Log.d("TAG", "request" + "\n" + requestLog);
Response response = chain.proceed(request);
long t2 = System.nanoTime();
String responseLog = String.format("Received response for %s in %.1fms%n%s",
response.request().url(), (t2 - t1) / 1e6d, response.headers());
String bodyString = response.body().string();
Log.d("TAG", "response" + "\n" + responseLog + "\n" + bodyString);
return response.newBuilder()
.body(ResponseBody.create(response.body().contentType(), bodyString))
.build();
}
public static String bodyToString(final Request request){
try{
final Request copy = request.newBuilder().build();
final Buffer buffer = new Buffer();
copy.body().writeTo(buffer);
return buffer.readUtf8();
}catch (final IOException e){
return "did not work";
}
}
}
我的URLs.java
Api客户Retrofit Client
。
public class URLs {
public static final String URL = "http://192.168.43.172/activityplanner_php/";
//当我将电脑连接到手机的热点时,这是我的ipv4 ip。 public static Retrofit retrofit = null;
public static Retrofit getClient(){
if (retrofit==null){
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new LoggingInterceptors())
.build();
retrofit = new Retrofit.Builder()
.baseUrl(URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
我的RegisterApi界面
public interface RegisterAPI {
@FormUrlEncoded
@POST("/activityplanner_php/insertUser.php")
Call<User> insertUser(@Field("LastName") String LastName, @Field("FirstName") String FirstName,
@Field("User_Email") String User_Email, @Field("MobilePhone") long MobilePhone,
@Field("SSN") String SSN, @Field("User_Password") String User_Password,
@Field("User_City") String User_City, @Field("User_Job") String User_Job,
@Field("User_BirthDate") Date User_BirthDate, @Field("Gender") String Gender);
}
我的用户响应模型。
public class User {
@SerializedName("success")
private int status;
@SerializedName("message")
private String message;
public User(int status, String message) {
this.status = status;
this.message = message;
}
public User() {
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
我的SignUpActivity。
public class SignUpActivity extends AppCompatActivity {
EditText etLastName, etFirstName, etEmail, etMobilePhone, etSsn, etPassword, etCity, etJob, etBirthDate;
RadioGroup rgGender;
Spinner spUserType;
ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
Button btnSignUp = (Button) findViewById(R.id.bSignUp);
etBirthDate = (EditText) findViewById(R.id.etBirthDate);
etLastName = (EditText) findViewById(R.id.etLastName);
etFirstName = (EditText) findViewById(R.id.etName);
etEmail = (EditText) findViewById(R.id.etEmail);
etMobilePhone = (EditText) findViewById(R.id.etPhone);
etSsn = (EditText) findViewById(R.id.etSSN);
etPassword = (EditText) findViewById(R.id.etPassword);
etCity = (EditText) findViewById(R.id.etCity);
etJob = (EditText) findViewById(R.id.etJob);
rgGender = (RadioGroup) findViewById(R.id.rgGender);
spUserType = (Spinner) findViewById(R.id.spUserRole);
btnSignUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
insertUser();
}
});
}
/*public void GoToLoginActivity(View v) {
insertUser();
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
}*/
private void insertUser(){
progressDialog.show();
String firstName = etFirstName.getText().toString();
String lastName = etLastName.getText().toString();
String u_Email = etEmail.getText().toString();
int radioButtonId = rgGender.getCheckedRadioButtonId();
View radioButton = rgGender.findViewById(radioButtonId);
int idx = rgGender.indexOfChild(radioButton);
RadioButton rbGender = (RadioButton)rgGender.getChildAt(idx);
String gender = rbGender.getText().toString();
Long mobilePhone =Long.parseLong(etMobilePhone.getText().toString());
String ssn = etSsn.getText().toString();
String u_City = etCity.getText().toString();
Date birthDate =Date.valueOf(etBirthDate.getText().toString());
String u_Job = etJob.getText().toString();
String password = etPassword.getText().toString();
insertData(firstName,lastName,u_Email,gender,mobilePhone,ssn,u_City,birthDate,u_Job,password);
}
private void insertData(String firstName, String lastName, String u_Email, String gender,
Long mobilePhone, String ssn, String u_City, Date birthDate, String u_Job, String password){
RegisterAPI registerAPI = URLs.getClient().create(RegisterAPI.class);
Call<User> call = registerAPI.insertUser(firstName, lastName, u_Email, mobilePhone, ssn, password,
u_City, u_Job, birthDate, gender);
call.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
User user =response.body();
if(user.getStatus()==1){
Toast.makeText(SignUpActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}else{
Toast.makeText(SignUpActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}
@Override
public void onFailure(Call<User> call, Throwable t) {
Toast.makeText(SignUpActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
});
}
}
我的activity_sign_up.xml布局。
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:background="@color/OpeningBackground"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="55dp"
android:background="@color/toolbar"
android:minHeight="?attr/actionBarSize"
android:theme="@android:style/Widget"
tools:layout_editor_absoluteY="1dp" />
<ScrollView
style="@android:style/Widget.DeviceDefault.Light.ScrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="52dp"
android:clipToPadding="true"
android:fillViewport="true"
android:scrollbarStyle="insideOverlay"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="200dp">
<EditText
android:id="@+id/etBirthDate"
style="@android:style/Widget.Material.Light.EditText"
android:layout_width="364dp"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:ems="10"
android:layout_marginStart="8dp"
android:hint="@string/birthDate"
android:inputType="date"
android:textColor="#ffffff"
android:textColorHint="#ffffff"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="@+id/etJob" />
<EditText
android:id="@+id/etPassword"
style="@android:style/Widget.Material.Light.EditText"
android:layout_width="364dp"
android:layout_marginStart="8dp"
android:layout_height="45dp"
android:layout_marginTop="16dp"
android:ems="10"
android:hint="@string/password"
android:inputType="numberPassword"
android:textAppearance="@android:style/Widget.Material.Light.EditText"
android:textColor="#ffffff"
android:textColorHint="#ffffff"
android:textSize="16sp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="@+id/etSSN" />
<EditText
android:id="@+id/etPhone"
style="@android:style/Widget.Material.Light.EditText"
android:layout_width="364dp"
android:layout_marginStart="8dp"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:ems="10"
android:hint="@string/phone"
android:inputType="phone"
android:textColor="#ffffff"
android:textColorHint="#ffffff"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="@+id/etEmail" />
<EditText
android:id="@+id/etName"
style="@android:style/Widget.Material.Light.EditText"
android:layout_width="179dp"
android:layout_height="wrap_content"
android:layout_marginLeft="200dp"
android:layout_marginTop="16dp"
android:ems="10"
android:hint="@string/Name"
android:inputType="textPersonName"
android:singleLine="true"
android:textColor="#ffffff"
android:textColorHint="#ffffff"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="@+id/etLastName"
style="@android:style/Widget.Material.Light.EditText"
android:layout_width="182dp"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:ems="10"
android:layout_marginStart="8dp"
android:hint="@string/lName"
android:inputType="textPersonName"
android:singleLine="true"
android:textColor="#ffffff"
android:textColorHint="#ffffff"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="@+id/etEmail"
android:layout_width="364dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:ems="10"
android:hint="@string/email"
android:inputType="textEmailAddress"
android:textColor="#ffffff"
android:textColorHint="#ffffff"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="@+id/etLastName" />
<EditText
android:id="@+id/etSSN"
style="@android:style/Widget.Material.Light.EditText"
android:layout_width="364dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:ems="10"
android:hint="@string/ssn"
android:inputType="number"
android:textColor="#ffffff"
android:textColorHint="#ffffff"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="@+id/etPhone" />
<EditText
android:id="@+id/etCity"
style="@android:style/Widget.Material.Light.EditText"
android:layout_width="364dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:ems="10"
android:hint="@string/city"
android:inputType="textPersonName"
android:textColor="#ffffff"
android:textColorHint="#ffffff"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/etPassword" />
<EditText
android:id="@+id/etJob"
style="@android:style/Widget.Material.Light.EditText"
android:layout_width="364dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:ems="10"
android:hint="@string/Job"
android:inputType="textPersonName"
android:textColor="#ffffff"
android:textColorHint="#ffffff"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/etCity" />
<Spinner
android:id="@+id/spUserRole"
style="@android:style/Widget.Material.Light.TextView.SpinnerItem"
android:layout_width="364dp"
android:layout_height="51dp"
android:layout_marginBottom="175dp"
android:layout_marginStart="8dp"
android:entries="@array/user_role"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tUser_Role_Hint"
app:layout_constraintVertical_bias="0.0" />
<TextView
android:id="@+id/tUser_Role_Hint"
android:layout_width="364dp"
android:layout_height="41dp"
android:layout_marginTop="16dp"
android:layout_marginStart="8dp"
android:text="@string/user_role_hint"
android:textAppearance="@style/TextAppearance.AppCompat.Widget.PopupMenu.Large"
android:textColor="#ffffff"
android:textSize="18sp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="@+id/etBirthDate" />
<Button
android:id="@+id/bSignUp"
style="@android:style/Widget.Material.Light.Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="48dp"
android:layout_marginEnd="32dp"
android:backgroundTint="@color/OpeningBackground"
android:text="@string/btnSignUp"
android:textColor="@android:color/background_light"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<TextView
android:id="@+id/textView"
android:layout_width="92dp"
android:layout_height="27dp"
android:layout_marginStart="24dp"
android:layout_marginTop="32dp"
android:text="@string/gender"
android:textColor="@color/buttoncolor"
android:textSize="20sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/spUserRole" />
<RadioGroup
android:id="@+id/rgGender"
android:layout_width="177dp"
android:layout_height="91dp"
android:layout_marginStart="20dp"
android:layout_marginTop="12dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView">
<RadioButton
android:id="@+id/rbMan"
style="@android:style/Widget.DeviceDefault.Light.CompoundButton.RadioButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:buttonTint="@color/buttoncolor"
android:text="Erkek"
android:textColor="#ffffff"
tools:layout_editor_absoluteX="16dp"
tools:layout_editor_absoluteY="676dp" />
<RadioButton
android:id="@+id/rbWoman"
style="@android:style/Widget.DeviceDefault.Light.CompoundButton.RadioButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:buttonTint="@color/buttoncolor"
android:text="Kadın"
android:textColor="#ffffff"
tools:layout_editor_absoluteX="130dp"
tools:layout_editor_absoluteY="676dp" />
</RadioGroup>
</android.support.constraint.ConstraintLayout>
</ScrollView>
</android.support.design.widget.CoordinatorLayout>
答案 0 :(得分:0)
我没有看到你在这里初始化进度对话框。我想这是在调用 show()
之前没有初始化进度对话框的错误ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
progressDialog = new ProgressDialog(this);
...............
}