Friday, October 18, 2013

How to convert Bitmap to String and String to Bitmap


Bitmap to String:
---------------------public String BitMapToString(Bitmap bitmap){
            ByteArrayOutputStream baos=new  ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG,100, baos);
            byte [] arr=baos.toByteArray();
            String result=Base64.encodeToString(arr, Base64.DEFAULT);
            return result;
      }


String to Bitmap:
----------------------public Bitmap StringToBitMap(String image){
       try{
           byte [] encodeByte=Base64.decode(image,Base64.DEFAULT);
           Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
           return bitmap;
         }catch(Exception e){
           e.getMessage();
          return null;
         }
 }

Parse the below url by using JSON. Display the profile picture and the name


URL:  
http://cancos.quadlogix.com/auth/friends 

MainActivity.java
---------------------
package com.kundan.jsonparsingex;


import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
public static final String URL="http://cancos.quadlogix.com/auth/friends";
Button btn,btn2;
static ListView lv;
static TextView tv1;
static ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv=(ListView) findViewById(R.id.listView1);
tv1=(TextView) findViewById(R.id.textView1);
iv=(ImageView) findViewById(R.id.imageView1);
btn=(Button) findViewById(R.id.button1);
btn2=(Button) findViewById(R.id.button2);
btn2.setEnabled(false);
btn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
GetJSONData task = new GetJSONData();
       task.execute(new String[] { URL });
       Toast.makeText(getApplicationContext(), "please wait till image and text loaded...", Toast.LENGTH_LONG).show();
       btn2.setEnabled(true);
}
});


      btn2.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
lv.setAdapter(new MyImageAdapter(getApplicationContext(), GetJSONData.mIcon,GetJSONData.nameID));

}
});

}



}

GetJSONData.java
---------------------------

package com.kundan.jsonparsingex;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
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.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Base64;
import android.util.Log;

public class GetJSONData extends AsyncTask<String, Void, String> {
static String[] nameID=null;
static Bitmap[] mIcon=null;
static String[] imageID=null;
@Override
protected String doInBackground(String... urls) {
String output = null;
       for (String url : urls) {
         
output = getOutputFromUrl(url);
       }
             
       return output;
}

private String getOutputFromUrl(String url) {
String output = null;
try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            output = EntityUtils.toString(httpEntity);
            System.out.println(output);
           try {
JSONObject jobj=new JSONObject(output);
JSONArray jarray=jobj.getJSONArray("data");
System.out.println("////////"+jarray);
JSONObject jobject=null;
nameID=new String[jarray.length()];
imageID=new String[jarray.length()];
mIcon = new Bitmap[jarray.length()];
for(int i=0;i<jarray.length();i++){
jobject=jarray.getJSONObject(i);
nameID[i]=jobject.getString("name");
imageID[i]=jobject.getString("profile_image");
mIcon[i] = StringToBitMap(imageID[i]);
//System.out.println("++++++++++"+nameID[i]);
//System.out.println("++++++++++"+imageID[i]);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}    
         
            
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
return output;
}
@Override
   protected void onPostExecute(String output) {
super.onPostExecute(output);
MainActivity.tv1.setText(nameID[0]);
MainActivity.iv.setImageBitmap(mIcon[0]); 
   
   }

public Bitmap StringToBitMap(String encodedString) {
   try {
       byte[] encodeByte = Base64.decode(encodedString, Base64.DEFAULT);
       Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0,encodeByte.length);
       return bitmap;
   } catch (Exception e) {
       e.getMessage();
       return null;
   }
}
 
}

MyImageAdapter.java
---------------------------
package com.kundan.jsonparsingex;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class MyImageAdapter extends BaseAdapter  {
Context context;
String[] nameID;
Bitmap[] imgId;
static String str1;
public MyImageAdapter(Context context,Bitmap[] ImageID, String[] nameID ) {
this.context=context;
this.imgId=ImageID;
this.nameID=nameID;
}

@Override
public int getCount() {
return nameID.length;
}

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

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView=inflater.inflate(R.layout.image_view, parent,false);
TextView name=(TextView) rowView.findViewById(R.id.nameView);
ImageView image=(ImageView) rowView.findViewById(R.id.imageView1);
name.setText(nameID[position]);
image.setImageBitmap(imgId[position]);
return rowView;
}

}

