Thursday, August 16, 2012

WebView with Example

If you want to show web application as a part of client application we can use WebView.
main.xml
<WebView android:id="@+id/webView1" android:layout_width="match_parent" android:layout_height="match_parent">
</WebView>

To open web page write.
WebView wv=(WebView)findViewById(R.id.webView1);
wv.loadUrl("http://www.google.com");

If you want to open a link url within webview.(Such as when user click of link url in webpage.It will open within webview by setting up WebViewClient)
wv.setWebViewClient(new WebViewClient());
 wv.loadUrl("http://www.google.com");
 
We can also display custom code(HTML code) in webview.if any webpage contain javascript to enable javascript in android we have to set setJavaScriptEnabled(true)
 WebSettings websetting=wv.getSettings();
        websetting.setJavaScriptEnabled(true);
        String cusdata="<html><body><h1>Hello, WebView</h1>" +
                "<input type='button' value='Say hello' />" +
"</body></html>";
 wv.loadData(cusdata, "text/html","UTF-8");


If any debug is there in webpage it will show you in logcat
(Debugging your webpage in webview)
 wv.setWebChromeClient(new WebChromeClient(){
             public void onConsoleMessage(String message,int lineno,String sourceid)
             {
                 Log.d("My Application","Messsage" + message + " line no " + lineno + " sourceid" + sourceid );
               
             }
           
         });
        
        wv.loadUrl("http://www.google.com");
Most important thing i Forget to tell you,Before doing all such thing in AndroidManifest.xml you must specify
 <uses-permission android:name="android.permission.INTERNET"/>


Saturday, July 14, 2012

Insert and Display Data from Database in Android

In this blog i am showing you insert and fetching of data from Database (SQLITE database)
Example
"Login and Registration form"


Database name:matrimonial.db
Table Name:Login , Register.
We need this class.
1. DataAdapter.java
2. DatabaseOpenHelper.java
3. Register.java
4. Login.java


DatabaseOpenHelper.java
In this class we are creating Database,Table
Be careful while writing the query.

package com.aniexample;


import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;


public class DatabaseOpenHelper extends SQLiteOpenHelper {
private static final String TAG="DatabaseOpenHelper";
private static final String Database_Name="matrimonial.db";
private static final String Table_Name1="Login";
private static final String Table_Name2="Register";


private static final String Sql_Query1="Create Table " + Table_Name1 + 
     "(_id INTEGER PRIMARY KEY AUTOINCREMENT," +
     "Uname TEXT, " +
     "Pass TEXT);";


private static final String Sql_Query2="Create Table " + Table_Name2 + 
"(_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"FName TEXT, " +
"LName TEXT," +
"Address TEXT," +
"Uname TEXT," +
"Pass TEXT);";
public DatabaseOpenHelper(Context context) {
super(context, Database_Name, null, 1);
// TODO Auto-generated constructor stub
}


@Override
public void onCreate(SQLiteDatabase database) {
// TODO Auto-generated method stub
Log.i(TAG,"Database Created");
database.execSQL(Sql_Query1);
database.execSQL(Sql_Query2);
}


@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
Log.w(TAG, "Version Upgraded from "+ arg1 +" to " + arg2);
}


}

DatabaseAdapter.java
In this class we create method where insertion and fetching of data takes place.

package com.aniexample;


import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;


public class DatabaseAdapter
{
SQLiteDatabase dbase;
DatabaseOpenHelper dbhelper;
public DatabaseAdapter(Context context)
{
dbhelper=new DatabaseOpenHelper(context);
}
public void open()
{
dbase=dbhelper.getWritableDatabase();


}
public void close()
{
dbase.close();
}
public long insertLogin(String uname,String pass)
{
ContentValues values=new ContentValues();
values.put("Uname", uname);
values.put("Pass",pass);
return dbase.insert("Login",null, values);

}
public long insertRegister(String fname,String lname,String add,String uname,String pass)
{
ContentValues values=new ContentValues();
values.put("FName", fname);
values.put("LName", lname);
values.put("Address",add);
values.put("Uname", uname);
values.put("Pass", pass);
return dbase.insert("Register", null, values);
}


public boolean deletedata(long id)
{
return dbase.delete("Register", "_id=?" +  id, null)>0;
}


public Cursor fetchid(String pass,String uname)
{
Cursor mcursor=dbase.rawQuery("select * from Login where Pass=? and Uname=?", new String[] {String.valueOf(pass),String.valueOf(uname) });
if (mcursor.getCount()>0)
{
mcursor.moveToFirst();

}
else
{

mcursor.moveToFirst();
}
return mcursor;
}
}
Login.java
Log.i will show the result in logcat.

