Wednesday 30 October 2013

hello for sqlite
=>manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.hello"
    android:versionCode="1"
    android:versionName="1.0" >

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
         <activity
            android:name=".Main_Screen"
            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=".Add_Update_User"
            android:configChanges="orientation"
            android:label="@string/app_name" />
        <activity
            android:name=".My_Blog"
            android:configChanges="orientation"
            android:label="@string/app_name" />
       
    </application>

</manifest>
==========================================================
Add_Update_User.java
package com.example.hello;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.PhoneNumberFormattingTextWatcher;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

public class Add_Update_User extends Activity {
    EditText add_name, add_mobile, add_email;
    Button add_save_btn, add_view_all, update_btn, update_view_all;
    LinearLayout add_view, update_view;
    String valid_mob_number = null, valid_email = null, valid_name = null,
        Toast_msg = null, valid_user_id = "";
    int USER_ID;
    DatabaseHandler dbHandler = new DatabaseHandler(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.add_update_screen);

    // set screen
    Set_Add_Update_Screen();

    // set visibility of view as per calling activity
    String called_from = getIntent().getStringExtra("called");

    if (called_from.equalsIgnoreCase("add")) {
        add_view.setVisibility(View.VISIBLE);
        update_view.setVisibility(View.GONE);
    } else {

        update_view.setVisibility(View.VISIBLE);
        add_view.setVisibility(View.GONE);
        USER_ID = Integer.parseInt(getIntent().getStringExtra("USER_ID"));

        Contact c = dbHandler.Get_Contact(USER_ID);

        add_name.setText(c.getName());
        add_mobile.setText(c.getPhoneNumber());
        add_email.setText(c.getEmail());
        // dbHandler.close();
    }
    add_mobile.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
            int count) {
        // TODO Auto-generated method stub

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
        // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub
        // min lenth 10 and max lenth 12 (2 extra for - as per phone
        // matcher format)
        Is_Valid_Sign_Number_Validation(12, 12, add_mobile);
        }
    });
    add_mobile
        .addTextChangedListener(new PhoneNumberFormattingTextWatcher());

    add_email.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
            int count) {
        // TODO Auto-generated method stub

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
        // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub
        Is_Valid_Email(add_email);
        }
    });

    add_name.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
            int count) {
        // TODO Auto-generated method stub

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
        // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub
        Is_Valid_Person_Name(add_name);
        }
    });

    add_save_btn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
        // TODO Auto-generated method stub
        // check the value state is null or not
        if (valid_name != null && valid_mob_number != null
            && valid_email != null && valid_name.length() != 0
            && valid_mob_number.length() != 0
            && valid_email.length() != 0) {

            dbHandler.Add_Contact(new Contact(valid_name,
                valid_mob_number, valid_email));
            Toast_msg = "Data inserted successfully";
            Show_Toast(Toast_msg);
            Reset_Text();

        }

        }
    });

    update_btn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
        // TODO Auto-generated method stub

        valid_name = add_name.getText().toString();
        valid_mob_number = add_mobile.getText().toString();
        valid_email = add_email.getText().toString();

        // check the value state is null or not
        if (valid_name != null && valid_mob_number != null
            && valid_email != null && valid_name.length() != 0
            && valid_mob_number.length() != 0
            && valid_email.length() != 0) {

            dbHandler.Update_Contact(new Contact(USER_ID, valid_name,
                valid_mob_number, valid_email));
            dbHandler.close();
            Toast_msg = "Data Update successfully";
            Show_Toast(Toast_msg);
            Reset_Text();
        } else {
            Toast_msg = "Sorry Some Fields are missing.\nPlease Fill up all.";
            Show_Toast(Toast_msg);
        }

        }
    });
    update_view_all.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
        // TODO Auto-generated method stub
        Intent view_user = new Intent(Add_Update_User.this,
            Main_Screen.class);
        view_user.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
            | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(view_user);
        finish();
        }
    });

    add_view_all.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
        // TODO Auto-generated method stub
        Intent view_user = new Intent(Add_Update_User.this,
            Main_Screen.class);
        view_user.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
            | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(view_user);
        finish();
        }
    });

    }

    public void Set_Add_Update_Screen() {

    add_name = (EditText) findViewById(R.id.add_name);
    add_mobile = (EditText) findViewById(R.id.add_mobile);
    add_email = (EditText) findViewById(R.id.add_email);

    add_save_btn = (Button) findViewById(R.id.add_save_btn);
    update_btn = (Button) findViewById(R.id.update_btn);
    add_view_all = (Button) findViewById(R.id.add_view_all);
    update_view_all = (Button) findViewById(R.id.update_view_all);

    add_view = (LinearLayout) findViewById(R.id.add_view);
    update_view = (LinearLayout) findViewById(R.id.update_view);

    add_view.setVisibility(View.GONE);
    update_view.setVisibility(View.GONE);

    }

    public void Is_Valid_Sign_Number_Validation(int MinLen, int MaxLen,
        EditText edt) throws NumberFormatException {
    if (edt.getText().toString().length() <= 0) {
        edt.setError("Number Only");
        valid_mob_number = null;
    } else if (edt.getText().toString().length() < MinLen) {
        edt.setError("Minimum length " + MinLen);
        valid_mob_number = null;

    } else if (edt.getText().toString().length() > MaxLen) {
        edt.setError("Maximum length " + MaxLen);
        valid_mob_number = null;

    } else {
        valid_mob_number = edt.getText().toString();

    }

    } // END OF Edittext validation

    public void Is_Valid_Email(EditText edt) {
    if (edt.getText().toString() == null) {
        edt.setError("Invalid Email Address");
        valid_email = null;
    } else if (isEmailValid(edt.getText().toString()) == false) {
        edt.setError("Invalid Email Address");
        valid_email = null;
    } else {
        valid_email = edt.getText().toString();
    }
    }

    boolean isEmailValid(CharSequence email) {
    return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
    } // end of email matcher

    public void Is_Valid_Person_Name(EditText edt) throws NumberFormatException {
    if (edt.getText().toString().length() <= 0) {
        edt.setError("Accept Alphabets Only.");
        valid_name = null;
    } else if (!edt.getText().toString().matches("[a-zA-Z ]+")) {
        edt.setError("Accept Alphabets Only.");
        valid_name = null;
    } else {
        valid_name = edt.getText().toString();
    }

    }

    public void Show_Toast(String msg) {
    Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
    }

    public void Reset_Text() {

    add_name.getText().clear();
    add_mobile.getText().clear();
    add_email.getText().clear();

    }

}
=========================================================================
=>Contact.java
package com.example.hello;

