Sunday, 8 December 2013

Android Json Parsing + Sqlite Database Example

Hello ALL,

 Today i created one example for Parsing JSON and store response in sqlite database and display, update and delete operations from database.

Menifest.xml


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

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

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
          <activity android:name="SearchProduct" />
          <activity android:name="AddUpdateValues"></activity>
    </application>

</manifest>


MainActivity.java


package com.samir;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.androidadvance.db.DatabaseHelper;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnItemClickListener {

private static final String rssFeed = "https://www.dropbox.com/s/rhk01nqlyj5gixl/jsonparsing.txt?dl=1";

private static final String ARRAY_NAME = "student";
private static final String ID = "id";
private static final String NAME = "name";
private static final String CITY = "city";
private static final String GENDER = "Gender";
private static final String AGE = "age";
private static final String BIRTH_DATE = "birthdate";

// List<Item> arrayOfList;

ArrayList<ProductModel> arrayOfList;
ListView listView;
NewsRowAdapter objAdapter;
DatabaseHelper db;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
arrayOfList = new ArrayList<ProductModel>();
listView = (ListView) findViewById(R.id.listview);
listView.setOnItemClickListener(this);

// arrayOfList = new ArrayList<Item>();

if (Utils.isNetworkAvailable(MainActivity.this)) {
new MyTask().execute(rssFeed);
} else {
showToast("No Network Connection!!!");
}

}

public void Search(View v) {
startActivity(new Intent(MainActivity.this, SearchProduct.class));
}
// public void Update(View v)
// {
// startActivity(new Intent(MainActivity.this,AddUpdateValues.class));
// }

// My AsyncTask start...

class MyTask extends AsyncTask<String, Void, String> {

ProgressDialog pDialog;

@Override
protected void onPreExecute() {
super.onPreExecute();

pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
}

@Override
protected String doInBackground(String... params) {
return Utils.getJSONString(params[0]);
}

@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);

if (null != pDialog && pDialog.isShowing()) {
pDialog.dismiss();
}

if (null == result || result.length() == 0) {
showToast("No data found from web!!!");
MainActivity.this.finish();
} else {

try {
JSONObject mainJson = new JSONObject(result);
JSONArray jsonArray = mainJson.getJSONArray(ARRAY_NAME);

db = new DatabaseHelper(MainActivity.this);
db.getWritableDatabase();
db.emptyProduct();

for (int i = 0; i < jsonArray.length(); i++) {
JSONObject objJson = jsonArray.getJSONObject(i);

ProductModel prod = new ProductModel();

prod.productname = objJson.getString(NAME);
prod.productprice = objJson.getString(CITY);
//prod.idno= objJson.getString(ID);


prod.setProductname(objJson.getString(NAME));
prod.setProductprice(objJson.getString(CITY));
//prod.setIdno(objJson.getString(ID));

Log.e("-----size-----",
"-----size-----" + objJson.getString(NAME));

db.addProduct(prod);

// Item objItem = new Item();
//
// objItem.setId(objJson.getInt(ID));
// objItem.setName(objJson.getString(NAME));
// objItem.setCity(objJson.getString(CITY));
// objItem.setGender(objJson.getString(GENDER));
// objItem.setAge(objJson.getInt(AGE));
// objItem.setBirthdate(objJson.getString(BIRTH_DATE));

// arrayOfList.add(prod);

}
db.close();
} catch (JSONException e) {
e.printStackTrace();
}
// check data...

/*
* for (int i = 0; i < arrayOfList.size(); i++) { Item item =
* arrayOfList.get(i); System.out.println(item.getId());
*
* System.out.println(item.getId());
* System.out.println(item.getName());
* System.out.println(item.getCity());
* System.out.println(item.getGender());
* System.out.println(item.getAge());
* System.out.println(item.getBirthdate()); }
*/

// Collections.sort(arrayOfList, new Comparator<Item>() {
//
// @Override
// public int compare(Item lhs, Item rhs) {
// return (lhs.getAge() - rhs.getAge());
// }
// });
setAdapterToListview();

}

}
}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
showDeleteDialog(position);
}

private void showDeleteDialog(final int position) {
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this)
.create();
alertDialog.setTitle("Delete ??");
alertDialog.setMessage("Are you sure want to Delete it??");
// db. removeProduct(prod);
alertDialog.setButton("No", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.setButton2("Yes", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {

// ProductModel model = new ProductModel();
String name = arrayOfList.get(position).getProductname();

db = new DatabaseHelper(MainActivity.this);
db.getWritableDatabase();


db.removeProduct(name);
db.close();
arrayOfList.remove(position);
objAdapter.notifyDataSetChanged();

}
});
alertDialog.show();

}

