بسم الله الرحمن الرحيم
في هذا الدرس سنقوم بعمل تطبيق تسجيل الدخول من خلال php & mysql
android login by mysql and json php

في البداية جدول قاعدة البيانات user
CREATE TABLE IF NOT EXISTS `user` (
`user_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`user_name` varchar(50) NOT NULL,
`password` varchar(20) NOT NULL,
`user_email` varchar(50) NOT NULL,
PRIMARY KEY (`user_id`),
UNIQUE KEY `user_email` (`user_email`)
)
كود صفحة conn.php وهو عبارة عن ملف يقوم بتجهيز لإتصال يقاعدة البيانات
<?php
$con = mysql_connect("localhost","root","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db= mysql_select_db("mokalfat", $con);
?>
$con = mysql_connect("localhost","root","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db= mysql_select_db("mokalfat", $con);
?>
كود صفحة login.php وهي الصفحة التي تستقبل المتغيرات من تطبيق الأندرويد و ترجع متغيرات json
<?php
require 'conn.php';
$username=$_GET['username'];
$pass=$_GET['pass'];
$query = "SELECT * FROM user where user_name='$username' and password='$pass' ";
$final_data = array();
if ($query_run = mysql_query($query))
{
$i=0;
$id ;
while($query_row = mysql_fetch_assoc($query_run))
{
$id =$query_row ['id'];
$i++;
}
if( $i==0)
{
$data = array('state' => '0', 'id' => 'Noid');
print (json_encode($data));
}
else {
$data = array('state' => '1', 'id' => ''.$id);
print (json_encode($data));
}
}else{
echo mysql_error();
}
?>
require 'conn.php';
$username=$_GET['username'];
$pass=$_GET['pass'];
$query = "SELECT * FROM user where user_name='$username' and password='$pass' ";
$final_data = array();
if ($query_run = mysql_query($query))
{
$i=0;
$id ;
while($query_row = mysql_fetch_assoc($query_run))
{
$id =$query_row ['id'];
$i++;
}
if( $i==0)
{
$data = array('state' => '0', 'id' => 'Noid');
print (json_encode($data));
}
else {
$data = array('state' => '1', 'id' => ''.$id);
print (json_encode($data));
}
}else{
echo mysql_error();
}
?>
الأن نتجه الي عمل تطبيق الجوال نقوم بإنشاء مشروع جديد بإستخدام eclipse.exe
نقوم بتعديل ال activty الموجودة او نقوم بإنشاء activty جديد ونضيف اليه مربيعن نص مربع لإسم المستخدم و الأخر لكلمة المرور و زر الدخول او صمم الواجهه التي تعجبك !
انظر لصورة activty التالية :
<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"
tools:context=".MainActivity"
android:background="#2B65EC"
>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="19dp"
android:layout_marginTop="36dp"
android:text="user name"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/editText1"
android:layout_marginTop="42dp"
android:text="password"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="@+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView2"
android:layout_marginTop="38dp"
android:ems="10"
android:inputType="textPassword" android:background="#F2EFEF" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="35dp"
android:layout_toRightOf="@+id/textView2"
android:text="Login" />
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView1"
android:layout_marginTop="22dp"
android:background="#F2EFEF"
android:ems="10" >
<requestFocus />
</EditText>
</RelativeLayout>
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:background="#2B65EC"
>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="19dp"
android:layout_marginTop="36dp"
android:text="user name"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/editText1"
android:layout_marginTop="42dp"
android:text="password"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="@+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView2"
android:layout_marginTop="38dp"
android:ems="10"
android:inputType="textPassword" android:background="#F2EFEF" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="35dp"
android:layout_toRightOf="@+id/textView2"
android:text="Login" />
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView1"
android:layout_marginTop="22dp"
android:background="#F2EFEF"
android:ems="10" >
<requestFocus />
</EditText>
</RelativeLayout>
الأن نقوم ببرمجة الأدوات نذهب class التابع لـ activty
package com.ameral.prog1;
import android.app.Activity;
import android.app.AlertDialog;
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 java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends Activity {
private EditText username;
private EditText pass;
public void mesegbox( String titel,String meseg){
AlertDialog alertDialog;
alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle(titel);
alertDialog.setMessage(meseg);
alertDialog.show();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bt1=(Button) findViewById(R.id.button1);
username=(EditText) findViewById(R.id.editText1);
pass=(EditText) findViewById(R.id.editText2);
if (getIntent().getBooleanExtra("EXIT", false)) {
finish();
}
bt1.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
String aa=username.getText().toString();
String aa2=pass.getText().toString();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.104/jonsn_android/login.php?username="+aa+"&pass="+aa2+"");
TextView textView = (TextView)findViewById(R.id.textView1);
try {
HttpResponse response = httpclient.execute(httppost);
String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
JSONObject object = new JSONObject(jsonResult);
String name = object.getString("state");
String verion = object.getString("id");
//textView.setText(name + " - " + verion);
int chk=Integer.parseInt(name);
if(chk==1)
{
mesegbox("you are login","success login thank you.");
}
else
{mesegbox("no login","error login please check user name or password ");
}
}
catch (JSONException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
});
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
e.printStackTrace();
}
return answer;
}
}
import android.app.Activity;
import android.app.AlertDialog;
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 java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends Activity {
private EditText username;
private EditText pass;
public void mesegbox( String titel,String meseg){
AlertDialog alertDialog;
alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle(titel);
alertDialog.setMessage(meseg);
alertDialog.show();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bt1=(Button) findViewById(R.id.button1);
username=(EditText) findViewById(R.id.editText1);
pass=(EditText) findViewById(R.id.editText2);
if (getIntent().getBooleanExtra("EXIT", false)) {
finish();
}
bt1.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
String aa=username.getText().toString();
String aa2=pass.getText().toString();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.104/jonsn_android/login.php?username="+aa+"&pass="+aa2+"");
TextView textView = (TextView)findViewById(R.id.textView1);
try {
HttpResponse response = httpclient.execute(httppost);
String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
JSONObject object = new JSONObject(jsonResult);
String name = object.getString("state");
String verion = object.getString("id");
//textView.setText(name + " - " + verion);
int chk=Integer.parseInt(name);
if(chk==1)
{
mesegbox("you are login","success login thank you.");
}
else
{mesegbox("no login","error login please check user name or password ");
}
}
catch (JSONException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
});
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
e.printStackTrace();
}
return answer;
}
}
و لا ننسي صلاحيات الدخول للإنترنت في التطبيق عدل ملف AndroidManifest.xml اضف الصلاحيات التالية قبل وسم
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
ملف AndroidManifest.xml الكامل بعد التعديل
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ameral.prog1"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.ameral.prog1.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ameral.prog1"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.ameral.prog1.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
قم بتشغيل التطبيق و ادخل اسم المستخدم صحيحين ستظهر لك رسالة انه تم تسجيل الدخول بنجاح واذا كانت احدهما خاطئة ستظهر له رسالة خطأ في تسجيل الدخول
تستطيع تحميل المشروع كامل من خلال الرابط التالي
تحميل تطبيق الأندرويد مفتوح المصدر : http://www.4shared.com/rar/iFXtGIXX/android_app.html
تحميل ملفات php :
http://www.4shared.com/rar/KENr9_aj/php_file.html
كلمة المرور فك الضغط : java-ar-android.blogspot.com
و السلام عليكم ورحمة الله وبركاته
في حال وجود اس استفسارات قم بالرد
السلام عليكم ورحمة الله وبركاته
ردحذفممكن توضيح اكتر للجزء ده
public void onClick(View v)
{
String aa=username.getText().toString();
String aa2=pass.getText().toString();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.104/jonsn_android/login.php?username="+aa+"&pass="+aa2+"");
TextView textView = (TextView)findViewById(R.id.textView1);
try {
HttpResponse response = httpclient.execute(httppost);
String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
JSONObject object = new JSONObject(jsonResult);
String name = object.getString("state");
String verion = object.getString("id");
//textView.setText(name + " - " + verion);
int chk=Integer.parseInt(name);
if(chk==1)
{
mesegbox("you are login","success login thank you.");
}
else
{mesegbox("no login","error login please check user name or password ");
}
شكرااااا