[Android] Login logout dengan Android MySQL

Jadi ceritanya, malem-malem ane lagi ngerjain project buat skripsweet, di project itu ada fitur login logutnya alias session setelah browsing akhirnya ketemu juga tutorialnya.. dan alangkah indahnya jika mau membagi, langsung aja dah.

pertama, jelas kita bikin database dulu, pada contoh postingan ini nama databasenya login dan nama tabelnya user, seperti ini

setelah itu bikin file 3 PHP dengan nama koneksi.php, login.php dan register.php

edit file koneksi.php ,lalu isi kan kode berikut:

<?php
mysql_connect("localhost","root","");
mysql_select_db("login");
?>

lalu file login.php, dengan kode berikut

<?php
include "koneksi.php";

$email    = $_GET["email"];
$password = $_GET["password"];

$query = "select * from user where email='$email' and password='$password' ";

$hasil = mysql_query($query);
if (mysql_num_rows($hasil) > 0) {
$response = array();
$response["login"] = array();
while ($data = mysql_fetch_array($hasil))
{
$h['id']    		= $data['id'] ;
$h['nama']  		= $data['nama'] ;
$h['email']  	    = $data['email'] ;
$h['password']      = $data['password'];

 array_push($response["login"], $h);
}
	$response["success"] = "1";
	echo json_encode($response);
}
else {
    $response["success"] = "0";
    $response["message"] = "Tidak ada data";
	echo json_encode($response);
}
?>

file register.php, dan editlah seperti ini

<?php

$nama=$_POST['nama'];
$email = $_POST['email'];
$password=$_POST['password'];

include "koneksi.php";

$query = "INSERT INTO user (nama,email,password)VALUES('$nama','$email','$password')";
$hasil = mysql_query($query);
if($hasil)
	{
	$response["success"] = "1";
        $response["message"] = "Data sukses diinput";
        echo json_encode($response);
	}
	else
	{$response["success"] = "0";
     $response["message"] = "Maaf , terjadi kesalahan";

        // echoing JSON response
        echo json_encode($response);
	}
?>

untuk bagian PHP mysql nya sudah selesai, lalu masuk ke androidnya, bikin dulu project androidnya, udah tau dong caranya..

pertama bikin class baru yang sebut saja SessionManager.java, nah file sessionmanager ini berfungsi seperti session pada web, berikut source codenya

package com.example.logreg;

import java.util.HashMap;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

@SuppressLint("CommitPrefEdits")
public class SessionManager {
	// Shared Preferences
	SharedPreferences pref;

	// Editor for Shared preferences
	Editor editor;

	// Context
	Context _context;

	// Shared pref mode
	int PRIVATE_MODE = 0;

	// nama sharepreference
	private static final String PREF_NAME = "Sesi";

	// All Shared Preferences Keys
	private static final String IS_LOGIN = "IsLoggedIn";
	public static final String KEY_NAME = "nama";
	public static final String KEY_EMAIL = "email";

	// Constructor
	public SessionManager(Context context){
		this._context = context;
		pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
		editor = pref.edit();
	}

	/**
	 * Create login session
	 * */
	public void createLoginSession(String name, String email){
		// Storing login value as TRUE
		editor.putBoolean(IS_LOGIN, true);

		editor.putString(KEY_NAME, name);
		editor.putString(KEY_EMAIL, email);
		editor.commit();
	}	

	/**
	 * Check login method wil check user login status
	 * If false it will redirect user to login page
	 * Else won't do anything
	 * */
	public void checkLogin(){
		// Check login status
		if(!this.isLoggedIn()){
			Intent i = new Intent(_context, MainActivity.class);
			i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			_context.startActivity(i);
			//((Activity)_context).finish();
		}

	}

	/**
	 * Get stored session data
	 * */
	public HashMap<String, String> getUserDetails(){
		HashMap<String, String> user = new HashMap<String, String>();

		user.put(KEY_NAME, pref.getString(KEY_NAME, null));
		user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));

		return user;
	}

	/**
	 * Clear session details
	 * */
	public void logoutUser(){
		// Clearing all data from Shared Preferences
		editor.clear();
		editor.commit();

		Intent i = new Intent(_context, MainActivity.class);
		i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		_context.startActivity(i);
	}

	public boolean isLoggedIn(){
		return pref.getBoolean(IS_LOGIN, false);
	}
}

berhubung, project ini menggunakan PHP mysql, biasanya kita membutuhkan JSON parser, nah makanya kita bikin class baru yang namanya JSONParser.java, berikut source codenya