public void setAdapterToListview() {

db = new DatabaseHelper(MainActivity.this);
db.getWritableDatabase();
arrayOfList.clear();
arrayOfList = db.getProudcts();
Log.e("-----size-----", "-----size-----" + arrayOfList.size());

objAdapter = new NewsRowAdapter(MainActivity.this, R.layout.row,
arrayOfList);
listView.setAdapter(objAdapter);
}

public void showToast(String msg) {
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
}

}



NewsRowAdapter.java

package com.samir;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class NewsRowAdapter extends ArrayAdapter<ProductModel> {

private Activity activity;
private List<ProductModel> items;
private ProductModel objBean;
private int row;

public NewsRowAdapter(Activity act, int resource, List<ProductModel> arrayList) {
super(act, resource, arrayList);
this.activity = act;
this.row = resource;
this.items = arrayList;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
ViewHolder holder;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(row, null);

holder = new ViewHolder();
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}

if ((items == null) || ((position + 1) > items.size()))
return view;

objBean = items.get(position);

holder.tvName = (TextView) view.findViewById(R.id.tvname);
holder.tvCity = (TextView) view.findViewById(R.id.tvcity);
holder.tvBDate = (TextView) view.findViewById(R.id.tvbdate);
holder.tvGender = (TextView) view.findViewById(R.id.tvgender);
holder.tvAge = (TextView) view.findViewById(R.id.tvage);


holder.tvCity.setText(Html.fromHtml(objBean.getProductname()));
holder.tvName.setText(Html.fromHtml(objBean.getProductprice()));


return view;
}

public class ViewHolder {
public TextView tvName, tvCity, tvBDate, tvGender, tvAge;
}

}


ProductModel.java

package com.samir;

public class ProductModel {

public String getProductname() {
return productname;
}

public void setProductname(String productname) {
this.productname = productname;
}

public String getProductprice() {
return productprice;
}

public void setProductprice(String productprice) {
this.productprice = productprice;
}

public String idno="", productname="", productprice="";

public String getIdno() {
return idno;
}

public void setIdno(String idno) {
this.idno = idno;
}


}


SearchProduct.java

package com.samir;

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

import com.androidadvance.db.DatabaseHelper;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class SearchProduct extends Activity implements TextWatcher {
EditText _searchbox;
private ProgressBar showprogress;
searchtask dotask;
private ArrayList<ProductModel> _productList;
ListView _listview;
DatabaseHelper db;
public AutoCompleteTextView myAutoComplete;
private ArrayList<ProductModel> _productList_Temp;
String query = "";
ArrayList<ProductModel> modelarray;

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

db = new DatabaseHelper(getApplicationContext());
db.getWritableDatabase();
modelarray=new ArrayList<ProductModel>();
modelarray.clear();
modelarray = db.getProudcts();

Log.e("-----size-----", "-----size-----" + modelarray.size());

db.close();
_searchbox = (EditText) findViewById(R.id.txtsearchproduct);
showprogress = (ProgressBar) findViewById(R.id.showprogress);
_listview = (ListView) findViewById(R.id.searchlistview);
_searchbox.addTextChangedListener(textwatcher);

}

Runnable runn = new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub
handlersearch.sendEmptyMessage(0);
}
};
TextWatcher textwatcher = new TextWatcher() {

public void onTextChanged(CharSequence s, int start, int before,
int count) {
Log.i("---onTextChanged ----", "---------onTextChanged ----");

if (_searchbox.getText().toString().length() > 1) {
query = _searchbox.getText().toString().replace(" ", "%20");

handlersearch.removeCallbacks(runn);
handlersearch.post(runn);

} else {
showprogress.setVisibility(View.GONE);

if (dotask != null) {
if (dotask.getStatus().equals(AsyncTask.Status.RUNNING)) {
dotask.cancel(true);
}
}

handlersearch.removeCallbacks(runn);

_productList = new ArrayList<ProductModel>();
_productList.clear();
_listview.setAdapter(new CustomBaseAdapter(SearchProduct.this,
_productList));
}

}

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

}

public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub

}
};

Handler handlersearch = new Handler() {

public void handleMessage(android.os.Message msg) {
dotask = new searchtask();
dotask.execute();
};
};