public class Contact {

    // private variables
    public int _id;
    public String _name;
    public String _phone_number;
    public String _email;

    public Contact() {
    }

    // constructor
    public Contact(int id, String name, String _phone_number, String _email) {
    this._id = id;
    this._name = name;
    this._phone_number = _phone_number;
    this._email = _email;

    }

    // constructor
    public Contact(String name, String _phone_number, String _email) {
    this._name = name;
    this._phone_number = _phone_number;
    this._email = _email;
    }

    // getting ID
    public int getID() {
    return this._id;
    }

    // setting id
    public void setID(int id) {
    this._id = id;
    }

    // getting name
    public String getName() {
    return this._name;
    }

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

    // getting phone number
    public String getPhoneNumber() {
    return this._phone_number;
    }

    // setting phone number
    public void setPhoneNumber(String phone_number) {
    this._phone_number = phone_number;
    }

    // getting email
    public String getEmail() {
    return this._email;
    }

    // setting email
    public void setEmail(String email) {
    this._email = email;
    }

}
==================================================================================
DatabaseHandler.java
package com.example.hello;

import java.util.ArrayList;

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;

public class DatabaseHandler extends SQLiteOpenHelper {

    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "contactsManager";

    // Contacts table name
    private static final String TABLE_CONTACTS = "contacts";

    // Contacts Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";
    private static final String KEY_PH_NO = "phone_number";
    private static final String KEY_EMAIL = "email";
    private final ArrayList<Contact> contact_list = new ArrayList<Contact>();

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

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

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