activity_main.xml
--------------------
<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"
   
    tools:context=".MainActivity" >

   <ListView
        android:id="@+id/listView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:divider="#990000"
        android:dividerHeight="1dip"
        android:paddingTop="5dip"
        android:layout_marginTop="150dp">
    </ListView>

   <Button
       android:id="@+id/button1"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="Load Profile" />

   <ImageView
       android:id="@+id/imageView1"
       android:layout_width="50dp"
       android:layout_height="50dp"
       android:layout_alignParentLeft="true"
       android:layout_below="@+id/button1"
       android:src="@drawable/ic_launcher" />

   <Button
       android:id="@+id/button2"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_alignParentLeft="true"
       android:layout_below="@+id/imageView1"
       android:layout_marginTop="16dp"
       android:text="View all Profile" />

   <TextView
       android:id="@+id/textView1"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignBottom="@+id/imageView1"
       android:layout_marginLeft="19dp"
       android:layout_toRightOf="@+id/imageView1"
       android:text="TextView" />

</RelativeLayout>


image_view.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" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/nameView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/imageView1"
        android:layout_marginLeft="14dp"
        android:layout_toRightOf="@+id/imageView1"
        android:text="Name"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#000099" />

</RelativeLayout>


Monday, October 14, 2013

ActionBar Tabs using FragmentPagerAdapter

MainActivity .java
------------------------

package com.kundan.actionbar_tabs;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;

@SuppressLint("NewApi")
public class MainActivity extends FragmentActivity implements TabListener {
private String[] tabs = { "One", "Two" };
private ViewPager viewPager;
   
   private ActionBar actionBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

        viewPager = (ViewPager) findViewById(R.id.pager);
        actionBar = getActionBar();
        viewPager.setAdapter(new TabsPagerAdapter(getSupportFragmentManager()));
        actionBar.setHomeButtonEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);        

        // Adding Tabs
        for (String tab_name : tabs) {
            actionBar.addTab(actionBar.newTab().setText(tab_name).setTabListener(this));
        }
}

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

@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub

}

@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());


}

@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub

}

}

TabsPagerAdapter .java
-----------------------------
package com.kundan.actionbar_tabs;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class TabsPagerAdapter extends FragmentPagerAdapter{

public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}

@Override
public Fragment getItem(int index) {
switch (index) {
       case 0:
           
           return new One();
       case 1:
          
           return new Two();
       
       }
 
       return null;
}

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

}
One .java
------------

package com.kundan.actionbar_tabs;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class One extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup viewGroup=(ViewGroup) inflater.inflate(R.layout.first, container,false);
return viewGroup;
 
}

}

Two .java
----------------
package com.kundan.actionbar_tabs;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Two extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup viewGroup=(ViewGroup) inflater.inflate(R.layout.two, container,false);
return viewGroup;
 
}

}


activity_main.xml
-------------------
<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=".MainActivity" >
<android.support.v4.view.ViewPager 
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

</RelativeLayout>

first.xml
--------------
<?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" 
    android:background="#996699">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="First fragment" 
        android:layout_gravity="center"/>

</LinearLayout>

two.xml
-------------
<?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" 
    android:background="#996600">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Second Fragment" 
        android:layout_gravity="center"
        />

</LinearLayout>




NOTE: you can slide left or right also...!!!

Friday, October 11, 2013

XML Parsing using XmlPullParser

players.xml
------------
<?xml version="1.0" encoding="UTF-8"?>
<players>
    <player>
        <id>1</id>
        <name>SACHIN</name>
        <salary>50000</salary>      
    </player>
    <player>
        <id>2</id>
        <name>KUNDAN</name>
        <salary>60000</salary>  
    </player>
    
</players>