package com.aniexample;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
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 AniExampleActivity extends Activity implements OnClickListener{
    /** Called when the activity is first created. */
DatabaseAdapter dbadpt;
Button btnlogin, btnreg;
EditText etuname,etpass;
final Context context=this;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        dbadpt=new DatabaseAdapter(getApplicationContext());
        etuname=(EditText)findViewById(R.id.txtuname);
        etpass=(EditText)findViewById(R.id.txtpass);
        btnlogin=(Button)findViewById(R.id.btnLogin);
        btnreg=(Button)findViewById(R.id.btnRegister);
        btnlogin.setOnClickListener(this);
        btnreg.setOnClickListener(this);
    }
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==R.id.btnLogin)
{
dbadpt.open();
String pass=etpass.getText().toString();
String uname=etuname.getText().toString();
Cursor cursor=dbadpt.fetchid(pass,uname);
if(cursor!=null)
{
Toast.makeText(getApplicationContext(), "Login successfull", Toast.LENGTH_LONG).show();
Log.i("Login", "Username:"+cursor.getString(1) + " password: "+cursor.getString(2));
}

dbadpt.close();
}
if (v.getId()==R.id.btnRegister)
{
Intent itreg=new Intent(context,Register.class);
startActivity(itreg);

}
}
}
Register.java

package com.aniexample;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
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{
DatabaseAdapter dbadpt;
EditText etfname,etlname,etadd,etunm,etpass;
    Button btnreg,btnrlog;
    final Context context=this;
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);
        dbadpt=new DatabaseAdapter(getApplicationContext());
        etfname=(EditText)findViewById(R.id.txtfname);
        etlname=(EditText)findViewById(R.id.txtlname);
        etadd=(EditText)findViewById(R.id.txtadd);
        etunm=(EditText)findViewById(R.id.txtuname1);
        etpass=(EditText)findViewById(R.id.txtpass1);
btnreg=(Button)findViewById(R.id.btnReg);
btnreg.setOnClickListener(this);
btnrlog=(Button)findViewById(R.id.btnGotologin);
btnrlog.setOnClickListener(this);


    }
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==R.id.btnReg)
{
String fname=etfname.getText().toString();
String lname=etlname.getText().toString();
String add=etadd.getText().toString();
String un=etunm.getText().toString();
String pass=etpass.getText().toString();
dbadpt.open();
long insertreg=dbadpt.insertRegister(fname, lname, add, un, pass);
long insertlogin=dbadpt.insertLogin(un, pass);
if (insertreg>=0)
{
Toast.makeText(getApplicationContext(), "ThankYou for Registration", Toast.LENGTH_LONG).show();



}
dbadpt.close();
}
if(v.getId()==R.id.btnGotologin)
{
Intent rlogin=new Intent(context,AniExampleActivity.class);
startActivity(rlogin);

}
}
}
main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
<LinearLayout android:layout_height="wrap_content" android:id="@+id/linearLayout1" android:layout_width="match_parent">
    <EditText android:id="@+id/txtuname" android:layout_height="wrap_content" android:layout_weight="1" android:layout_width="wrap_content" android:hint="UserName">
        <requestFocus></requestFocus>
    </EditText>
</LinearLayout>
<LinearLayout android:layout_height="wrap_content" android:id="@+id/linearLayout2" android:layout_width="match_parent">
    <EditText android:id="@+id/txtpass" android:layout_height="wrap_content" android:layout_weight="1" android:layout_width="wrap_content" android:inputType="textPassword" android:hint="Password"></EditText>
    
</LinearLayout>
<LinearLayout android:layout_height="wrap_content" android:id="@+id/linearLayout3" android:layout_width="match_parent">
    <Button android:text="Login" android:id="@+id/btnLogin" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
    <Button android:text="Register" android:id="@+id/btnRegister" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>