    // Create tables again
    onCreate(db);
    }

    /**
     * All CRUD(Create, Read, Update, Delete) Operations
     */

    // Adding new contact
    public void Add_Contact(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(KEY_NAME, contact.getName()); // Contact Name
    values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone
    values.put(KEY_EMAIL, contact.getEmail()); // Contact Email
    // Inserting Row
    db.insert(TABLE_CONTACTS, null, values);
    db.close(); // Closing database connection
    }

    // Getting single contact
    Contact Get_Contact(int id) {
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
        KEY_NAME, KEY_PH_NO, KEY_EMAIL }, KEY_ID + "=?",
        new String[] { String.valueOf(id) }, null, null, null, null);
    if (cursor != null)
        cursor.moveToFirst();

    Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
        cursor.getString(1), cursor.getString(2), cursor.getString(3));
    // return contact
    cursor.close();
    db.close();

    return contact;
    }

    // Getting All Contacts
    public ArrayList<Contact> Get_Contacts() {
    try {
        contact_list.clear();

        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
        do {
            Contact contact = new Contact();
            contact.setID(Integer.parseInt(cursor.getString(0)));
            contact.setName(cursor.getString(1));
            contact.setPhoneNumber(cursor.getString(2));
            contact.setEmail(cursor.getString(3));
            // Adding contact to list
            contact_list.add(contact);
        } while (cursor.moveToNext());
        }

        // return contact list
        cursor.close();
        db.close();
        return contact_list;
    } catch (Exception e) {
        // TODO: handle exception
        Log.e("all_contact", "" + e);
    }

    return contact_list;
    }

    // Updating single contact
    public int Update_Contact(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, contact.getName());
    values.put(KEY_PH_NO, contact.getPhoneNumber());
    values.put(KEY_EMAIL, contact.getEmail());

    // updating row
    return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
        new String[] { String.valueOf(contact.getID()) });
    }

    // Deleting single contact
    public void Delete_Contact(int id) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
        new String[] { String.valueOf(id) });
    db.close();
    }

    // Getting contacts Count
    public int Get_Total_Contacts() {
    String countQuery = "SELECT  * FROM " + TABLE_CONTACTS;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    cursor.close();

    // return count
    return cursor.getCount();
    }

}
=========================================================================
Main_Screen.java
package com.example.hello;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class Main_Screen extends Activity {
    Button add_btn;
    ListView Contact_listview;
    ArrayList<Contact> contact_data = new ArrayList<Contact>();
    Contact_Adapter cAdapter;
    DatabaseHandler db;
    String Toast_msg;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    try {
        Contact_listview = (ListView) findViewById(R.id.list);
        Contact_listview.setItemsCanFocus(false);
        add_btn = (Button) findViewById(R.id.add_btn);

        Set_Referash_Data();

    } catch (Exception e) {
        // TODO: handle exception
        Log.e("some error", "" + e);
    }
    add_btn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
        // TODO Auto-generated method stub
        Intent add_user = new Intent(Main_Screen.this,
            Add_Update_User.class);
        add_user.putExtra("called", "add");
        add_user.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
            | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(add_user);
        finish();
        }
    });

    }

    public void Call_My_Blog(View v) {
//    Intent intent = new Intent(Main_Screen.this, My_Blog.class);
//    startActivity(intent);

    }

    public void Set_Referash_Data() {
    contact_data.clear();
    db = new DatabaseHandler(this);
    ArrayList<Contact> contact_array_from_db = db.Get_Contacts();

    for (int i = 0; i < contact_array_from_db.size(); i++) {

        int tidno = contact_array_from_db.get(i).getID();
        String name = contact_array_from_db.get(i).getName();
        String mobile = contact_array_from_db.get(i).getPhoneNumber();
        String email = contact_array_from_db.get(i).getEmail();
        Contact cnt = new Contact();
        cnt.setID(tidno);
        cnt.setName(name);
        cnt.setEmail(email);
        cnt.setPhoneNumber(mobile);

        contact_data.add(cnt);
    }
    db.close();
    cAdapter = new Contact_Adapter(Main_Screen.this, R.layout.listview_row,
        contact_data);
    Contact_listview.setAdapter(cAdapter);
    cAdapter.notifyDataSetChanged();
    }

    public void Show_Toast(String msg) {
    Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    Set_Referash_Data();

    }

    public class Contact_Adapter extends ArrayAdapter<Contact> {
    Activity activity;
    int layoutResourceId;
    Contact user;
    ArrayList<Contact> data = new ArrayList<Contact>();

    public Contact_Adapter(Activity act, int layoutResourceId,
        ArrayList<Contact> data) {
        super(act, layoutResourceId, data);
        this.layoutResourceId = layoutResourceId;
        this.activity = act;
        this.data = data;
        notifyDataSetChanged();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;
        UserHolder holder = null;

        if (row == null) {
        LayoutInflater inflater = LayoutInflater.from(activity);

        row = inflater.inflate(layoutResourceId, parent, false);
        holder = new UserHolder();
        holder.name = (TextView) row.findViewById(R.id.user_name_txt);
        holder.email = (TextView) row.findViewById(R.id.user_email_txt);
        holder.number = (TextView) row.findViewById(R.id.user_mob_txt);
        holder.edit = (Button) row.findViewById(R.id.btn_update);
        holder.delete = (Button) row.findViewById(R.id.btn_delete);
        row.setTag(holder);
        } else {
        holder = (UserHolder) row.getTag();
        }
        user = data.get(position);
        holder.edit.setTag(user.getID());
        holder.delete.setTag(user.getID());
        holder.name.setText(user.getName());
        holder.email.setText(user.getEmail());
        holder.number.setText(user.getPhoneNumber());

        holder.edit.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Log.i("Edit Button Clicked", "**********");

            Intent update_user = new Intent(activity,
                Add_Update_User.class);
            update_user.putExtra("called", "update");
            update_user.putExtra("USER_ID", v.getTag().toString());
            activity.startActivity(update_user);

        }
        });
        holder.delete.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(final View v) {
            // TODO Auto-generated method stub

            // show a message while loader is loading

            AlertDialog.Builder adb = new AlertDialog.Builder(activity);
            adb.setTitle("Delete?");
            adb.setMessage("Are you sure you want to delete ");
            final int user_id = Integer.parseInt(v.getTag().toString());
            adb.setNegativeButton("Cancel", null);
            adb.setPositiveButton("Ok",
                new AlertDialog.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog,
                    int which) {
                    // MyDataObject.remove(positionToRemove);
                    DatabaseHandler dBHandler = new DatabaseHandler(
                        activity.getApplicationContext());
                    dBHandler.Delete_Contact(user_id);
                    Main_Screen.this.onResume();

                }
                });
            adb.show();
        }

        });
        return row;

    }

    class UserHolder {
        TextView name;
        TextView email;
        TextView number;
        Button edit;
        Button delete;
    }

    }

}
=======================================================================
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="10dp"
        android:gravity="bottom|center"
        android:onClick="Call_My_Blog"
        android:orientation="horizontal" >

        <ImageView
            android:id="@+id/imageButton1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/textView1"
            android:layout_gravity="bottom"
            android:onClick="Call_My_Blog"
            android:src="@drawable/ic_launcher" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="Call_My_Blog"
            android:text="Get More Tutorial"
            android:textAppearance="?android:attr/textAppearanceLarge" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="#000000"
        android:orientation="horizontal"
        android:weightSum="1" >

        <Button
            android:id="@+id/add_btn"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#000000"
            android:clickable="false"
            android:focusable="false"
            android:text="Add User"
            android:textColor="#FFFFFF" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <ListView
            android:id="@+id/list"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:focusable="false"
            android:focusableInTouchMode="false" />
    </LinearLayout>