player.java
-------------
package com.example.xmlpullparsing;
public class Player {
private int id;
private String name;
private float salary;

    
    public int getId() {
return id;
}


public void setId(int id) {
this.id = id;
}


public String getName() {
return name;
}


public void setName(String name) {
this.name = name;
}


public float getSalary() {
return salary;
}


public void setSalary(float salary) {
this.salary = salary;
}


@Override
    public String toString() {
        return " Id= "+id + "\n Name= " + name + "\n Salary= " + salary;
    }
}

XmlPullParserHandler .java
--------------------------------

package com.example.xmlpullparsing;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;


public class XmlPullParserHandler {
    private List<Player> players= new ArrayList<Player>();
    private Player player;
    private String text;

    public List<Player> getPlayers() {
        return players;
    }

    public List<Player> parse(InputStream is) {
           try {
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            factory.setNamespaceAware(true);
            XmlPullParser  parser = factory.newPullParser();

            parser.setInput(is, null);

            int eventType = parser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                String tagname = parser.getName();
                switch (eventType) {
                case XmlPullParser.START_TAG:
                    if (tagname.equalsIgnoreCase("player")) {
                        // create a new instance of employee
                        player = new Player();
                    }
                    break;

                case XmlPullParser.TEXT:
                    text = parser.getText();
                    break;

                case XmlPullParser.END_TAG:
                    if (tagname.equalsIgnoreCase("player")) {
                        // add employee object to list
                        players.add(player);
                    }else if (tagname.equalsIgnoreCase("id")) {
                    player.setId(Integer.parseInt(text));
                    }  else if (tagname.equalsIgnoreCase("name")) {
                    player.setName(text);
                    } else if (tagname.equalsIgnoreCase("salary")) {
                    player.setSalary(Float.parseFloat(text));
                    } 
                    break;

                default:
                    break;
                }
                eventType = parser.next();
            }

        } catch (XmlPullParserException e) {
        e.printStackTrace();
       
        catch (IOException e) {
        e.printStackTrace();
        }

        return players;
    }
}

MainActivity .java
-------------------
package com.example.xmlpullparsing;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
       ListView listView = (ListView) findViewById(R.id.listView1);
       
        List<Player> players = null;
        try {
            XmlPullParserHandler parser = new XmlPullParserHandler();
            InputStream is=getAssets().open("players.xml");
            players = parser.parse(is);
            
            ArrayAdapter<Player> adapter =new ArrayAdapter<Player>(this,android.R.layout.simple_list_item_1, players);
            listView.setAdapter(adapter);
            
        } catch (IOException 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.activity_main, menu);
        return true;
    }
    
}

activity_main.xml
-------------------
<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"
    tools:context=".MainActivity" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        android:divider="#FFCC00"
    android:dividerHeight="4px"
   
    >

    </ListView>

</RelativeLayout>



Tuesday, October 8, 2013

SQLite CURD Operation

Contact.java
--------------
package com.mangium.databaseoperation;

public class Contact {
String id;
String name;
String phone;
public Contact() {
super();
}
public Contact(String id, String name, String phone) {
super();
this.id = id;
this.name = name;
this.phone = phone;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}


}

DatabaseHandler.java
-------------------------
package com.mangium.databaseoperation;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;

public class DatabaseHandler extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 1;    
    private static final String DATABASE_NAME = "mydb";   
    static final String TABLE_CONTACTS = "contacts";
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";
    private static final String KEY_PH_NO = "phone";

public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
String STUDENT_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
                + KEY_PH_NO + " TEXT" + ")";
        db.execSQL(STUDENT_CONTACTS_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);        
        onCreate(db);
}
public void addContact(Contact contact) {
       SQLiteDatabase db = this.getWritableDatabase();  
       ContentValues val = new ContentValues();        
val.put("ID", contact.getId());
val.put("NAME", contact.getName());
val.put("PHONE", contact.getPhone());       
       db.insert(TABLE_CONTACTS, null, val);
       db.close();
   }