package com.example.logreg;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

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.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

	static InputStream is = null;
	static JSONObject jObj = null;
	static String json = "";

	// constructor
	public JSONParser() {

	}

	public JSONObject getJSONFromUrl(String url) {

		// Making HTTP request
		try {
			// defaultHttpClient
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(url);

			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			is = httpEntity.getContent();

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			json = sb.toString();
		} catch (Exception e) {
			Log.e("Buffer Error", "Error converting result " + e.toString());
		}

		// try parse the string to a JSON object
		try {
			jObj = new JSONObject(json);
		} catch (JSONException e) {
			Log.e("JSON Parser", "Error parsing data " + e.toString());
		}

		// return JSON String
		return jObj;

	}

	public JSONObject makeHttpRequest(String url, String method,
			List<NameValuePair> params) {

		// Making HTTP request
		try {

			// check for request method
			if (method == "POST") {
				// request method is POST
				// defaultHttpClient
				DefaultHttpClient httpClient = new DefaultHttpClient();
				HttpPost httpPost = new HttpPost(url);
				httpPost.setEntity(new UrlEncodedFormEntity(params));

				HttpResponse httpResponse = httpClient.execute(httpPost);
				HttpEntity httpEntity = httpResponse.getEntity();
				is = httpEntity.getContent();

			} else if (method == "GET") {
				// request method is GET
				DefaultHttpClient httpClient = new DefaultHttpClient();
				String paramString = URLEncodedUtils.format(params, "utf-8");
				url += "?" + paramString;
				HttpGet httpGet = new HttpGet(url);

				HttpResponse httpResponse = httpClient.execute(httpGet);
				HttpEntity httpEntity = httpResponse.getEntity();
				is = httpEntity.getContent();
			}

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			json = sb.toString();
		} catch (Exception e) {
			Log.e("Buffer Error", "Error converting result " + e.toString());
		}

		// try parse the string to a JSON object
		try {
			jObj = new JSONObject(json);
		} catch (JSONException e) {
			Log.e("JSON Parser", "Error parsing data " + e.toString());
		}

		// return JSON String
		return jObj;

	}
}

ketika tadi bikin project android, editlah file actitity_main.xml, yang ada folder res->layout, edit kayak gini

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbarStyle="insideInset" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical" >

            <EditText
                android:id="@+id/email"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="10dp"
                android:hint="email"
                android:paddingRight="10dp" />

            <EditText
                android:id="@+id/password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="10dp"
                android:hint="insert password"
                android:inputType="textPassword"
                android:paddingRight="10dp" />

            <Button
                android:id="@+id/login"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="10dp"
                android:paddingRight="10dp"
                android:text="Login" />

            <Button
                android:id="@+id/daftar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="50dp"
                android:paddingRight="10dp"
                android:text="Register" />
        </LinearLayout>
    </ScrollView>

</LinearLayout>

nah, kalo udah edit juga mainactivity.java nya, edit kayak gini

package com.example.logreg;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
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 MainActivity extends Activity  {

	Button daftar, login;
	Intent a;
	EditText email, password;
	String url, success;
	SessionManager session;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		session = new SessionManager(getApplicationContext());
		Toast.makeText(getApplicationContext(),
				"User Login Status: " + session.isLoggedIn(), Toast.LENGTH_LONG)
				.show();

		daftar = (Button) findViewById(R.id.daftar);
		login = (Button) findViewById(R.id.login);
		email = (EditText) findViewById(R.id.email);
		password = (EditText) findViewById(R.id.password);

		daftar.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View arg0) {
				Intent daftar = new Intent(MainActivity.this, Register.class);
				startActivity(daftar);

			}
		});

		login.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				url = "http://10.0.2.2/login/login.php?" + "email="
						+ email.getText().toString() + "&password="
						+ password.getText().toString();

				if (email.getText().toString().trim().length() > 0
						&& password.getText().toString().trim().length() > 0) 
				{
					new Masuk().execute();
				} 
				else 
				{
					Toast.makeText(getApplicationContext(), "Username/password masih kosong gan.!!", Toast.LENGTH_LONG).show();
				}
			}
		});
	}

	public class Masuk extends AsyncTask<String, String, String> 
	{
		ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
		ProgressDialog pDialog;

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();

			pDialog = new ProgressDialog(MainActivity.this);
			pDialog.setMessage("Tunggu Bentar ya...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(true);
			pDialog.show();
		}
		@Override
		protected String doInBackground(String... arg0) {
			JSONParser jParser = new JSONParser();

			JSONObject json = jParser.getJSONFromUrl(url);

			try {
				success = json.getString("success");

				Log.e("error", "nilai sukses=" + success);

				JSONArray hasil = json.getJSONArray("login");

				if (success.equals("1")) {

					for (int i = 0; i < hasil.length(); i++) {

						JSONObject c = hasil.getJSONObject(i);

						String nama = c.getString("nama").trim();
						String email = c.getString("email").trim();
						session.createLoginSession(nama, email);
						Log.e("ok", " ambil data");

					}
				} else {
					Log.e("erro", "tidak bisa ambil data 0");
				}

			} catch (Exception e) {
				// TODO: handle exception
				Log.e("erro", "tidak bisa ambil data 1");
			}

			return null;

		}
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			pDialog.dismiss();
			if (success.equals("1")) {
				a = new Intent(MainActivity.this, MyAccount.class);
				startActivity(a);
				finish();
			} else {

				Toast.makeText(getApplicationContext(), "Username/password salah gan.!!", Toast.LENGTH_LONG).show();
			}

		}

	}

}