</LinearLayout>
register.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
    <EditText android:id="@+id/txtfname" android:layout_height="wrap_content" android:layout_width="match_parent" android:hint="First Name">
        <requestFocus></requestFocus>
    </EditText>
    <EditText android:id="@+id/txtlname" android:layout_height="wrap_content" android:layout_width="match_parent" android:hint="Last Name"></EditText>
    <EditText android:id="@+id/txtadd" android:layout_height="wrap_content" android:layout_width="match_parent" android:inputType="textPostalAddress" android:hint="Address"></EditText>
    <EditText android:id="@+id/txtuname1" android:layout_height="wrap_content" android:layout_width="match_parent" android:hint="Enter Username"></EditText>
    <EditText android:id="@+id/txtpass1" android:layout_height="wrap_content" android:layout_width="match_parent" android:inputType="textPassword" android:hint="Enter Password"></EditText>
    <LinearLayout android:layout_height="wrap_content" android:id="@+id/linearLayout1" android:layout_width="match_parent">
        <Button android:text="Register" android:id="@+id/btnReg" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
        <Button android:text="GotoLogin" android:id="@+id/btnGotologin" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
    </LinearLayout>    
</LinearLayout>
Set the activity of register.xml in AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.aniexample"
      android:vrsionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="10" />


    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".AniExampleActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
<activity android:name=".Register" android:label="@string/app_name"></activity>
    </application>
</manifest>
Registration



Login


When Login Button is click Result get displayed in logcat.


Saturday, June 30, 2012

Display photo when it is selected in Gallery using Android application

Gallery Example
Example show: Photo get display when it is selected in Gallery.
main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
<ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/icon"></ImageView>
<Gallery android:id="@+id/gallery1" android:layout_width="match_parent" android:layout_height="wrap_content"></Gallery>
</LinearLayout>
For Background
attributes.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
 <declare-styleable name="Gallery1">
 <attr name="android:galleryItemBackground"></attr>
 </declare-styleable>   
</resources>
Now moving in coding part.

package com.galleryexample;


import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;


public class GallaryExampleActivity extends Activity {
    /** Called when the activity is first created. */
Integer[] pics={
        R.drawable.inv1,
        R.drawable.inv2,
        R.drawable.inv3,
        R.drawable.inv4,
        R.drawable.inv5,
        R.drawable.inv6,
        R.drawable.inv7,
        R.drawable.inv8,
        R.drawable.inv9
       
      };
       ImageView imgview;
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Gallery ga=(Gallery)findViewById(R.id.gallery1);
    ga.setAdapter(new ImageAdapter(this));
    imgview =(ImageView)findViewById(R.id.imageView1);
       
       // display image when photo is selected in gallery
   ga.setOnItemSelectedListener(new              Gallery.OnItemSelectedListener() {


     @Override
     public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,long arg3) {

     Toast.makeText(getBaseContext(), "You have selected picture " + (arg2+1) + "", Toast.LENGTH_SHORT).show();
     imgview.setImageResource(pics[arg2]);
    }


    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
    // TODO Auto-generated method stub

    }
    });
       
   //display image when photo is clicked in gallery
/*  ga.setOnItemClickListener(new OnItemClickListener() {
     @Override
     public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
     Toast.makeText(getBaseContext(), "You have selected picture " + (arg2+1) + "", Toast.LENGTH_SHORT).show();
     imgview.setImageResource(pics[arg2]);
    }
    }); */
}


//creating another class
    
    public class ImageAdapter extends BaseAdapter {
    private Context ctx;
    int imgback;
    public ImageAdapter(Context c)
    {
    ctx=c;
    TypedArray ta=c.obtainStyledAttributes(R.styleable.Gallery1);
    imgback=ta.getResourceId(R.styleable.Gallery1_android_galleryItemBackground, 1);
    ta.recycle();
    }


    @Override
    public int getCount() {
    // TODO Auto-generated method stub
    return pics.length ;
    }


    @Override
    public Object getItem(int position) {
    // TODO Auto-generated method stub
    return null;
    }


    @Override
    public long getItemId(int position) {
    // TODO Auto-generated method stub
    return 0;
    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
    ImageView iv=new ImageView(ctx);
    iv.setImageResource(pics[position]);
    iv.setScaleType(ImageView.ScaleType.FIT_XY);
    iv.setLayoutParams(new Gallery.LayoutParams(150,150));
    iv.setBackgroundResource(imgback);
    return iv;
    }
     }
}