public void getContact(String id) {
   SQLiteDatabase db = this.getReadableDatabase();      
   Cursor cur = db.query(TABLE_CONTACTS, null, null, null, null, null, null);
   while(cur.moveToNext()){
    try{
    String val=cur.getString(0);
    if(val.equals(id)){
           
    try{
   
    String name=cur.getString(1);
    String phone=cur.getString(2);
    Show_home.tv1.setText(name);
    Show_home.tv2.setText(phone);
   
    }catch(Exception e){
    e.printStackTrace();
    }
   
    db.close();
    }
    }catch (Exception e){
    e.printStackTrace();
    }
   
   }
   
   cur.close();
}
 
public void deleteContact(String id){
SQLiteDatabase db = this.getWritableDatabase();
String where=KEY_ID+"=?";
String[]whereArgs=new String[]{id};
db.delete(TABLE_CONTACTS, where, whereArgs);
db.close();
}
public void updateContact(String id){
SQLiteDatabase db = this.getWritableDatabase();
String where=KEY_ID+"=?";
String[]whereArgs=new String[]{id};
/*Update.editText1.setText(Show_home.tv1.getText());
Update.editText2.setText(Show_home.tv2.getText());*/
ContentValues val=new ContentValues();  
val.put("NAMe", Update.editText1.getText().toString());
val.put("PHONE", Update.editText2.getText().toString());
db.update(TABLE_CONTACTS, val, where, whereArgs);
 
}
}

MainActivity.java
-------------------
package com.mangium.databaseoperation;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
static EditText ed1;
static EditText ed2;
static EditText ed3;
Button insert_btn, show_btn;
String str1,str2,str3;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed1=(EditText) findViewById(R.id.editText1);
ed2=(EditText) findViewById(R.id.editText2);
ed3=(EditText) findViewById(R.id.editText3);
insert_btn=(Button) findViewById(R.id.insertbtn);
show_btn=(Button) findViewById(R.id.showbtn);
insert_btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
String id=ed1.getText().toString();
String nm=ed2.getText().toString();
String ph=ed3.getText().toString();
Contact contact=new Contact(id,nm,ph);
db.addContact(contact);
ed2.setText(null);
ed3.setText(null);
ed1.requestFocus();
ed1.setSelectAllOnFocus(true);
Toast.makeText(getApplicationContext(), "Record inserted successfully..", Toast.LENGTH_SHORT).show();
 
}
});
show_btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),Show_home.class);
startActivity(i);
}
});
}

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

}


Show_home.java
-------------------
package com.mangium.databaseoperation;

import android.app.Activity;
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.TextView;
import android.widget.Toast;

public class Show_home extends Activity{
static EditText ed1;
static TextView tv1,tv2;
Button searchbtn,delbtn,updatebtn;
String str;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_home);
ed1=(EditText) findViewById(R.id.editText);
searchbtn=(Button) findViewById(R.id.okbtn);
tv1=(TextView) findViewById(R.id.nameView);
tv2=(TextView) findViewById(R.id.phoenView);
delbtn=(Button) findViewById(R.id.delbutton);
updatebtn=(Button) findViewById(R.id.updatebutton);
searchbtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
db.getContact(ed1.getText().toString());
ed1.requestFocus();
ed1.setSelectAllOnFocus(true);
Toast.makeText(getApplicationContext(), "SUCCESS...!!!", Toast.LENGTH_SHORT).show();
}
});
delbtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
db.deleteContact(ed1.getText().toString());
Toast.makeText(getApplicationContext(), "Record Deleted...with ID="+ed1.getText().toString(), Toast.LENGTH_SHORT).show();
tv1.setText("null");
tv2.setText("null");
}
});
updatebtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),Update.class);
startActivity(i);
}
});
}
}


Update.java
------------------
package com.mangium.databaseoperation;

