Thursday, February 11, 2016

Calling Web service in Andriod

Following are the files

Following are the files

1- content_main.xml



    xmlns:app="http://schemas.android.com/apk/res-auto"
    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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.siddhu.myandroidwebservice.MainActivity"
    tools:showIn="@layout/activity_main">

   
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

       
            android:id="@+id/textView1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:gravity="center"
            android:text="Celsius to Farenheit"
            android:textSize="30dp" />

       
            android:id="@+id/editText1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:numeric="integer"
            android:singleLine="true" />

       
            android:id="@+id/button1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:gravity="center"
            android:text="Convert to Farenheit" />

       
            android:id="@+id/tv_result"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="" android:textSize="26dp"/>

   


2- AndroidManifest.xml

Dont forget to add this line before or after ending of application tag.

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



3- build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.example.siddhu.myandroidwebservice"
        minSdkVersion 8
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
    compile files('libs/ksoap2-android-assembly-2.5.8-jar-with-dependencies.jar')
}

4- MainActivity

package com.example.siddhu.myandroidwebservice;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

public class MainActivity extends AppCompatActivity {

    private final String NAMESPACE = "http://www.w3schools.com/xml/";
    private final String URL = "http://www.w3schools.com/xml/tempconvert.asmx";
    private final String SOAP_ACTION = "http://www.w3schools.com/xml/CelsiusToFahrenheit";
    private final String METHOD_NAME = "CelsiusToFahrenheit";
    private String TAG = "PGGURU";
    private static String celcius;
    private static String fahren;
    Button b;
    TextView tv;
    EditText et;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Celcius Edit Control
        et = (EditText) findViewById(R.id.editText1);
        //Fahrenheit Text control
        tv = (TextView) findViewById(R.id.tv_result);
        //Button to trigger web service invocation
        b = (Button) findViewById(R.id.button1);
        //Button Click Listener
        b.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                //Check if Celcius text control is not empty
                if (et.getText().length() != 0 && et.getText().toString() != "") {
                    //Get the text control value
                    celcius = et.getText().toString();
                    //Create instance for AsyncCallWS
                    AsyncCallWS task = new AsyncCallWS();
                    //Call execute
                    task.execute();
                    //If text control is empty
                } else {
                    tv.setText("Please enter Celcius");
                }
            }
        });
    }

    private class AsyncCallWS extends AsyncTask {
        @Override
        protected Void doInBackground(String... params) {
            Log.i(TAG, "doInBackground");
            getFahrenheit(celcius);
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            Log.i(TAG, "onPostExecute");
            tv.setText(fahren + "° F");
        }

        @Override
        protected void onPreExecute() {
            Log.i(TAG, "onPreExecute");
            tv.setText("Calculating...");
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            Log.i(TAG, "onProgressUpdate");
        }

    }

    public void getFahrenheit(String celsius) {
        //Create request
        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
        //Property which holds input parameters
        PropertyInfo celsiusPI = new PropertyInfo();
        //Set Name
        celsiusPI.setName("Celsius");
        //Set Value
        celsiusPI.setValue(celsius);
        //Set dataType
        celsiusPI.setType(double.class);
        //Add the property to request object
        request.addProperty(celsiusPI);
        //Create envelope
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        envelope.dotNet = true;
        //Set output SOAP object
        envelope.setOutputSoapObject(request);
        //Create HTTP call object
        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

        try {
            //Invole web service
            androidHttpTransport.call(SOAP_ACTION, envelope);
            //Get the response
            SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
            //Assign it to fahren static variable
            fahren = response.toString();

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}




How to add jar files in class path in Android Studio

step -1-
Keep all the jar files in the libs folder of the projects
File -- > Project Structure
or
Ctr + Alt + Shift + S
Import1
Step -2-
Go to dependencies Tab
Import3
Step -3
click on '+' insert and click on file dependencies and select the files which we want to add in class path
Import2
Step-4 Finally see you will be able to see follwing lines added in
build.gradle
compile files('libs/ksoap2-android-assembly-2.5.8-jar-with-dependencies.jar')

Wednesday, February 10, 2016

Android CRUD using SQLite

SQLite is a opensource SQL database that stores data to a text file on a device and Android has it built in SQLite database implementation.

It supports major RDBMS features.  Concept remains same as we use to do with other database

1- Create DB
2- Give Grant to DB
3- Create Table
5- Get Connection from code
6- Perform CRUD Operation
7- Close Connection

Database - Package which we used in android to do the same is android.database.sqlite.

Step 1-2 : -Database creation and Granting default permission

This can be done using openOrCreateDatabase method
SQLiteDatabase mydb = openOrCreateDatabase("OUR_DB_NAME",MODE_PRIVATE,null);

Step 3 : -Create Table/Inserting/Updating/Fetching

We can use execSQL method to create and exeute sql command like insert/update/delete etc.

mydb.execSQL("CREATE TABLE IF NOT EXISTS Siddhu_Table(Name VARCHAR PRIMARY KEY,Number VARCHAR);");


Fetching

we use Cursor class to fetch data. Cursor class method rawQuery it will return a resultset with the cursor pointing to the table. We can move the cursor forward and retrieve the data.

Cursor resultSet = mydatbase.rawQuery("Select * from Siddhu_Table",null);
resultSet.moveToFirst();
String UName = resultSet.getString(1);
String PWord = resultSet.getString(2);

Please find below code that shows CRUD operation from Android


1- content_main.xml


    xmlns:app="http://schemas.android.com/apk/res-auto"
    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="com.example.siddhu.mydatabaseapplication.MainActivity"
    tools:showIn="@layout/activity_main">


      
            android:id="@+id/nameText1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="textNoSuggestions"
            android:layout_centerVertical="true"
            android:layout_toRightOf="@+id/nameLabel1"
            android:layout_toEndOf="@+id/nameLabel1" 

       
            android:id="@+id/numberText2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/nameText1"
            android:layout_below="@+id/nameText1"
            android:ems="10" 


        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/spinner"
        android:layout_below="@+id/okButton"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"

    
            android:id="@+id/okButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
        android:layout_marginTop="31dp"
            android:text="OK"
        android:layout_below="@+id/numberText2"
        android:layout_alignRight="@+id/nameLabel1"
        android:layout_alignEnd="@+id/nameLabel1" 
    

            android:id="@+id/nameLabel1"
            android:layout_width="210px"
            android:layout_height="70px"
            android:text="Name:"
            android:textSize="15sp"
            android:typeface="serif"
            android:textStyle="italic"
            android:textColor="#001eff"
            android:layout_x="8px"
            android:layout_y="15px"
            android:layout_above="@+id/numberText2"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true">


            android:id="@+id/numberLabel2"
            android:layout_width="210px"
            android:layout_height="70px"
            android:text="Number:"
            android:textSize="15sp"
            android:typeface="serif"
            android:textStyle="italic"
            android:textColor="#0015ff"
            android:layout_x="10px"
            android:layout_y="82px"
            android:layout_above="@+id/okButton"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true">
  
            android:id="@+id/label3"
            android:layout_width="125px"
            android:layout_height="47px"
            android:textSize="15sp"
            android:layout_x="100px"
            android:layout_y="262px"
            android:layout_alignBaseline="@+id/spinner"
            android:layout_alignBottom="@+id/spinner"
            android:layout_toRightOf="@+id/numberLabel2"
            android:layout_alignRight="@+id/numberText2"
            android:layout_alignEnd="@+id/numberText2">


2- MainActivity.java

package com.example.siddhu.mydatabaseapplication;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

public class MainActivity extends Activity

{
    EditText text1,text2;
    TextView label1;
    Button button2;
    Spinner spinner1;
    SQLiteDatabase mydb;
    private static final String[] array = {"ADD", "DELETE", "VIEW", "UPDATE"};
    @Override    public void onCreate(Bundle icicle)
    {
        super.onCreate(icicle);
        setContentView(R.layout.activity_main);
        text1=  (EditText) findViewById(R.id.nameText1);
        text2=  (EditText) findViewById(R.id.numberText2);
        label1 = (TextView) findViewById(R.id.label3);
        button2 = (Button) findViewById(R.id.okButton);
        spinner1 = (Spinner) findViewById  (R.id.spinner);
        ArrayAdapter   adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, array);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner1.setAdapter(adapter);
        button2.setOnClickListener(new clicker());
        try        {
            mydb = this.openOrCreateDatabase("Siddhu.db", MODE_PRIVATE, null);
            //mydb = this.openDatabase("mydb", null);            mydb.execSQL("CREATE TABLE IF NOT EXISTS Siddhu_Table (Name VARCHAR PRIMARY KEY,Number VARCHAR);");
        }catch(Exception e){text2.setText("Here comes the exception :::"+e);}
    } //--------------------------------------------------    class clicker implements Button.OnClickListener
    {
        public void onClick(View v)
        {
            Cursor c;
            String s = (String) spinner1.getSelectedItem();
            Object ob1 = text1.getText();
            Object ob2 = text2.getText();
            try            {
                if(s.equals("ADD"))                 {
                    mydb.execSQL("INSERT INTO Siddhu_Table (Name,Number) values ('"+ob1+"','"+ob2+"');");
                    label1.setText("ADDED");
                }
                else                if(s.equals("DELETE"))
                {                     mydb.execSQL("DELETE FROM Siddhu_Table WHERE Name='"+ob1+"';");

                    label1.setText("DELETED");
                }
                else if(s.equals("UPDATE"))
                {
                    mydb.execSQL("UPDATE Siddhu_Table  SET Number='"+ob2+"' WHERE Name='"+ob1+"';");
                    label1.setText("UPDATED");
                }
                else                {
                    c = mydb.rawQuery("SELECT * FROM Siddhu_Table WHERE Name='"+ob1+"';",null);
                    c.moveToFirst();
                        int n = c.getColumnIndex("Number");
                        String s1 = c.getString(n);
                        text2.setText(s1);
                        label1.setText("SHOWING…");
                  }
            }catch(Exception e){text2.setText(""+e);}
        }
    } //------------------------------------------------------}







Step to connect to Sqlite3 via ADB Shell

1- Go to your platform-tools folder in a command prompt

C:\Users\myDocument\AppData\Local\Android\sdk\platform-tools

2- Enter the command adb devices to get the list of your devices
List of devices attached
emulator-5554   device

3- Connect a shell to your device:

adb -s emulator-5554 shell


4- Navigate to the folder containing your db file:
Note: If you did not have databases folder create it using mkdkir databases

cd data/data/com.example.siddhu.addition/databases/

5- run sqlite3 to connect to your db:

sqlite3 Siddhu.db

6- run sqlite3 commands that you like eg:

Select * from table1 where ...;


To know where sqlite database stored created by you in android studio, you need to follow simple steps:

1.Run your application
2.Go to Tools--->Android---->Device Monitor
3.Find your application name in left panel
4.Then click on File Explorer tab
5.Select data folder
6.Select data folder again and find your app or module name
7.Click on your  database name
8.On right-top window you have an option to pull file from device.
9.Click it and save it on your PC
10.Use FireFox Sqlite manager or sqllite Studio software to open that file

http://sqlitestudio.pl/?act=download

http://www.c-sharpcorner.com/UploadFile/e14021/know-where-database-is-stored-in-android-studio/

Tuesday, February 09, 2016

Addition/Substraction of two value in Android using Android Studio

There are Four main files in android when we create application using Android studio
1- AndroidManifest
2- MainActivity
3- activity_main.xml
4- content_main.xml

Lets try to digout one by one

1- AndroidManifest

This is the main file which contain information such as application label and its activity associated with it. Activity label will be displayed on the screen.
This file also shows our main java class which is going to be executed when user perform any even on the screen. i.e for us it is MainActivity



android:allowBackup=”true”
android:icon=”@mipmap/ic_launcher”
android:label=”TestAddition1?
android:supportsRtl=”true”
android:theme=”@style/AppTheme”>

android:name=”.MainActivity”
android:label=”TestAddition2?
android:theme=”@style/AppTheme.NoActionBar”>



2- MainActivity

This is main java class which contains code that handle all the ui request from the user.
package com.example.siddhu.addition;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.view.View.OnClickListener;
public class MainActivity extends AppCompatActivity {

//step1 : create all the variables.
EditText et1, et2, et3;
Button b1, b2;

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

//step2 : get all the views from xml file.
et1 = (EditText) findViewById(R.id.editText1);
et2 = (EditText) findViewById(R.id.editText2);
et3 = (EditText) findViewById(R.id.editText3);

b1 = (Button) findViewById(R.id.button1);
b2 = (Button) findViewById(R.id.button2);

//step3 : write add functionality.
b1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String f = et1.getText().toString();
int i = Integer.parseInt(f);
String s = et2.getText().toString();
int j = Integer.parseInt(s);

Integer result = i+j;
String res = result.toString();
et3.setText(res);
}
});
b2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String f = et1.getText().toString();
int i = Integer.parseInt(f);
String s = et2.getText().toString();
int j = Integer.parseInt(s);

Integer result = i-j;
String res = result.toString();
et3.setText(res);
}
});

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

}
3- activity_main.xml

This is base xml used by the android to map activity associated with UI Pages.

tools:context=”com.example.siddhu.addition.MainActivity”

4- content_main.xml

This is ui xml. This is render on screen of android to show different components



android:id=”@+id/editText1?
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignParentTop=”true”
android:layout_centerHorizontal=”true”
android:layout_marginTop=”24dp”
android:ems=”10?
android:inputType=”textNoSuggestions”/>

android:id=”@+id/editText2?
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignLeft=”@+id/editText1?
android:layout_below=”@+id/editText1?
android:ems=”10? />

android:id=”@+id/button1?
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignLeft=”@+id/editText2?
android:layout_below=”@+id/editText2?
android:text=”Add” />

android:id=”@+id/button2?
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignBaseline=”@+id/button1?
android:layout_alignBottom=”@+id/button1?
android:layout_alignRight=”@+id/editText2?
android:text=”Sub” />

android:id=”@+id/editText3?
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignLeft=”@+id/button1?
android:layout_below=”@+id/button1?
android:ems=”10? >