nah abis itu bikin activity baru, isikan Activity name nya dengan nama Register, sedangkan untuk layout namenya kasih nama activity_register, tinggal finish deh.

edit file activity_register.xml seperti ini;

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbarStyle="insideInset" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical" >

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:gravity="center_horizontal"
                android:paddingLeft="10dp"
                android:text="Pendaftaran"
                android:textSize="25sp" />

            <EditText
                android:id="@+id/email"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="10dp"
                android:hint="email"
                android:paddingRight="10dp" />

            <EditText
                android:id="@+id/password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="10dp"
                android:hint="password"
                android:inputType="textPassword"
                android:paddingRight="10dp" />

            <EditText
                android:id="@+id/nama"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="10dp"
                android:hint="nama"
                android:paddingRight="10dp" />

            <Button
                android:id="@+id/daftar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="10dp"
                android:paddingRight="10dp"
                android:text="Daftar" />

            <TextView
                android:id="@+id/keterangan"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="13dp"
                android:text="Isilah semua inputan"
                android:textColor="#aa0000" />
        </LinearLayout>
    </ScrollView>

</LinearLayout>

kalo untuk file Register.java nya kayak gini;

package com.example.logreg;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Register extends Activity {

	ProgressDialog pDialog;

	JSONParser jsonParser = new JSONParser();
	EditText email, password,nama; 
	Button daftar;
	private static String url = "http://10.0.2.2/login/Register.php";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);

		email 	=(EditText)findViewById(R.id.email);
		password=(EditText)findViewById(R.id.password);
		nama	=(EditText)findViewById(R.id.nama);
		daftar = (Button)findViewById(R.id.daftar);
		final EmailValidator emailValid = new EmailValidator();
		daftar.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				if(!emailValid.validate(email.getText().toString()))
				{
					Toast.makeText(Register.this, "Emailnya ga valid", Toast.LENGTH_LONG).show();
					email.setText("");
				}
				else
				{
					new daftarAku().execute();
				}

			}
		});
	}

	public class daftarAku extends AsyncTask<String, String, String>
	{

		String success;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(Register.this);
			pDialog.setMessage("Proses mendaftar...");
			pDialog.setIndeterminate(false);
			pDialog.show();
		}

		@Override
		protected String doInBackground(String... params) {

			String strnama 		= nama.getText().toString();
			String stremail		= email.getText().toString();
			String strpassword	= password.getText().toString();

			List<NameValuePair> nvp = new ArrayList<NameValuePair>();
			nvp.add(new BasicNameValuePair("nama", strnama));
			nvp.add(new BasicNameValuePair("email", stremail));
			nvp.add(new BasicNameValuePair("password", strpassword));

			JSONObject json = jsonParser.makeHttpRequest(url, "POST", nvp);
			try { 
				success = json.getString("success");

			} catch (Exception e) {
				Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();
			}

			return null;
		}

		protected void onPostExecute(String file_url) {
			// dismiss the dialog once done
			pDialog.dismiss();

			if (success.equals("1")) {
			    Toast.makeText(getApplicationContext(), "Regitrasi sukses", Toast.LENGTH_LONG).show();

			} else {
				Toast.makeText(getApplicationContext(), "Registrasi gagal", Toast.LENGTH_LONG).show();
			}
		}

	}
	public class EmailValidator{

	  	  private Pattern pattern;
	  	  private Matcher matcher;

	  	  private static final String EMAIL_PATTERN = 
	                     "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

	  	  public EmailValidator()
	  	  {
	  		  pattern = Pattern.compile(EMAIL_PATTERN);
	  	  }

	  	  public boolean validate(final String hex)
	  	  {
	  		  matcher = pattern.matcher(hex);
	  		  return matcher.matches();  
	  	  }
	  }

}

