Hello all..
I have shown two other examples for creating a connection between android and php. But still users are finding difficulty in grasping it.
These are other posts.
1.Android phpMysql connection.
2.Android phpmySQL connection redone.
Here is one more post on this which is even more detailed.
OK we will start now.
First create a fresh project named “AndroidPHP”.
Now My main java file is named “AndroidPHPConnectionDemo.java”.
First we will create a layout for the login form. This xml will do this. copy this code to main.xml.
<code>
</code>
Now create another xml named userpage.xml by right clicking the layout folder -> Android XML File.
Copy this code into that. This is the layout to show in the activity when the user successfully logins.
<code>
</code>
Now in the main java file im my case AndroidPHPConnectionDemo.java, copy this code.
<ocde>
</code>
Now create another java class “UserPage.java”
This is simply a navigation page when the user log in.
<code>
</code>
OK Android side is done.
Now the server side (php side).
These things you need top remember.
1. Make sure the url you are providing to the android java code is correct.
2. Make sure your server is running.
3. Make sure your php page has no errors.
4. Also if connecting to a remote URL, you should have internet connection in your emulator or device.
5. Make sure you have a database named mydatabase(in this case) and a table named “tbl_user” and some users inserted in it.
This is the creation query of the table tbl_user in the MYSQL database.
<ocde>
Check the screenshot.
I an using xampp server.
So inside xampp/htdocs folder, i have a folder named “my_folder_inside_htdocs”. Inside this folder I have a php file “check.php” which has the code for checking the user in the database.
Copy this code to check.php
<code>
</code>
Done.Now run your project and sign in with a valid user. that’s all.
Happy Coding.
Feel free to ask if you have any doubts.
Please leave your valuable comments on this post and also you can share this post.
Download the complete source code of this example from here.
References: http://www.coderzheaven.com
I have shown two other examples for creating a connection between android and php. But still users are finding difficulty in grasping it.
These are other posts.
1.Android phpMysql connection.
2.Android phpmySQL connection redone.
Here is one more post on this which is even more detailed.
OK we will start now.
First create a fresh project named “AndroidPHP”.
Now My main java file is named “AndroidPHPConnectionDemo.java”.
First we will create a layout for the login form. This xml will do this. copy this code to main.xml.
<code>
<?xml version="1.0" encoding="utf-8"?> android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_gravity="center|center_vertical" ><TextView android:id="@+id/tv0" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Login Form Demo From Coderzheaven" android:textSize="20sp" android:gravity="center" android:textStyle="bold" /><TextView android:id="@+id/tv1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Username" /><EditText android:text="" android:id="@+id/username" android:layout_width="fill_parent" android:layout_height="wrap_content" android:singleLine="true"></EditText><TextView android:id="@+id/tv2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Password" /><EditText android:text="" android:id="@+id/password" android:layout_width="fill_parent" android:layout_height="wrap_content" android:singleLine="true"></EditText><Button android:text="Login" android:id="@+id/Button01" android:layout_width="fill_parent" android:layout_height="wrap_content"></Button><TextView android:id="@+id/tv" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="" /></LinearLayout>Now create another xml named userpage.xml by right clicking the layout folder -> Android XML File.
Copy this code into that. This is the layout to show in the activity when the user successfully logins.
<code>
<?xml version="1.0" encoding="utf-8"?><LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content"> <TextView android:text="Login Success." android:id="@+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content"> </TextView></LinearLayout></code>
Now in the main java file im my case AndroidPHPConnectionDemo.java, copy this code.
<ocde>
package pack.coderzheaven;import java.util.ArrayList;import java.util.List;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.HttpClient;import org.apache.http.client.ResponseHandler;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.BasicResponseHandler;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import android.app.Activity;import android.app.AlertDialog;import android.app.ProgressDialog;import android.content.DialogInterface;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast;public class AndroidPHPConnectionDemo extends Activity { Button b; EditText et,pass; TextView tv; HttpPost httppost; StringBuffer buffer; HttpResponse response; HttpClient httpclient; List<NameValuePair> nameValuePairs; ProgressDialog dialog = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); b = (Button)findViewById(R.id.Button01); et = (EditText)findViewById(R.id.username); pass= (EditText)findViewById(R.id.password); tv = (TextView)findViewById(R.id.tv); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dialog = ProgressDialog.show(AndroidPHPConnectionDemo.this, "", "Validating user...", true); new Thread(new Runnable() { public void run() { login(); } }).start(); } }); } void login(){ try{ httpclient=new DefaultHttpClient(); httppost= new HttpPost("http://10.0.2.2/my_folder_inside_htdocs/check.php"); // make sure the url is correct. //add your data nameValuePairs = new ArrayList<NameValuePair>(2); //
Always use the same variable name for posting i.e the android side
variable name and php side variable name should be similar, nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim())); // $Edittext_value = $_POST['Edittext_value']; nameValuePairs.add(new BasicNameValuePair("password",pass.getText().toString().trim())); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); //Execute HTTP Post Request response=httpclient.execute(httppost); // edited by James from coderzheaven.. from here.... ResponseHandler<String> responseHandler = new BasicResponseHandler(); final String response = httpclient.execute(httppost, responseHandler); System.out.println("Response : " + response); runOnUiThread(new Runnable() { public void run() { tv.setText("Response from PHP : " + response); dialog.dismiss(); } }); if(response.equalsIgnoreCase("User Found")){ runOnUiThread(new Runnable() { public void run() { Toast.makeText(AndroidPHPConnectionDemo.this,"Login Success", Toast.LENGTH_SHORT).show(); } }); startActivity(new Intent(AndroidPHPConnectionDemo.this, UserPage.class)); }else{ showAlert(); } }catch(Exception e){ dialog.dismiss(); System.out.println("Exception : " + e.getMessage()); } } public void showAlert(){ AndroidPHPConnectionDemo.this.runOnUiThread(new Runnable() { public void run() { AlertDialog.Builder builder = new AlertDialog.Builder(AndroidPHPConnectionDemo.this); builder.setTitle("Login Error."); builder.setMessage("User not Found.") .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); AlertDialog alert = builder.create(); alert.show(); } }); }}</code>
Now create another java class “UserPage.java”
This is simply a navigation page when the user log in.
<code>
package pack.coderzheaven;import android.app.Activity;import android.os.Bundle;public class UserPage extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.userpage); }}</code>
OK Android side is done.
Now the server side (php side).
These things you need top remember.
1. Make sure the url you are providing to the android java code is correct.
2. Make sure your server is running.
3. Make sure your php page has no errors.
4. Also if connecting to a remote URL, you should have internet connection in your emulator or device.
5. Make sure you have a database named mydatabase(in this case) and a table named “tbl_user” and some users inserted in it.
This is the creation query of the table tbl_user in the MYSQL database.
<ocde>
CREATE TABLE `mydatabase`.`tbl_user` (`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,`username` VARCHAR( 20 ) NOT NULL ,`password` VARCHAR( 20 ) NOT NULL) ENGINE = MYISAM</code> I an using xampp server.
So inside xampp/htdocs folder, i have a folder named “my_folder_inside_htdocs”. Inside this folder I have a php file “check.php” which has the code for checking the user in the database.
Copy this code to check.php
<code>
<?php$hostname_localhost ="localhost";$database_localhost ="mydatabase";$username_localhost ="root";$password_localhost ="";$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)ortrigger_error(mysql_error(),E_USER_ERROR);mysql_select_db($database_localhost, $localhost);$username = $_POST['username'];$password = $_POST['password'];$query_search = "select * from tbl_user where username = '".$username."' AND password = '".$password. "'";$query_exec = mysql_query($query_search) or die(mysql_error());$rows = mysql_num_rows($query_exec);//echo $rows; if($rows == 0) { echo "No Such User Found"; } else { echo "User Found"; }?></code>
Done.Now run your project and sign in with a valid user. that’s all.
NOTE: All NETWORK OPERATIONS SHOULD BE DONE INSIDE A THREAD.
Happy Coding.
Feel free to ask if you have any doubts.
Please leave your valuable comments on this post and also you can share this post.
Download the complete source code of this example from here.
References: http://www.coderzheaven.com





No comments :
Post a Comment