private class searchtask extends AsyncTask<Void, Void, Void> {

protected void onPreExecute() {

showprogress.setVisibility(View.VISIBLE);
};

protected void onPostExecute(Void param) {
// animation.dismiss();
showprogress.setVisibility(View.GONE);
if (_productList == null)
return;

ArrayList<String> item = new ArrayList<String>();

for (int i = 0; i < _productList.size(); i++) {
item.add(_productList.get(i).productname);
}

myAutoComplete = (AutoCompleteTextView) findViewById(R.id.myautocomplete);

myAutoComplete.addTextChangedListener(SearchProduct.this);

myAutoComplete.setAdapter(new ArrayAdapter<String>(
SearchProduct.this,
android.R.layout.simple_dropdown_item_1line, item));

_productList_Temp = new ArrayList<ProductModel>();

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

_productList_Temp.add(_productList.get(i));

}

_listview.setAdapter(new CustomBaseAdapter(SearchProduct.this,
_productList_Temp));

}

@Override
protected Void doInBackground(Void... params) {

db = new DatabaseHelper(getApplicationContext());
db.getWritableDatabase();
ArrayList<ProductModel> product_list = db.getProudcts(query);
System.out.println("product_list.size>>>>>" + product_list.size());

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

String tidno = product_list.get(i).getIdno();

System.out.println("tidno>>>>>" + tidno);
String tname = product_list.get(i).getProductname();
String tprice = product_list.get(i).getProductprice();

ProductModel _ProductModel = new ProductModel();

_ProductModel.setIdno(tidno);
_ProductModel.setProductname(tname);
_ProductModel.setProductprice(tprice);

_productList.add(_ProductModel);
}
// _productList = _parser.getProductList();

return null;
}

}

private class CustomBaseAdapter extends BaseAdapter {
LayoutInflater _inflater;

List<ProductModel> productList;

public CustomBaseAdapter(Context context, List<ProductModel> productList) {
_inflater = LayoutInflater.from(context);
this.productList = productList;

}

public int getCount() {
// TODO Auto-generated method stub
return productList.size();
}

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

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

public View getView(int position, View convertView, ViewGroup parent) {

ViewHolder _holder;
if (convertView == null) {

convertView = _inflater.inflate(R.layout.product_list, null);
_holder = new ViewHolder();

_holder.title = (TextView) convertView
.findViewById(R.id.txt_title_text);
_holder.price = (TextView) convertView
.findViewById(R.id.txt_price);

convertView.setTag(_holder);
} else {
_holder = (ViewHolder) convertView.getTag();
}

_holder.title.setText(productList.get(position).productname.trim());

_holder.price.setText(productList.get(position).productprice);

return convertView;
}

private class ViewHolder {
TextView title;
TextView price;
}
}

@Override
public void afterTextChanged(Editable arg0) {
// 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 onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub

}
}


Utils.java

package com.samir;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class Utils {
public static String getJSONString(String url) {
String jsonString = null;
HttpURLConnection linkConnection = null;
try {
URL linkurl = new URL(url);
linkConnection = (HttpURLConnection) linkurl.openConnection();
int responseCode = linkConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream linkinStream = linkConnection.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int j = 0;
while ((j = linkinStream.read()) != -1) {
baos.write(j);
}
byte[] data = baos.toByteArray();
jsonString = new String(data);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (linkConnection != null) {
linkConnection.disconnect();
}
}
return jsonString;
}

public static boolean isNetworkAvailable(Activity activity) {
ConnectivityManager connectivity = (ConnectivityManager) activity
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
return false;
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}

}



DatabaseHelper.java

package com.androidadvance.db;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import com.samir.ProductModel;

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


public class DatabaseHelper extends SQLiteOpenHelper {

public static String DATABASENAME = "androidadvancesqlite";
public static String PRODUCTTABLE = "products";
public static String colProductId = "id";
public static String _colProductid = "productidno";
public static String colProductName = "productname";
public static String colProductPrice = "productprice";
private ArrayList<ProductModel> cartList = new ArrayList<ProductModel>();
Context c;

public DatabaseHelper(Context context) {
super(context, DATABASENAME, null, 33);
c = context;
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE if not exists producttable(id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "productidno"
+ " TEXT ,"
+ "productname"
+ " TEXT,"
+ "productprice" + " TEXT)");

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" + PRODUCTTABLE);
onCreate(db);
}

public void addProduct(ProductModel productitem) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("productidno", productitem.idno);
contentValues.put("productname", productitem.productname);
contentValues.put("productprice", productitem.productprice);
db.insert("producttable", null, contentValues);
Log.e("-----size-----", "-----size-----" + productitem.productname);
db.close();

}