</LinearLayout>
======================================================================
add_update_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="15dp"
        android:layout_marginTop="5dp"
        android:gravity="center"
        android:text="User Application"
        android:textSize="18dp" />

    <EditText
        android:id="@+id/add_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Name"
        android:inputType="textPersonName" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/add_mobile"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:ems="10"
        android:hint="Mobile Number"
        android:inputType="phone"
        android:maxLength="12" />

    <EditText
        android:id="@+id/add_email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:ems="10"
        android:hint="Email Address"
        android:inputType="textEmailAddress" />

    <LinearLayout
        android:id="@+id/add_view"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="10dp"
        android:orientation="horizontal"
        android:weightSum="2" >

        <Button
            android:id="@+id/add_save_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            android:layout_weight="1"
            android:background="#000000"
            android:text="Add User"
            android:textColor="#FFFFFF" />

        <Button
            android:id="@+id/add_view_all"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            android:layout_weight="1"
            android:background="#000000"
            android:text="View All"
            android:textColor="#FFFFFF" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/update_view"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="10dp"
        android:orientation="horizontal"
        android:weightSum="2" >

        <Button
            android:id="@+id/update_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            android:layout_weight="1"
            android:background="#000000"
            android:text="Save Updates"
            android:textColor="#FFFFFF" />

        <Button
            android:id="@+id/update_view_all"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            android:layout_weight="1"
            android:background="#000000"
            android:text="View All"
            android:textColor="#FFFFFF" />
    </LinearLayout>

