Immanuel

Wednesday, February 19, 2014

Install Oracle Java in Ubuntu 13.10

Hello all,

This blog is about installing oracle java in Ubuntu 13.10. Oracle Java is the important run time environment for installing Android Studio and Hadoop end etc.

By default Ubuntu gives open jdk that is good but still i prefer to use oracle java.

Follow the following steps to install

1. Check for java in Ubuntu

dpkg --list | grep -i jdk

2. Add Repository to ubuntu

sudo add-apt-repository ppa:webupd8team/java
 
3. Update list and install oracle JAVA

sudo apt-get update && sudo apt-get install oracle-jdk7-installer

4. Accept the license agreement and enable JDK

update-alternatives --display java
 
5.Check Ubuntu Java Version
java -version
 
If you see this in terminal then all works good
 
java version “1.7.0_25″
Java(TM) SE Runtime Environment (build 1.7.0_25-b15)
Java HotSpot(TM) Server VM (build 23.3-b01, mixed mode)
 
6.Check  Java  Compiler Version
 
javac -version
It should show something like this
javac 1.7.0_25
.
7. Add JAVA_HOME to environment variable

Edit /etc/environment and add JAVA_HOME=/usr/lib/jvm/java-7-oracle to the end of the file
sudo nano /etc/environment
 
8. Append to the end of the file
JAVA_HOME=/usr/lib/jvm/java-7-oracle
 
Happy Hacking:) 
 
  

Tuesday, February 4, 2014

Android Web login Using JSON Example

Logging in to the web site in android mobile can be achieved by loading the entire page in Web view but this has lots of drawbacks
1. Your web site should be mobile compatibility and more responsive
2. Network bandwidth
3. Time delay

This can be overcome by using the HttpClient and JSON in Android.

We are about to create a native android application that will have a login and register form which is used to login / register the user to the website that is running PHP (You  can your any other also) in internet.
JSON (Java Script Object Notation) is the intermediate data transfer agent between web server and Android Mobile

Pre-requestion 
1. Android Development Environment in your system
            Refer:http://arunimmanuel.blogspot.in/2012/07/installing-android-in-windows.html
            (or)
            Download latest Android studio from google  http://developer.android.com/sdk/installing/studio.html
2. Web site with PHP, MYSQL which give JSON array output.

Steps to be followed
Create a Signup page in Web server named signup.html



Sign Up


User Name:

Password:



