Nupur Bhagat Nupur Bhagat - 4 months ago 6
MySQL Question

Android Connection with MYSQL database using php

I am trying to connect my android login page with MYSQL database present on the server. But I am facing problem now in passing php file through android.. My connection from php to MYSql database is successful.

PHP CODE:-

<?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);
}
?>

**Output :-**
[1]: http://kezinking.com/SampleConLogin


The output after running the php file on web browser is:-
" Connection Successful please fill all values "

Android- MainActivity.Java

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>


After Debugging Error:-
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

Error in Emulator:-
Invalid Ip Address




Thanks for helping me..(In Advance..)

Answer

Try like below: In insert method call asynctask like below:

new insertData().execute(namevaluepair);

and then code like below:

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
    }}

for more information see this link you get idea how to implement it. how to insert data in php using web service android