kalo udah bikin activity baru lagi activity namenya di kasih nama MyAccount ,dan layoutnya dikasih nama activity_myAccount, edit file activity_myAccount.xml seperti ini:

<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MyAccount" >

    <TextView
        android:id="@+id/status"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:gravity="center_horizontal"
        android:paddingLeft="10dp"
        android:text="Hallo"
        android:textSize="25sp" />

    <Button
        android:id="@+id/logout"
        android:layout_width="fill_parent"
        android:layout_height="45dp"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="126dp" 
        android:text="Logout"/>

</RelativeLayout>

nah, untuk file MyAccount.java edit seperti ini;

package com.example.logreg;

import java.util.HashMap;

import org.json.JSONArray;
import android.os.Bundle;
import android.app.Activity;
import android.text.Html;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MyAccount extends Activity {

	Button logout;
	SessionManager session;
	TextView status;
	JSONArray contacts = null;
	String email, nama, id;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_my_account);

		session = new SessionManager(getApplicationContext());
		Toast.makeText(getApplicationContext(),
				"User Login Status: " + session.isLoggedIn(), Toast.LENGTH_LONG)
				.show();

		session.checkLogin();

		HashMap<String, String> user = session.getUserDetails();

		nama = user.get(SessionManager.KEY_NAME);
		// id = user.get(SessionManager.KEY_ID);

		TextView status = (TextView) findViewById(R.id.status);
		status.setText(Html.fromHtml("Welcome,<b>" + nama + "</b>  "));

		logout = (Button) findViewById(R.id.logout);

		logout.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				session.logoutUser();
				finish();
			}
		});
	}

}

jangan lupa menambahkan uses permission internet di androidmanifestnya
nah, kelar deh, kalo bener pasti hasilnya gini

Registrasi

Login

MyAccount

download projectnya di sini

sekian, semoga bermanfaat

 

Referensi http://www.androidhive.info/2012/08/android-session-management-using-shared-preferences/