</LinearLayout>
======================================================================
listview_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/user_name_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:visibility="gone" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/user_name_txt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text=""
                android:textAppearance="?android:attr/textAppearanceMedium" />

            <TextView
                android:id="@+id/user_mob_txt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text=""
                android:textAppearance="?android:attr/textAppearanceSmall" />

            <TextView
                android:id="@+id/user_email_txt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text=""
                android:textAppearance="?android:attr/textAppearanceSmall" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="right"
            android:orientation="horizontal" >

            <Button
                android:id="@+id/btn_update"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="5dp"
                android:background="@drawable/ic_launcher"
                android:focusable="false"
                android:focusableInTouchMode="false"
                android:text="" />

            <Button
                android:id="@+id/btn_delete"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="5dp"
                android:background="@drawable/ic_launcher"
                android:focusable="false"
                android:focusableInTouchMode="false"
                android:text="" />
        </LinearLayout>
    </LinearLayout>

</LinearLayout>

sqlite database

https://github.com/khetiyachintan/SQLite-Database-Example

Monday 21 October 2013

soap based parsing

http://stackoverflow.com/questions/1484122/android-wsdl-soap-service-client

Sunday 20 October 2013

package com.niticentral.Interface;

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

import org.apache.http.NameValuePair;
import org.apache.http.client.ResponseHandler;
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.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.util.Log;

public class Http {
    JSONObject jo_search, jo_category, jo_category_story, jo_get_recent_post,
            jo_story_detail, jo_res_comment, jo_res_newsletter,
            jo_get_author_post, jo_get_author_list, jo_res_about_us,
            facebook_wallpost,jo_short_url;
    JSONArray jr_comments_list;
    String apikey = "26fcfd6c27628f6947fe27e4a302f4ca";
    String sort_api_key = "R_83b6276d7ae7c97ec01755df963d4650";
        String sort_api_name= "nitidigital";
           
