Thursday, May 1, 2014

Simple HTTP requests (GET & POST)

Let us see a Login Request, It also contains Shared-preference usage.

LoginActivity 

package com.example.testapp;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends Activity {

Dialog dialog;
Button bLogin, bCreateAccount;
EditText etUsername, etPassword;

Intent nextActivity;

//ArrayList<NameValuePair> nameValuePairs;  //to add Parameters to POST method

private SharedPreferences loginAndProfileSharedPref;

String username = null, password = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE); // Removes title bar

setContentView(R.layout.login_activity);

bLogin = (Button) findViewById(R.id.login);
etUsername = (EditText) findViewById(R.id.username);
etPassword = (EditText) findViewById(R.id.password);
bCreateAccount = (Button) findViewById(R.id.register);

bCreateAccount.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
nextActivity = new Intent(LoginActivity.this,
RegistrationActivity.class);
startActivity(nextActivity);
}
});

bLogin.setOnClickListener(new OnClickListener() {

public void onClick(View arg0) {
// TODO Auto-generated method stub
if ((etUsername.length() >= 0) && (etPassword.length() > 0)) {

username = etUsername.getText().toString().trim();
password = etPassword.getText().toString();

/* //to send data in POST method
nameValuePairs.add(new BasicNameValuePair("username",
username));
nameValuePairs.add(new BasicNameValuePair("password",
password));*/

new LoginCheck().execute();

} else {
if ((etUsername.length() <= 0)) {
etUsername.setError("enter username");
} else if ((etPassword.length() <= 0)) {
etPassword.setError("enter password");
}
}
}
});

}

protected class LoginCheck extends AsyncTask<Void, Void, Void> {

String response = null;
ProgressDialog pd;

protected void onPreExecute() {

pd = ProgressDialog.show(LoginActivity.this, "Login Checking",
"Please Wait");

pd.setCancelable(true);
}

@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
// GET method
response = CustomHttpClient.executeHttpGet(
"http://www.yourdamain.com/userLogin?username="+username+"&password="+password)
.trim();

/* // POST method
response = CustomHttpClient.executeHttpPost(
"http://www.yourdamain.com/userLogin", nameValuePairs)
.trim();*/
//nameValuePairs.clear();

} catch (Exception e) {
// TODO: handle exception
Log.d("Loginpage", e.toString());
}

return null;
}

protected void onPostExecute(Void unused) {

// pd.dismiss();

try {
pd.dismiss();
// Then assign progress Dialog to null
pd = null;

} catch (Exception e) {
e.printStackTrace();
}

if (response != null) {

if (response.equals("wrong username")) {

Toast.makeText(LoginActivity.this,
"enter correct username", 1000).show();

} else if (response.equals("wrong password")) {

Toast.makeText(LoginActivity.this,
"enter correct password", 1000).show();
} else if (response.equals("success")) {
Toast.makeText(LoginActivity.this, "Login succesfull..!!",
1000).show();

loginAndProfileSharedPref = getSharedPreferences("loginAndProfileSharedPref",
MODE_WORLD_WRITEABLE);
Editor ed = loginAndProfileSharedPref.edit();
ed.putBoolean("login", true);
ed.putString("username", username);
ed.commit();

finish();

Intent go = new Intent(LoginActivity.this,
ListActivity.class);
startActivity(go);

} else {
Toast.makeText(LoginActivity.this,
"Something went wrong!! Try again..!!", 1000)
.show();
}
}
}
}
}

login_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="20dp">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="Login Here"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/username"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="15dp"
        android:hint="enter username"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/password"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/username"
        android:layout_below="@+id/username"
        android:layout_marginTop="15dp"
        android:ems="10"
        android:hint="enter password"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/login"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/password"
        android:layout_marginTop="20dp"
        android:text="Login" />

    <Button
        android:id="@+id/register"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/login"
        android:layout_below="@+id/login"
        android:layout_marginTop="50dp"
        android:text="Create Account" />

</RelativeLayout>

In manifest file add this permission,

    <uses-permission android:name="android.permission.INTERNET" />