38 thoughts on “[Android] Login logout dengan Android MySQL

      • coba dilihat logcatnya, kalo errornya illegal karakter yang disebabkan karakter spasi(%20) mungkin bisa ditambah kan code seperti ini contohnya

        String mail = email.getText().toString();
        String pass = password.getText().toString();

        String theEmail = mail.replace(” “, “%20″);
        String thePass = pass.replace(” “, “%20″);

        url = “http://pakardemam.besaba.com/login/login.php?” + “email=”
        + theEmail+ “&password=”+ thePass;

  1. capek cari kemana mana ribet semua.
    eh… di Adi Hidayat.com gak pakek ribet sourcode nya.
    semoga tugas akhir gua selesai.
    arigato Adi Hidayat.com

  2. Mas Adi yang baik hati saya sudah ikuti semua setting nya tapi kok sya gagal register ya, data masuk di sql tapi kosong nama,email, dan passnya apa yang salah ya? Need Help

    Trims

    • Kemungkinan di bagian ini

      nvp.add(new BasicNameValuePair(“nama”, strnama));
      nvp.add(new BasicNameValuePair(“email”, stremail));
      nvp.add(new BasicNameValuePair(“password”, strpassword));

      yang didalam tanda petik(“”), itu harus sama seperti di tabel database, case sensitive

    • coba di rubah

      String mail = email.getText().toString();
      String pass = password.getText().toString();

      String theEmail = mail.replace(” “, “%20″);
      String thePass = pass.replace(” “, “%20″);

      url = “http://10.0.2.2/login/login.php?” + “email=”
      + theEmail+ “&password=”+ thePass;

  3. kak saya mau tanya. kok pas di run di android muncul tulisan “Sayangnya aplikasi telah berhenti” ya? itu kenapa kak? minta solusinya ya kak. maklum, masih baru.. :)

  4. gan, punya ane gag isa dpake. .
    padahal uda ane donlod punya agan. . .
    d local host nya uda bener, trus d hapenya gmana caranya. . ?
    trus pake seting ip gag gan. . .?
    punya ane force closed soalnya. . .

    • kalo masih eror kemungikan
      1. permission internet belum ditambahkan ke android manifest
      2. url encodernya, karater spasi diganti dengan %20, caranya;

      String mail = email.getText().toString();
      String pass = password.getText().toString();

      String theEmail = mail.replace(” “, “%20″);
      String thePass = pass.replace(” “, “%20″);
      url = “http://10.0.2.2/login/login.php?” + “email=”+ theEmail+ “&password=”+ thePass;

      if (email.getText().toString().trim().length() > 0
      && password.getText().toString().trim().length() > 0)
      {
      new Masuk().execute();
      }
      else
      {
      Toast.makeText(getApplicationContext(), “Username/password masih kosong gan.!!”, Toast.LENGTH_LONG).show();
      }

      kalo ane ga pake seting IP, langsung ke hosting, tapi untuk tutorial pake localhost

  5. kok ane kagak bisa terkoneksi ya gan?? kagak ada yang eror, manifestnya udah ane tambahin permission internetnye. trus klo udah proses login, loading bentar terus force close…knpe tu ya gan…
    oh iya ane nge-runnya kagak pake emulator. paham lah ente maksud ane… makasih gan

  6. I see a lot of interesting articles on your page.

    You have to spend a lot of time writing, i know how to save you a lot of work, there is a tool that creates unique, google friendly posts in couple of seconds, just search in google – laranita’s
    free content source

  7. mau tanya mas, bisa ngasih solusi gak,
    kalu udah login terus setelah login itu terhubung sama webservice ku gimana caranya yaa?
    makasih, mohon bantuannya

  8. kak mau nny nh, kalau mau buat login dengan tabel log, jadi biar user yg udah login di kodekan 1 dan user yang udah logout di kodekan 0 pada statusnya. biar logout bisa membailkkan angka 1 menjadi 0 itu gimana ya ka. mohon bantuannya ya ka.

  9. kalo errornya seperti ini kenapa gan?

    The method makeHttpRequest(String, String, List) is undefined for the type JSONParser

  10. gan sya udh hosting ke web. login dan register udh brhasil tp pas nampilan info myaccount ga bsa gan. ada kterangan “hallo bro, null”. itu kenapa gan ?

  11. Halo mas, saya sudah coba aplikasi yang di suguhkan diatas, saya coba jalan semua, yang mau saya tanyakan,
    gimana caranya supaya ketika user sudah berhasil login, si user tidak perlu login lagi walaupun devicenya restart/mati.

    sewaktu berhasil login muncul “status login true/false”, harusnya kan pada saat status false, user diarahkan ke halaman login, dan ketika true harusnya langsung ke Myaccount.class.

    tolong solusinya mas jika berkenan mohon kirim kan jawabannya ke valefor.me15@gmail.com, need fast reply
    terimakasih sebelumnya,

    salam.

    • Hai, saya pun dapat masalah yang sama. Awak ada jalan penyelesaiannya tak ? Boleh kongsi dengan saye ? terima kasih :)

  12. kenapa ya saya pas login force closed ,,
    sudah disesuaikan dengan petunjuk diatas tapi masih force close

  13. THank gan soucecode nya .. dah working d ane tinggal code buat select insert sama update nya gmn gan ? help me pliss

  14. Assalamualaikum,

    Terima kasih tutorial di atas. Sangat berguna untuk projek saya. Tapi ade satu persoalan. Macam mana saya nak kekalkan apps terus mengekalkan user dalam apps selagi mereka belum logout. Kerana apabila saya tutup dan buka semula apps, user akan ke halaman login dan user harus log masuk semula. Harap awak dapat membantu, terima kasih :)

  15. terima kasih gan sebelumnya, ini saya mau nanya kenapa ya pada parameter dan
    (BasicNameValuePair) tidak ada di saya di kodingan

    List nvp = new ArrayList();
    nvp.add(new BasicNameValuePair(“nama”, strnama));
    nvp.add(new BasicNameValuePair(“email”, stremail));
    nvp.add(new BasicNameValuePair(“password”, strpassword));

    JSONObject json = jsonParser.makeHttpRequest(url, “POST”, nvp);?

    tolong solusinya gan..
    terima kasih

Leave a Reply to jonawar Cancel reply

Your email address will not be published. Required fields are marked *


1 + = 4

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>