    String record_count = "15";
    //<string name="url"></string>
    //String sort_api = "http://api.bitly.com/v3/shorten/?login=nitidigital&apiKey=R_83b6276d7ae7c97ec01755df963d4650&longUrl=http://www.niticentral.com/2013/05/20/we-cant-afford-to-be-junked-79694.html";
    public JSONObject get_sort_url (String long_url){
        try {
            DefaultHttpClient httpclient = new DefaultHttpClient();
            ResponseHandler<String> responsehandler = new BasicResponseHandler();
            HttpGet getmethod = new HttpGet("http://api.bitly.com/v3/shorten/?login="+sort_api_name+"&apiKey="+sort_api_key+"&longUrl="+long_url+"");
            String response = httpclient.execute(getmethod, responsehandler);
            jo_short_url = new JSONObject(response);
            //
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jo_short_url;
       
    }
    public JSONObject search1(String page, String key) {
        try {
            DefaultHttpClient httpclient = new DefaultHttpClient();
            ResponseHandler<String> responsehandler = new BasicResponseHandler();
            HttpGet getmethod = new HttpGet(Constants.base_url
                    + "get_search_results/?dev=1&search="+key+"&count="
                    + record_count + "&page=" + page + "&apikey=" + apikey + "");
            String response = httpclient.execute(getmethod, responsehandler);
            jo_search = new JSONObject(response);
            //
        } catch (Exception e) {
            e.printStackTrace();
        }

        return jo_search;

    }
    public JSONObject search(String page, String key) {
        // http://beta.niticentral.com/api/respond/submit_comment/?dev=1&post_id=15782&name=rami&email=rami@gmail.com&content=rrrrrrrr&apikey=26fcfd6c27628f6947fe27e4a302f4ca
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            ResponseHandler<String> resonseHandler = new BasicResponseHandler();
   
            HttpPost getmethod = new HttpPost(Constants.base_url
                    + "get_search_results/?dev=1");
            // http://www.niticentral.com/api/respond/submit_comment/?dev=1
           
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
            nameValuePairs.add(new BasicNameValuePair("search", key));
            nameValuePairs.add(new BasicNameValuePair("count", record_count));
            nameValuePairs.add(new BasicNameValuePair("page", page));
           
            nameValuePairs.add(new BasicNameValuePair("apikey", apikey));

            getmethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            String response = httpClient.execute(getmethod, resonseHandler);
            //Constants.appendLog("res"+response);
            jo_search = new JSONObject(response);
           

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

    }

    public JSONObject get_category() {
        try {
            DefaultHttpClient httpclient = new DefaultHttpClient();
            ResponseHandler<String> responsehandler = new BasicResponseHandler();

            HttpGet getmethod = new HttpGet(Constants.base_url
                    + "get_category_index/?dev=1&catid=214&apikey=" + apikey
                    + "");
            String response = httpclient.execute(getmethod, responsehandler);
            jo_category = new JSONObject(response);
            // //Log.e("","jr_res_category"+jo_category);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return jo_category;

    }

    public JSONObject get_category_story(String page, String cat_id) {
        try {
            DefaultHttpClient httpclient = new DefaultHttpClient();
            ResponseHandler<String> responsehandler = new BasicResponseHandler();

            HttpGet getmethod = new HttpGet(Constants.base_url
                    + "get_category_posts/?dev=1&id=" + cat_id + "&count="
                    + record_count + "&page=" + page + "&apikey=" + apikey + "");
            String response = httpclient.execute(getmethod, responsehandler);
            jo_category_story = new JSONObject(response);
            // //Log.e("","jr_res_category"+jo_category_story);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return jo_category_story;

    }

    public JSONObject get_story_detail(String story_id,String width) {
        try {
            DefaultHttpClient httpclient = new DefaultHttpClient();
            ResponseHandler<String> responsehandler = new BasicResponseHandler();
           
            HttpGet getmethod = new HttpGet(Constants.base_url
                    + "get_post/?dev=1&id=" + story_id + "&width="+width+"&apikey=" + apikey
                    + "");
            String response = httpclient.execute(getmethod, responsehandler);
            jo_story_detail = new JSONObject(response);
            // //Log.e("","jo_story_detail"+jo_story_detail);
        //    Constants.appendLog("res jo_story_detail"+jo_story_detail);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return jo_story_detail;

    }

    public JSONObject get_author_list(String page) {
        try {
            DefaultHttpClient httpclient = new DefaultHttpClient();
            ResponseHandler<String> responsehandler = new BasicResponseHandler();

            HttpGet getmethod = new HttpGet(Constants.base_url
                    + "get_author_index_paging/?dev=1&id=23268&apikey="
                    + apikey + "&count="+record_count+"&page=" + page + "");
            String response = httpclient.execute(getmethod, responsehandler);
            jo_get_author_list = new JSONObject(response);
            // //Log.e("","jo_get_author_list"+jo_get_author_list);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return jo_get_author_list;

    }

    public JSONObject get_author_post(String author_id, String page) {
        try {
            DefaultHttpClient httpclient = new DefaultHttpClient();
            ResponseHandler<String> responsehandler = new BasicResponseHandler();

            HttpGet getmethod = new HttpGet(Constants.base_url
                    + "get_author_posts/?dev=1&id=" + author_id + "&count="
                    + record_count + "&page=" + page + "&apikey=" + apikey + "");
            String response = httpclient.execute(getmethod, responsehandler);
            jo_get_author_post = new JSONObject(response);
            // //Log.e("","jo_story_detail"+jo_story_detail);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return jo_get_author_post;

    }

    public JSONArray get_comment_list(String story_id) {
        try {
            DefaultHttpClient httpclient = new DefaultHttpClient();
            ResponseHandler<String> responsehandler = new BasicResponseHandler();

            HttpGet getmethod = new HttpGet(Constants.base_url
                    + "get_posts_comments/?dev=1&post_id=" + story_id
                    + "&apikey=" + apikey + "");
            String response = httpclient.execute(getmethod, responsehandler);
            jr_comments_list = new JSONArray(response);
            //Log.e("", "jo_story_detail" + jr_comments_list);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return jr_comments_list;

    }

    public JSONObject send_comment(String post_id, String name, String email,
            String content) {
        // http://beta.niticentral.com/api/respond/submit_comment/?dev=1&post_id=15782&name=rami&email=rami@gmail.com&content=rrrrrrrr&apikey=26fcfd6c27628f6947fe27e4a302f4ca
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            ResponseHandler<String> resonseHandler = new BasicResponseHandler();
   
            HttpPost getmethod = new HttpPost(Constants.base_url
                    + "respond/submit_comment/?dev=1");
            // http://www.niticentral.com/api/respond/submit_comment/?dev=1
           
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
            nameValuePairs.add(new BasicNameValuePair("post_id", post_id));
            nameValuePairs.add(new BasicNameValuePair("name", name));
            nameValuePairs.add(new BasicNameValuePair("email", email));
            nameValuePairs.add(new BasicNameValuePair("content", content));
            nameValuePairs.add(new BasicNameValuePair("apikey", apikey));

            getmethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            String response = httpClient.execute(getmethod, resonseHandler);
            //Constants.appendLog("res"+response);
            jo_res_comment = new JSONObject(response);
           

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

    }

    public JSONObject news_letter(String action, String email_id) {
        try {
            DefaultHttpClient httpclient = new DefaultHttpClient();
            ResponseHandler<String> responsehandler = new BasicResponseHandler();

            HttpGet getmethod = new HttpGet(Constants.base_url + "respond/"
                    + action + "/?dev=1&email=" + email_id + "&apikey="
                    + apikey + "");
            String response = httpclient.execute(getmethod, responsehandler);
            jo_res_newsletter = new JSONObject(response);
            //Log.e("", "Res" + response);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return jo_res_newsletter;

    }

    public JSONObject cmspage(String key) {
        try {
            DefaultHttpClient httpclient = new DefaultHttpClient();
            ResponseHandler<String> resonseHandler = new BasicResponseHandler();
            HttpGet get_method = new HttpGet(Constants.base_url
                    + "get_page/?dev=1&slug=" + key
                    + "&apikey=26fcfd6c27628f6947fe27e4a302f4ca");
            String response = httpclient.execute(get_method, resonseHandler);
            jo_res_about_us = new JSONObject(response);
            // //Log.e("","jo_res_author_post"+jo_res_author_post);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jo_res_about_us;

    }

}
------------------------------------------------------------------------------------------------------
try {
                Http get_category = new Http();
                jo_res_category = get_category.get_category();
                jr_res_category = jo_res_category.getJSONArray("categories");
                for (int i = 0; i < jr_res_category.length(); i++) {
                    jo_category_details = jr_res_category.getJSONObject(i);
                    category_id.add(jo_category_details.getString("id"));
                    category_name.add(jo_category_details.getString("name"));
                }
                settings = getSharedPreferences(PREFS_NAME, 0);
                SharedPreferences.Editor editor = settings.edit();
                int j;
                editor.putInt("size", category_id.size());
                for (j = 0; j < category_id.size(); j++) {
                    editor.putString("catid" + j, category_id.get(j));
                    editor.putString("catname" + j, category_name.get(j));
                }
                // Commit the edits!
                editor.commit();
                flag_first = false;

            } catch (Exception e) {
                //FlurryAgent.onError("uncaught", "crash", "exception");
                FlurryAgent.onError("Crash", "Exception in Home Page in android PhoneModel "
                        + PhoneModel + " of version " + AndroidVersion,
                        e.getMessage());

            }