// update

public void updateProduct(ProductModel productList) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("productname", productList.productname);

contentValues.put("productprice", productList.productprice);
db.update("producttable", contentValues, "productidno="
+ productList.idno, null);

db.close();
}

public void emptyProduct() {
try {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from producttable");
db.close();
} catch (Exception e) {
e.printStackTrace();
}
}

public void removeProduct(String productname) {
try {
String[] args = { productname };
getWritableDatabase().delete("producttable", "productname=?", args);

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

public ArrayList<ProductModel> getProudcts() {

cartList.clear();

SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select * from producttable", null);
if (cursor.getCount() != 0) {
if (cursor.moveToFirst()) {
do {
ProductModel item = new ProductModel();

item.idno = cursor.getString(cursor
.getColumnIndex("productidno"));

item.productname = cursor.getString(cursor
.getColumnIndex("productname"));

item.productprice = cursor.getString(cursor
.getColumnIndex("productprice"));

cartList.add(item);

} while (cursor.moveToNext());
}
}
cursor.close();
db.close();
return cartList;
}

public ArrayList<ProductModel> getProudcts(String record) {

cartList.clear();

SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.query(true, "producttable", new String[] {
"productidno", "productname", "productprice" }, "productname"
+ "=?", new String[] { record }, null, null, null, null);

if (cursor.getCount() != 0) {
if (cursor.moveToFirst()) {
do {
ProductModel item = new ProductModel();

item.idno = cursor.getString(cursor
.getColumnIndex("productidno"));

item.productname = cursor.getString(cursor
.getColumnIndex("productname"));

item.productprice = cursor.getString(cursor
.getColumnIndex("productprice"));

cartList.add(item);

} while (cursor.moveToNext());
}
}
cursor.close();
db.close();
return cartList;
}
}


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="fill_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/listview"  android:layout_weight="1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        >
    </ListView>
    
    <Button  android:text="search" android:onClick="Search"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        />
    <Button  android:text="update"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        />
    </LinearLayout>

product_list.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/category_list_id"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/white"
    android:paddingBottom="1dp" >

    <LinearLayout
        android:id="@+id/ll_place_name_use"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"
        android:orientation="vertical"
        android:paddingRight="8dp" >

        <TextView
            android:id="@+id/txt_title_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:maxLines="3"
            android:padding="2dp"
            android:text="aaa"
            android:textColor="@android:color/black"
            android:textSize="16sp"
            android:textStyle="bold" >
        </TextView>

        <TextView
            android:id="@+id/txt_price"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:padding="2dp"
            android:text="1000"
            android:textColor="@android:color/black"
            android:textSize="14sp"
            android:visibility="visible" >
        </TextView>
    </LinearLayout>

</RelativeLayout>

row.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/relativelay"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/list_bg"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tvname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="5dip"
        android:maxLines="1"
        android:text=""
        android:textColor="@android:color/black"
        android:textSize="14dp"
        android:textStyle="bold" >
    </TextView>

    <TextView
        android:id="@+id/tvcity"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/tvname"
        android:layout_marginLeft="5dip"
        android:layout_marginTop="3dip"
        android:maxLines="1"
        android:text=""
        android:textColor="@android:color/black"
        android:textSize="14dp" >
    </TextView>

    <TextView
        android:id="@+id/tvbdate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/tvcity"
        android:layout_marginLeft="5dip"
        android:layout_marginTop="3dip"
        android:maxLines="1"
        android:text=""
        android:textColor="@android:color/black"
        android:textSize="14dp" >
    </TextView>

    <TextView
        android:id="@+id/tvgender"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginRight="15dip"
        android:maxLines="1"
        android:text=""
        android:textColor="@android:color/black"
        android:textSize="14dp"
        android:textStyle="bold" >
    </TextView>

    <TextView
        android:id="@+id/tvage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/tvgender"
        android:layout_marginRight="15dip"
        android:layout_marginTop="3dip"
        android:maxLines="1"
        android:text=""
        android:textColor="@android:color/black"
        android:textSize="14dp" >
    </TextView>

</RelativeLayout>

searchproduct.xml


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

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

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="15dp"
            android:layout_marginTop="10dp"
            android:layout_weight="1"
            android:gravity="center"
            android:text="Search Record"
            android:textSize="18dp"
            android:textStyle="bold" />

        <ProgressBar
            android:id="@+id/showprogress"
            style="?android:attr/progressBarStyleSmall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:paddingRight="10dp"
            android:visibility="gone" />
    </LinearLayout>

    <EditText
        android:id="@+id/txtsearchproduct"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="search"
        android:lines="1"
        android:paddingLeft="25dp"
        android:visibility="visible" >
    </EditText>

    <AutoCompleteTextView
        android:id="@+id/myautocomplete"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:completionThreshold="1"
        android:hint="search"
        android:lines="1"
        android:visibility="gone" />

    <ListView
        android:id="@+id/searchlistview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>



Download Source Code

Sunday, 27 October 2013

How to call HTTPS webservices in android




For Example :

==> First call following method.

public static void trustAllHosts() {

        X509TrustManager easyTrustManager = new X509TrustManager() {

            public void checkClientTrusted(X509Certificate[] chain,
                    String authType) throws CertificateException {
                // Oh, I am easy!
            }

            public void checkServerTrusted(X509Certificate[] chain,
                    String authType) throws CertificateException {
                // Oh, I am easy!
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

        };

        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { easyTrustManager };

        // Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance("TLS");

            sc.init(null, trustAllCerts, new java.security.SecureRandom());

            HttpsURLConnection
                    .setDefaultSSLSocketFactory(sc.getSocketFactory());

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

====> After this


For calling HTTPS webservices you need to create Custom HttpClient instead of using DefaultHttpClient.


HttpClient _httpclient = Utils.getNewHttpClient();

Following is getNewHttpClient() method :



public static HttpClient getNewHttpClient() {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore
.getDefaultType());
trustStore.load(null, null);

SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));

ClientConnectionManager ccm = new ThreadSafeClientConnManager(
params, registry);

return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
return new DefaultHttpClient();
}
}