Then create signup.php
$Uname = $_POST["txtUname"];
$Pass = $_POST["txtPass"];
$con=mysqli_connect("YOUR_HOST","YOUR_USERNAME","YOUR_PASS","YOUR_DB");
// Check connection
if (mysqli_connect_errno())
{
$response["success"] = 0;
 $response["message"] = "Database Error!";
die(json_encode($response));
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
try{

mysqli_query($con,"INSERT INTO login VALUES ('$Uname','$Pass')");
$response["success"] = 1;
 $response["message"] = "Registration successful!";
die(json_encode($response));
}
catch(Exception $e){
$response["success"] = 0;
 $response["message"] = "Cannot Add";
die(json_encode($response));
}
mysqli_close($con);

?>


Create login page login.html




User Name:


Password:



Create login.php

$Uname = $_POST["txtUName"];
$Pass = $_POST["txtPass"];

$con=mysqli_connect("YOUR_HOST","YOUR_USERNAME","YOUR_PASS","YOUR_DB");// Check connection
if (mysqli_connect_errno())
  {
$response["success"] = 0;
 $response["message"] = "Database Error!";
die(json_encode($response));
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$result = mysqli_query($con,"SELECT * FROM login where UName='$Uname' AND Pass='$Pass'");

while($row = mysqli_fetch_array($result))
  {
$response["success"] = 1;
 $response["message"] = "Login successful!";
die(json_encode($response));
header("Location: home.php");
  }

mysqli_close($con);
?>


Now create a new Android Project

My MainActivity is renamed to Login

Create login.xml

Code for login.xml

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
   >

   


Create register.xml

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
   >

            android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/password"
        android:layout_centerVertical="true"
        android:text="Username" />

            android:id="@+id/username"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:ems="10" />

            android:id="@+id/TextView01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/username"
        android:layout_below="@+id/username"
        android:text="Password" />

            android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="16dp"
        android:gravity="center"
        android:text="Android Remote Server Tutorial"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textStyle="bold" />

            android:id="@+id/password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/TextView01"
        android:layout_centerHorizontal="true"
        android:ems="10"
        android:inputType="textPassword" />

   


Now inflate these activity and views in respective Java files

I have Login.java and Register.java

Login.java

package com.android.json.login;

import java.util.ArrayList;
import java.util.List;

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

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

public class Login extends Activity implements OnClickListener{
   
    private EditText user, pass;
    private Button mSubmit, mRegister;
   
     // Progress Dialog
    private ProgressDialog pDialog;

    // JSON parser class
    JSONParser jsonParser = new JSONParser();
   
    //php login script location:
   
    //localhost : 
    //testing on your device
    //put your local ip instead,  on windows, run CMD > ipconfig
    //or in mac's terminal type ifconfig and look for the ip under en0 or en1
   // private static final String LOGIN_URL = "http://xxx.xxx.x.x:1234/webservice/login.php";
   
    //testing on Emulator:
    private static final String LOGIN_URL = "http://arunimmanuel.000space.com/Social/login.php";
   
  //testing from a real server:
    //private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/login.php";
   
    //JSON element ids from repsonse of php script:
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
       
        //setup input fields
        user = (EditText)findViewById(R.id.username);
        pass = (EditText)findViewById(R.id.password);
       
        //setup buttons
        mSubmit = (Button)findViewById(R.id.login);
        mRegister = (Button)findViewById(R.id.register);
       
        //register listeners
        mSubmit.setOnClickListener(this);
        mRegister.setOnClickListener(this);
       
    }

    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.login:
                new AttemptLogin().execute();
            break;
        case R.id.register:
                Intent i = new Intent(this, Register.class);
                startActivity(i);
            break;

        default:
            break;
        }
    }
   
    class AttemptLogin extends AsyncTask {

         /**
         * Before starting background thread Show Progress Dialog
         * */
        boolean failure = false;
       
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Login.this);
            pDialog.setMessage("Attempting login...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
       
        @Override
        protected String doInBackground(String... args) {
            // TODO Auto-generated method stub
             // Check for success tag
            int success;
            String username = user.getText().toString();
            String password = pass.getText().toString();
            try {
                // Building Parameters
                List params = new ArrayList();
                params.add(new BasicNameValuePair("txtUName", username));
                params.add(new BasicNameValuePair("txtPass", password));

                Log.d("request!", "starting");
                // getting product details by making HTTP request
                JSONObject json = jsonParser.makeHttpRequest(
                       LOGIN_URL, "POST", params);

                // check your log for json response
                Log.d("Login attempt", json.toString());

                // json success tag
                success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    Log.d("Login Successful!", json.toString());
                    Intent i = new Intent(Login.this, Home.class);
                    finish();
                    startActivity(i);
                    return json.getString(TAG_MESSAGE);
                }else{
                    Log.d("Login Failure!", json.getString(TAG_MESSAGE));
                    return json.getString(TAG_MESSAGE);     
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
           return null; 
        }
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once product deleted
            pDialog.dismiss();
            if (file_url != null){
                Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
            }
        }     
    }
 }


Register.java

package com.android.json.login;