output

Wednesday, June 20, 2012

Insert Data in SQLite Database using Android Application

Hello user, today i am going to show how to create database in SQLite and Learn to insert data in database.
Here two field i have taken no and name.
To set watermark on field take <editText android:hint="No" />


<linearlayout android:baselinealigned="false" android:layout_height="match_parent" android:layout_width="match_parent" android:orientation="vertical" xmlns:android=
"http://schemas.android.com/apk/res/android">
<textview android:layout_height="wrap_content" android:layout_width="fill_parent" android:text="@string/hello">
<edittext android:hint="No" android:id="@+id/txtNo" android:layout_height="wrap_content" android:layout_width="match_parent">
<requestfocus></requestfocus>
</edittext>
<edittext android:hint="Name" android:id="@+id/txtName" android:layout_height="wrap_content" android:layout_width="match_parent"></edittext>
<button android:id="@+id/Save" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="Save"></button>
</textview></linearlayout>
Now Let start with coding.
DatabaseDemo.java

package com.databasedemo.db;


import android.app.Activity;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


public class DatabaseDemo1Activity extends Activity implements OnClickListener 
{
    /** Called when the activity is first created. */
    EditText etno,etname;
    Button btnSave;
    DatabaseAdapter dbAdapter;
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        dbAdapter=new DatabaseAdapter(getApplicationContext());
        
        etno=(EditText)findViewById(R.id.txtNo);
        etname=(EditText)findViewById(R.id.txtName);
        btnSave=(Button)findViewById(R.id.Save);
        btnSave.setOnClickListener(this);
    }
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==R.id.Save)
{
//Toast.makeText(getApplicationContext(), "save",Toast.LENGTH_LONG).show();
String no=etno.getText().toString();
String name=etname.getText().toString();
dbAdapter.open();
long inserted=dbAdapter.insertTest(no,name);
if(inserted>=0)
{
Toast.makeText(getApplicationContext(), "data saved",Toast.LENGTH_LONG).show();

etno.setText("");
etname.setText("");
}
else
{
Toast.makeText(getApplicationContext(), "data not saved",Toast.LENGTH_LONG).show();

}
dbAdapter.close();
}
}
}

Here i marked some text in red color, use it after creating DatabaseAdapter Class.
Now Take DatabaseOpenHelper class.


In DatabaseOpenHelper.java
In this class we will create database test_database.db and Table= test.
Make sure there must be space between create table and TABLE_NAME

package com.databasedemo.db;


import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;


public class DatabaseOpenHelper extends SQLiteOpenHelper {


public static final String DBName = "test_database.db";
public static final String TABLE_NAME = "test";
public static final String TABLE_SQL = "Create Table "+ TABLE_NAME 
+"(_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+"no TEXT, "
+"name TEXT);";

public DatabaseOpenHelper(Context context) {
super(context, DBName, null, 1);
// TODO Auto-generated constructor stub
}


@Override
public void onCreate(SQLiteDatabase database) {
// TODO Auto-generated method stub
          database.execSQL(TABLE_SQL);
}


@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub


}


}

To check whether Database is created or not check.
1. click on DDMS TAB.
2. click File Explorer tab.
3. click "data" to expand 
4. again click on "data" to expand
5. see the package name that we create."com.databasedemo.db"
6. in package you will see the "database" click on it
7. after clicking you will see the database name that we named.
do all this when you run application.
Now create DatabaseAdapter class.


In DatabaseAdapter.java

package com.databasedemo.db;


import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;


public class DatabaseAdapter {
SQLiteDatabase database;
DatabaseOpenHelper dbHelper;

public DatabaseAdapter(Context context)
{
       dbHelper=new DatabaseOpenHelper(context);
       
}
public void open()
{
database=dbHelper.getWritableDatabase();
}
public void close()
{
database.close();
}
public long insertTest(String no,String name)
{
ContentValues values=new ContentValues();
values.put("no", no);
values.put("name", name);

return database.insert("test",null, values);
}
}
In next session we will see how to retrieve data
OUTPUT