Here we have use custom MySSLSocketFactory class, which is following.

Create new class MySSLSocketFactory.java copy following code and paste.







public class MySSLSocketFactory extends SSLSocketFactory {
SSLContext sslContext = SSLContext.getInstance("TLS");

public MySSLSocketFactory(KeyStore truststore)
throws NoSuchAlgorithmException, KeyManagementException,
KeyStoreException, UnrecoverableKeyException {
super(truststore);

TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}

public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}

public X509Certificate[] getAcceptedIssuers() {
return null;
}
};

sslContext.init(null, new TrustManager[] { tm }, null);
}

@Override
public Socket createSocket(Socket socket, String host, int port,
boolean autoClose) throws IOException, UnknownHostException {
return sslContext.getSocketFactory().createSocket(socket, host, port,
autoClose);
}

@Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
}

Now done :) You can parse your xml now. 



Sunday, 11 August 2013

Using multiple text colors in Android's textview

I had faced on issue in my past project. How to set multiple colors in single textview ? For that I have solve it using following way.

    productprice.setText(Html.fromHtml("Price" + ": "
                    + "<font color=\"#990000\">"

                    + cartList.get(position).ProductPrice + " " + "</font>"));


productprice is TextView, set   android:textColor as default color for Textview.


Hope it helps you also.

Wednesday, 1 May 2013

What does “xmlns” in Android XML mean?

Generally we write following line in android xml file.
xmlns:android="http://schemas.android.com/apk/res/android"

 It defines XML Namespace.

The Namespace Prefix is "android" and the Namespace URI is "http://schemas.android.com/apk/res/android"

Basically, every element (or attribute) in xml belongs to a namespace, a way of "qualifying" the name of the element.

Example :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

Wednesday, 17 April 2013

Select + copy text in a TextView?

 Generally we can copy / paste the value from EditText by long click. It is in-build functionality of Android. Now lets say you have requirement same thing in TextView. Then you have to use registerForContextMenu.


 Like  registerForContextMenu(yourtextview);

 and your TextView will be registered for receiving context menu events.

Then You have to override onCreateContextMenu() method. Following is entire code.


 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        txtcopytext = (TextView) findViewById(R.id.txtcopytext);
        registerForContextMenu(txtcopytext);

    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        // user has long pressed your TextView
        menu.add(0, v.getId(), 0,
                "Copy");

        // cast the received View to TextView so that you can get its text
        TextView yourTextView = (TextView) v;

        // place your TextView's text in clipboard
        ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        clipboard.setText(yourTextView.getText());
    }