Android-соединение с базой данных MYSQL с использованием php
Я пытаюсь соединить мою страницу входа Android с базой данных MySQL, присутствующей на сервере.
Но сейчас я сталкиваюсь с проблемой передачи PHP-файла через Android. Мое соединение от PHP до базы данных MySQL, однако, успешно.
Код PHP:
<?php
$host='localhost';
$uname='amodbina0106';
$pwd='Amodbina200';
$db="kezin_king";
$con=mysqli_connect("localhost","amodbina0106","Amodbina200","kezin_king");
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
echo "Connection Successful";
$username = $_GET['username'];
$password = $_GET['password'];
$flag['code']=0;
if($name == '' || $username == '' || $password == '' || $email == ''){
echo 'please fill all values';
}
else{
$sql=mysql_query("insert into sample values('$id','$name') ",$con);
if(mysqli_query($con,$sql))
{
$flag['code']=1;
echo"hi";
}
print(json_encode($flag));
mysql_close($con);
}
?>
Вывод после запуска php-файла в веб-браузере:
Соединение установлено, пожалуйста, заполните все значения
Мой код MainActivity:
package com.example.nupur.phpdb_con;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.Buffer;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class MainActivity extends AppCompatActivity {
EditText etUsername, etPassword;
TextView txtView;
Button btnLogin;
String username;
String password;
InputStream is = null;
String result = "";
String line = null;
int code;
InputStream inputStream = null;
BufferedReader reader;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
txtView = (TextView) findViewById(R.id.txtView);
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
username = etUsername.getText().toString();
password = etPassword.getText().toString();
insert();
// txtView.setText(etUsername.getText()+" "+etPassword.getText());
}
});
}
public String insert() {
BufferedReader bufferedReader;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<>();
nameValuePairs.add(new BasicNameValuePair("Username", username));
nameValuePairs.add(new BasicNameValuePair("Password", password));
try {
// create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// make GET request to the given URL
HttpResponse httpResponse = httpclient.execute(new HttpGet("http://kezinking.com/SampleConLogin"));
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// convert inputstream to string
if (inputStream != null) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
while ((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
} else
result = "Did not work!";
} catch (Exception e) {
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
try {
BufferedReader reader = new BufferedReader
(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
} catch (Exception e) {
Log.e("Fail 2", e.toString());
}
try {
JSONObject json_data = new JSONObject(result);
code = (json_data.getInt("code"));
if (code == 1) {
Toast.makeText(getBaseContext(), "Inserted Successfully",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getBaseContext(), "Sorry, Try Again",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Log.e("Fail 3", e.toString());
}
return null;
}
// @Override
//public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.activity_main, menu);
//return true;
//}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.nupur.phpdb_con.MainActivity">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ems="10"
android:id="@+id/etUsername"
android:layout_marginBottom="10px"
android:hint="UserName"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/etPassword"
android:ems="10"
android:layout_marginTop="100px"
android:hint="Password" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="@+id/btnLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="250px"
android:gravity="center"
android:text="@string/Login"
android:layout_marginTop="400px"/>
</LinearLayout>
<TextView
android:gravity="bottom"
android:id="@+id/txtView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</android.support.constraint.ConstraintLayout>
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.nupur.phpdb_con">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
После ошибки отладки:
E/Fail 1: android.os.NetworkOnMainThreadException
E/Fail 2: java.lang.NullPointerException: lock == null
E/Fail 3: org.json.JSONException: End of input at character 0 of
Ошибка в эмуляторе:
Неверный IP-адрес
3 ответа
MainActivity.Java
package com.example.nupur.phpdb_con;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.Buffer;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import static android.R.attr.id;
public class MainActivity extends ActionBarActivity {
EditText etUsername, etPassword;
TextView Show;
Button btnLogin;
String username;
String password;
InputStream is = null;
String result = "";
String line = null;
int code;
InputStream inputStream = null;
BufferedReader reader;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
Show = (TextView) findViewById(R.id.txtView);
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
username = etUsername.getText().toString();
password = etPassword.getText().toString();
insert(username,password);
//Show.setText(etUsername.getText()+" "+etPassword.getText());
}
});
}
public void insert(final String username, final String password){
class SendPostReqAsynTask extends AsyncTask<String,Void,String>{
@Override
protected String doInBackground(String... params) {
String paramUsername=params[0];
String paramPassword=params[1];
//String username = etUsername.getText().toString();
//String password = etPassword.getText().toString();
List<NameValuePair> nameValuePairs= new ArrayList<>();
nameValuePairs.add(new BasicNameValuePair("username",username));
nameValuePairs.add(new BasicNameValuePair("password",password));
try{
HttpClient httpClient = new DefaultHttpClient();
// HttpGet request = new HttpGet("http://www.example.com");
HttpPost httpPost = new HttpPost("http://kezinking.com/try.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response= httpClient.execute(httpPost);
HttpEntity entity= response.getEntity();
int i =response.getStatusLine().getStatusCode();
System.out.println(i);
}catch(ClientProtocolException e){
}catch (IOException e){
}
return "Success";
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
TextView textViewResult = (TextView) findViewById(R.id.txtView);
textViewResult.setText("Inserted");
}
}
SendPostReqAsynTask sendPostReqAsynTask=new SendPostReqAsynTask();
sendPostReqAsynTask.execute(username,password);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
AndroidManifest.xml: -
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.nupur.phpdb_con">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Android- Activity_main.xml: -
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.nupur.phpdb_con.MainActivity">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ems="10"
android:id="@+id/etUsername"
android:layout_marginBottom="10px"
android:hint="UserName"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/etPassword"
android:ems="10"
android:layout_marginTop="100px"
android:hint="Password" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="@+id/btnLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="250px"
android:gravity="center"
android:text="@string/Login"
android:layout_marginTop="400px"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_marginTop="600px"
android:gravity="bottom"
android:id="@+id/txtView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</android.support.constraint.ConstraintLayout>
PHP-файл:-(try.php)
?php
$con=mysqli_connect("localhost","amodbina0106","Amodbina200","kezin_king");
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
echo "Connected successfully";
?>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<table style="width: 100%">
<?php
$username=($_POST['username']);
$password=($_POST['password']);
$sql=mysqli_query($con,"INSERT INTO `kezin_king`.`Test` (`Vendor_ID`, `username`, `password`) VALUES (NULL, '$username', '$password')");
$sql=mysqli_query($con,"SELECT * FROM `Test` WHERE 1");
while($row=mysqli_fetch_assoc($sql))
{
$vendor_id=$row['Vendor_ID'];
$user_name=$row['username'];
$password=$row['password'];
?>
<tr>
<th><?php echo $vendor_id; ?></th>
<th><?php echo $user_name; ?></th>
<th><?php echo $password; ?></th>
</tr>
<?php }?>
</table>
Здесь имя таблицы - Test, а используемая база данных называется kezinking.
Попробуйте, как показано ниже: В вызове метода вставки asynctask, как показано ниже:
new insertData().execute(namevaluepair);
а затем код, как показано ниже:
private class insertData extends AsyncTask<Arraylist<NameValuePair>, Void, String> { @Override
protected String doInBackground(Arraylist<NameValuePair>... params) {
ArrayList<NameValuePair> namevaluepair=params[0];
//make http request here
}}
Для получения дополнительной информации, перейдя по этой ссылке, вы получите представление о том, как ее реализовать. Как вставить данные в PHP с помощью веб-сервиса Android
Вы не можете отобразить строку в php-файле и представить как JSONObject в Android.
все ошибки и сообщения должны быть в массиве json, а в файле php показан только массив json.
я предлагаю это:
<?php
$host='localhost';
$uname='amodbina0106';
$pwd='Amodbina200';
$db="kezin_king";
$result = array();
$con=mysqli_connect("localhost","amodbina0106","Amodbina200","kezin_king");
if ($con->connect_error) {
$result['status'] = false;
$result['message'] = 'server lost';
die(json_encode($result));
}
$username = $_GET['username'];
$password = $_GET['password'];
$flag['code']=0;
if($name == '' || $username == '' || $password == '' || $email == ''){
$result['status'] = false;
$result['message'] = 'All field required';
}
else{
$sql=mysql_query("insert into sample values('$id','$name') ",$con);
if(mysqli_query($con,$sql))
{
$flag['code']=1;
$result['status'] = true;
$result['message'] = 'hi';
}
print(json_encode($result));
mysql_close($con);
}
?>