import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Register extends Activity implements OnClickListener{
   
    private EditText user, pass;
    private Button  mRegister;
   
     // Progress Dialog
    private ProgressDialog pDialog;

    // JSON parser class
    JSONParser jsonParser = new JSONParser();
   
    //php login script
   
    //localhost : 
    //testing on your device
    //put your local ip instead,  on windows, run CMD > ipconfig
    //or in mac's terminal type ifconfig and look for the ip under en0 or en1
   // private static final String LOGIN_URL = "http://xxx.xxx.x.x:1234/webservice/register.php";
   
    //testing on Emulator:
    private static final String LOGIN_URL = "http://arunimmanuel.000space.com/Social/signup.php";
   
  //testing from a real server:
    //private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/register.php";
   
    //ids
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);
       
        user = (EditText)findViewById(R.id.username);
        pass = (EditText)findViewById(R.id.password);
       

        mRegister = (Button)findViewById(R.id.register);
        mRegister.setOnClickListener(this);
       
    }


    public void onClick(View v) {
        // TODO Auto-generated method stub
       
                new CreateUser().execute();
       
    }
   
    class CreateUser extends AsyncTask {

         /**
         * Before starting background thread Show Progress Dialog
         * */
        boolean failure = false;
       
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Register.this);
            pDialog.setMessage("Creating User...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
       
        @Override
        protected String doInBackground(String... args) {
            // TODO Auto-generated method stub
             // Check for success tag
            int success;
            String username = user.getText().toString();
            String password = pass.getText().toString();
            try {
                // Building Parameters
                List params = new ArrayList();
                params.add(new BasicNameValuePair("txtUname", username));
                params.add(new BasicNameValuePair("txtPass", password));

                Log.d("request!", "starting");
               
                //Posting user data to script
                JSONObject json = jsonParser.makeHttpRequest(
                       LOGIN_URL, "POST", params);

                // full json response
                Log.d("Login attempt", json.toString());

                // json success element
                success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    Log.d("User Created!", json.toString());                 
                    finish();
                    return json.getString(TAG_MESSAGE);
                }else{
                    Log.d("Login Failure!", json.getString(TAG_MESSAGE));
                    return json.getString(TAG_MESSAGE);
                   
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
           
        }
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once product deleted
            pDialog.dismiss();
            if (file_url != null){
                Toast.makeText(Register.this, file_url, Toast.LENGTH_LONG).show();
            }

        }
       
    }
  }


We need JSON parser class to parse the JSON response
JSONParser.java

package com.android.json.login;

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() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List 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;

    }
}

Now update the Manifest
1. Permission to Access Internet
2. Add new Activity to Manifest

AndroidManifest.xml



            android:name = ".Register"/>
                    android:name=".Home"/>


Download Source code from GitHub : https://github.com/arunimmanuelpro/Android-JSON
Happy Hacking :)

Sunday, February 2, 2014

Getting Started with Git in Eclipse

Hello Every one after long time i am posting this post, this will explain how simply you can use GIT(Version Control System) for your projects on Eclipse.
Pre request
1. Eclipse
2. Account on https://github.com

First i will push my android project into github repository
1. Log into your github

2. Click on "New Repository" in your dashboard which is found in bottom right


3. Enter the Name of your repository, i have entered as "Sample" and click on "Create Repository"


4. After creating the repository you can see the repository page, now click on http and copy the URL as shown below


Now we have created the repository in github and we have to create the Android project in eclipse

5. Right Click on the Android Project ->Team -> Share Project


6. Set Git in a Dialog that appear, ignore Warning just click OK and Click on Next

7. For the first time you have to create a local repository click on create and enter the name and click finish


8. Check the repository name and click finish


9. Now commit your code to the local repository Right Click on the project ->Team ->Commit



10. Authorize yourself with username and email address of git


11. Now a new screen will appear enter the comit message and select the files that want to be commited and click Commit


12. Now we will push this to the remote git Right Click on project title -> Team -> Remote->Push


13. Enter the username and password of the git and Click Next





14. Wait for a minute and Click Finish


15. Go to github site and refresh your repository page you can see the android folder and its content is added to the repository.


Hope this one will help.Happy hacking :)

Twitter Bird Gadget