import android.app.Activity;
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 Update extends Activity {
Button updatebutton;
static EditText editText1,editText2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.update);
editText1=(EditText) findViewById(R.id.updatenmText);
editText2=(EditText) findViewById(R.id.updatephText);
updatebutton=(Button) findViewById(R.id.updatebutton1);
editText1.setText(Show_home.tv1.getText());
editText2.setText(Show_home.tv2.getText());
updatebutton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
db.updateContact(Show_home.ed1.getText().toString());
Toast.makeText(getApplicationContext(), "Record updated successfully", Toast.LENGTH_SHORT).show();
Intent intent=new Intent(getApplicationContext(),Show_home.class);
startActivity(intent);
}
});
}

}


activity_main.xml
----------------------
<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=".MainActivity" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="63dp"
        android:ems="10"
        android:hint="Enter Student id"
        android:selectAllOnFocus="true" 
        android:inputType="number"/>

    <requestFocus />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="17dp"
        android:ems="10"
        android:hint="Enter Student Name" >
    </EditText>

    <EditText
        android:id="@+id/editText3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText2"
        android:layout_below="@+id/editText2"
        android:layout_marginTop="18dp"
        android:ems="10"
        android:hint="Enter Student Phone" 
        android:inputType="number"/>

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:gravity="center"
        android:text="@string/head_title"
        android:textSize="18sp" />

    <LinearLayout
        android:id="@+id/LinearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText3"
        android:layout_below="@+id/editText3"
        android:layout_marginTop="88dp"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/showbtn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Search" />

        <Button
            android:id="@+id/insertbtn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Insert" />
    </LinearLayout>

</RelativeLayout>

show_home.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" >

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="40sp"
        android:ems="10"
        android:hint="Enter Student Id" 
        android:selectAllOnFocus="true"/>
<requestFocus />
    <TextView
        android:id="@+id/phoenView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textView2"
        android:layout_alignBottom="@+id/textView2"
        android:layout_alignLeft="@+id/nameView"
        android:text="null"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="22dp"
        android:text="Phone"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <Button
        android:id="@+id/okbtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/editText"
        android:layout_marginTop="16dp"
        android:text="Search" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="@string/search_info" 
        android:textSize="18sp"/>

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/textView2"
        android:layout_below="@+id/okbtn"
        android:layout_marginTop="34dp"
        android:text="Name"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <Button
        android:id="@+id/updatebutton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/phoenView"
        android:layout_marginTop="30dp"
        android:text="Update" />

    <TextView
        android:id="@+id/nameView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/textView2"
        android:layout_marginLeft="22dp"
        android:layout_toRightOf="@+id/textView1"
        android:text="null"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <Button
        android:id="@+id/delbutton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/updatebutton"
        android:text="Delete" />

</RelativeLayout>

update.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" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="15dp"
        android:text="@string/update_record" 
        android:textSize="18sp"/>

    <EditText
        android:id="@+id/updatenmText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="22dp"
        android:ems="10"
        android:hint="Enter new Name" />

    <EditText
        android:id="@+id/updatephText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/updatenmText"
        android:layout_below="@+id/updatenmText"
        android:layout_marginTop="15dp"
        android:ems="10"
        android:hint="Enter new Phone"
        android:inputType="number" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/updatenmText"
        android:layout_alignBottom="@+id/updatenmText"
        android:layout_alignParentLeft="true"
        android:text="Name" 
        android:layout_marginLeft="10dp"
        android:textSize="16sp"/>

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/updatephText"
        android:layout_alignBottom="@+id/updatephText"
        android:layout_alignParentLeft="true"
        android:text="Phone" 
        android:layout_marginLeft="10dp"
        android:textSize="16sp"/>

    <Button
        android:id="@+id/updatebutton1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/updatephText"
        android:layout_marginTop="33dp"
        android:text="Update" />

</RelativeLayout>

strings.xml
-------------
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">DatabaseOperation</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
 <string name="head_title"><u>Student Information</u></string>
 <string name="search_info"><u>Search Results</u></string>
 <string name="update_record"><u>Update Records</u></string>
</resources>

AndroidManifest.xml
----------------------
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mangium.databaseoperation"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.mangium.databaseoperation.MainActivity"
            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="Show_home"></activity>
        <activity android:name="Update"></activity>
    </application>

</manifest>