AdvancedListViewActivity.java
import android.app.ListActivity;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.os.Bundle;
public class AdvancedListViewActivity extends ListActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Context ctx = getApplicationContext();
Resources res = ctx.getResources();
String[] options = res.getStringArray(R.array.country_names);
TypedArray icons = res.obtainTypedArray(R.array.country_icons);
setListAdapter(new ImageAndTextAdapter(ctx, R.layout.main_list_item,
options, icons));
}
}
ImageAndTextAdapter.java
import android.content.Context;
import android.content.res.TypedArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class ImageAndTextAdapter extends ArrayAdapter<String> {
private LayoutInflater mInflater;
private String[] mStrings;
private TypedArray mIcons;
private int mViewResourceId;
public ImageAndTextAdapter(Context ctx, int viewResourceId,
String[] strings, TypedArray icons) {
super(ctx, viewResourceId, strings);
mInflater = (LayoutInflater)ctx.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
mStrings = strings;
mIcons = icons;
mViewResourceId = viewResourceId;
}
@Override
public int getCount() {
return mStrings.length;
}
@Override
public String getItem(int position) {
return mStrings[position];
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mInflater.inflate(mViewResourceId, null);
ImageView iv = (ImageView)convertView.findViewById(R.id.option_icon);
iv.setImageDrawable(mIcons.getDrawable(position));
TextView tv = (TextView)convertView.findViewById(R.id.option_text);
tv.setText(mStrings[position]);
return convertView;
}
}
main_list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:id="@+id/option_icon"
android:layout_width="48dp"
android:layout_height="fill_parent"/>
<TextView
android:id="@+id/option_text"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16dp" >
</TextView>
</LinearLayout>
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ListView android:id="@android:id/list"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
/>
</LinearLayout>
Countries.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="country_names">
<item>Bhutan</item>
<item>Colombia</item>
<item>Italy</item>
<item>Jamaica</item>
<item>Kazakhstan</item>
<item>Kenya</item>
</string-array>
<array name="country_icons">
<item>@drawable/bhutan</item>
<item>@drawable/colombia</item>
<item>@drawable/italy</item>
<item>@drawable/jamaica</item>
<item>@drawable/kazakhstan</item>
<item>@drawable/kenya</item>
</array>
</resources>
Friday, October 28, 2011
how to make http request from android client ,parese json response and add the data into local db
//gettin my splisttfrom server
String getMySPListFromServer(String key) {
String getMySPList=null;
mDBHelper =mAppMgr.getDbHelper();
getMySPList=connect("http://50.28.26.182:8080/SMS/spList?sessionId="+mSessionId+"&client_type=mc&catalog_version_id=0&profile_id="+key);
String status=JSONSMParser.parseStatus(getMySPList);
Log.d("splist",getMySPList);
if(status.equals("200")){
mMySPProfiles=JSONSMParser.parseMySPList(getMySPList);
createMySPProfiles( mDBHelper,key);
Log.e(TAG+"created profiles","profiles");
return status;
}
else
return status;
}
/**
* This method connects to server through HTTP request .
*/
private static String connect(String url){
// Create the httpclient
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
// return string
String returnString = null;
try {
// Open the webpage.
response = httpclient.execute(httpget);
// if(response.getStatusLine().getStatusCode() == 200){
if(true) {
// Connection was established. Get the content.
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
// Load the requested page converted to a string into a JSONObject.
// JSONObject myAwway = new JSONObject(convertStreamToString(instream));
returnString = convertStreamToString(instream);
// Log.e(TAG,"instream : "+convertStreamToString(instream));
// Log.e(TAG,"myawway : "+ myAwway);
// Get the query value'
//String query = myAwway.getString("query");
// JSONObject menuObject =myAwway.getJSONObject("photos");
// Make array of the suggestions
// JSONArray suggestions =menuObject.getJSONArray("photo");
// Build the return string.
// returnString = "Found: " + suggestions.length() ;
// for (int i = 0; i < suggestions.length(); i++) {
// returnString += "\n\t" +(suggestions.getJSONObject(i).getString("id").toString());
// }
// returnString = "Found";
// Cose the stream.
instream.close();
}
}
else {
// code here for a response othet than 200. A response 200 means the webpage was ok
// Other codes include 404 - not found, 301 - redirect etc...
// Display the response line.
returnString = "Unable to load page - " + response.getStatusLine();
}
return returnString ;
}
catch (IOException ex) {
// thrown by line 80 - getContent();
// Connection was not established
returnString = "Connection failed; " + ex.getMessage();
}
// catch (JSONException ex){
// JSON errors
// returnString = "JSON failed; " + ex.getMessage();
// }
return returnString;
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Log.e(TAG,"sb string : "+ sb.toString());
return sb.toString();
}
/**
* method to parse login status coming from server
*
*/
public static String parseStatus(String jsonString) {
String login_statuscode=null;
String status_msg=null;
try {
JSONObject jObject = new JSONObject(jsonString);
login_statuscode=jObject.getString("status_code");
status_msg=jObject.getString("status_msg");
Log.d("login status", ""+jObject.getString("status_code"));
}
catch (JSONException e) {
e.printStackTrace();
}
return login_statuscode;
}
public static List<ServiceProvider> parseMySPList(String jsonString) {
mMyProlist = new ArrayList<ServiceProvider>();
try {
int noOfUserComments;
int noOfEmailids;
int noOfPhnos;
int noOfServices;
JSONObject jObject = new JSONObject(jsonString);
JSONArray menuitemArray1 = jObject.getJSONArray("MyServiceProvider");
/*
{"MyServiceProvider":[["2002_chakri_edu","Chakrapani","Chakrapani provides technical guidance for CSE Students
","India","hyderabad","4","0","Chakrapani","ICICI","12345555555",[["54843958"]],[["chakri@gmail.com"]],
[[null]],[["7001","100.0","Teaches Computer Engineering Subjects","Computer Engineering by Chakri"]]],[
"2010_sumir_medical","Sumir Bharathi","Sumir provides services on psychology","india","hyderabad","4","0",
"Sumir Bharathi","ICICI","4543759459",[["4358345"]],[["sumir@gmail.com"]]
,[[null]],[["7009","67.89","This course provides introduction to psychology","psychology_introductory_lectur"]]]]}
*/
Log.d("",""+menuitemArray1.length());
UserComments userComments;
Phnos pHno;
ArrayList<UserComments> usercommentsList=new ArrayList<UserComments>();
ArrayList<Phnos> PhnosList=new ArrayList<Phnos>();
Service1 service;
ArrayList<Service1> servicesList=new ArrayList<Service1>();
EmailIds emailid;
ArrayList<EmailIds> emailidList=new ArrayList<EmailIds>();
for(int i=0 ;i<menuitemArray1.length();i++){
ServiceProvider pfl=new ServiceProvider();
JSONArray tempArray = menuitemArray1.getJSONArray(i);
Log.e("menuitemArray1 size",""+menuitemArray1.length());
Log.e("tempArray.length()",""+tempArray.length());
int j=0;
int k=0;
Log.d("Myspdetails", tempArray.getString(k));
Log.d("Myspdetails", tempArray.getString(++k));
Log.d("Myspdetails", tempArray.getString(++k));
Log.d("Myspdetails", tempArray.getString(++k));
Log.d("Myspdetails", tempArray.getString(++k));
Log.d("Myspdetails", tempArray.getString(++k));
Log.d("Myspdetails", tempArray.getString(++k));
Log.d("Myspdetails", tempArray.getString(++k));
Log.d("Myspdetails", tempArray.getString(++k));
Log.d("Myspdetails", tempArray.getString(++k));
//Log.d("user comments size", tempArray.getString(++k));
k=0;
pfl.profile_id=tempArray.getString(k);
pfl.profile_name=tempArray.getString(++k);
pfl.profile_des=tempArray.getString(++k);
pfl.country=tempArray.getString(++k);
pfl.city=tempArray.getString(++k);
pfl.rating=tempArray.getString(++k);
pfl.is_online=tempArray.getString(++k);
pfl.acname=tempArray.getString(++k);
pfl.bankname=tempArray.getString(++k);
pfl.acno=tempArray.getString(++k);
// noOfUserComments = Integer.parseInt(tempArray.getString(++k));
JSONArray tempArray3 =tempArray.getJSONArray(++k);
for( j=0; j<tempArray3.length(); j++){
JSONArray tempArray31 =tempArray3.getJSONArray(j);
pHno=new Phnos(null);
int l=0;
pHno.phno=tempArray31.getString(l);
pHno.profileid=pfl.profile_id;
Log.e("pHno.profileid",""+pHno.profileid);
Log.e("pHno.phno",""+pHno.phno);
PhnosList.add(pHno);
}
JSONArray tempArray4=tempArray.getJSONArray(++k);
for( j=0; j<tempArray4.length(); j++){
JSONArray tempArray41 =tempArray4.getJSONArray(j);
emailid=new EmailIds();
int l=0;
emailid.emailid = tempArray41.getString(l);
emailid.profileid=pfl.profile_id;
Log.e("emailid.profilrid",""+emailid.profileid);
Log.e("emailid.emailid",""+emailid.emailid);
emailidList.add(emailid);
}
JSONArray tempArray1 =tempArray.getJSONArray(++k);
for( j=0; j<tempArray1.length(); j++){
JSONArray tempArray11 =tempArray1.getJSONArray(j);
userComments=new UserComments();
int l=0;
userComments.userComments = tempArray11.getString(l);
userComments.profileid=pfl.profile_id;
Log.e("userComments.profileid",""+userComments.profileid);
Log.e("userComments.userComments",""+userComments.userComments);
usercommentsList.add( userComments);
}
JSONArray tempArray2 =tempArray.getJSONArray(++k);
for( j=0; j<tempArray2.length(); j++){
JSONArray tempArray21 =tempArray2.getJSONArray(j);
int l=0;
service=new Service1();
service.sp_profile_id=pfl.profile_id;
service.service_id = tempArray21.getString(l);
Log.e("service.sp_profile_id",""+service.sp_profile_id);
Log.e("service.service_id",""+service.service_id);
service.service_charge = tempArray21.getString(++l);
Log.e("service_charge",""+service.service_charge);
service.service_name= tempArray21.getString(++l);
service.service_des= tempArray21.getString(++l);
servicesList.add(service);
}
pfl.usercommentsList=usercommentsList;
pfl.phnoList=PhnosList;
pfl.serviceList=servicesList;
pfl.email_idList=emailidList;
mMyProlist.add(pfl);
}
} catch (JSONException e) {
e.printStackTrace();
}
return mMyProlist;
}
public static void createMySPProfiles(DatabaseHelper mDBHelper, String key) {
SQLiteDatabase database = mDBHelper.getWritableDatabase();
ContentValues valueph= new ContentValues();
ContentValues valuemailid= new ContentValues();
ContentValues values3 = new ContentValues();
ContentValues nuprofiles= new ContentValues();
ContentValues valuecomments = new ContentValues();
database.execSQL("delete from nu_subscriptions");
int j=0;
int i =0;
database.execSQL("delete from SM_profile1 ");
Log.e(TAG+"all records deleted ","from SM_profile1");
ContentValues valueser = new ContentValues();
for(;i<mMySPProfiles.size();i++){
String profile_id = mMySPProfiles.get(i).profile_id;
// String category_id = mProfiles.get(i).category_id;
String profile_name=mMySPProfiles.get(i).profile_name;
//String profile_des = mProfiles.get(i).profile_des;
String country=mMySPProfiles.get(i).country;
String city = mMySPProfiles.get(i).city;
String acno=mMySPProfiles.get(i).acno;
String acname=mMySPProfiles.get(i).acname;
String bankname=mMySPProfiles.get(i).bankname;
String rating=mMySPProfiles.get(i).rating;
// String service_id=mProfiles.get(i).service_id;
String is_online=mMySPProfiles.get(i).is_online;
Log.d("profile_id",""+profile_id);
values3.put("profile_id",profile_id);
values3.put("is_online",is_online);
Log.d("profile_name",""+profile_name);
values3.put("profile_name",profile_name);
values3.put("acno",acno);
values3.put("acname",acname);
values3.put("bankname",bankname);
values3.put("country",country);
values3.put("city",city);
values3.put("rating",rating);
//values3.put("videoid",videoid);
database.insert("SM_profile1", null, values3);
}
i=0;
ArrayList<UserComments> usercomments = mMySPProfiles.get(i).usercommentsList;
ArrayList<Service1>serviceList=mMySPProfiles.get(i).serviceList;
ArrayList<EmailIds> emailList=mMySPProfiles.get(i).email_idList;
Log.e("emailList",""+emailList.size());
ArrayList<Phnos> phNoList=mMySPProfiles.get(i).phnoList;
Log.e(" phNoList",""+ phNoList.size());
database.execSQL("delete from SM_email_id1");
database.execSQL("delete from SM_phone_numbers");
for(j=0;j<usercomments.size();j++)
{
String userComments=usercomments.get(j).userComments;
String sp_profile_id = usercomments.get(j).profileid;
String profileid=sp_profile_id;
valuecomments .put("profile_id",sp_profile_id);
valuecomments .put("user_comments",userComments );
database.insert("SM_user_comments1", null,valuecomments);
}
for(j=0;j<emailList.size();j++)
{
String emailid=emailList.get(j).emailid;
String sp_profile_id =emailList.get(j).profileid;
//String profileid=profile_id;
valuemailid.put("profile_id", sp_profile_id);
valuemailid.put("email_id",emailid);
database.insert("SM_email_id1", null,valuemailid);
}
for(j=0;j<phNoList.size();j++)
{
//String sp_profile_id = mMySPProfiles.get(i).profile_id;
String phNo=phNoList.get(j).phno;
String profileid=phNoList.get(j).profileid;
valueph.put("profile_id",profileid);
valueph.put("contact_number",phNo);
database.insert("SM_phone_numbers", null,valueph);
}
for(j=0;j<serviceList.size();j++)
{
String sp_profile_id = serviceList.get(j).sp_profile_id;
String service_id=serviceList.get(j).service_id;
String service_name=serviceList.get(j).service_name;
// String service_des=serviceList.get(j).service_des;
String service_charge=serviceList.get(j).service_charge;
Log.e("sp_profile_id",""+sp_profile_id);
valueser.put("sp_profile_id",sp_profile_id);
valueser.put("service_id",service_id);
valueser.put("service_name",service_name);
Log.e(TAG,""+service_name);
// valueser.put("service_description",service_des);
valueser.put("service_charge",service_charge);
Log.e(TAG,""+service_charge);
valueser.put("nu_profile_id",key);
database.insert("nu_subscriptions", null,valueser);
}
//Log.e(TAG+"mMySPProfiles.size()",""+mMySPProfiles.size());
}
String getMySPListFromServer(String key) {
String getMySPList=null;
mDBHelper =mAppMgr.getDbHelper();
getMySPList=connect("http://50.28.26.182:8080/SMS/spList?sessionId="+mSessionId+"&client_type=mc&catalog_version_id=0&profile_id="+key);
String status=JSONSMParser.parseStatus(getMySPList);
Log.d("splist",getMySPList);
if(status.equals("200")){
mMySPProfiles=JSONSMParser.parseMySPList(getMySPList);
createMySPProfiles( mDBHelper,key);
Log.e(TAG+"created profiles","profiles");
return status;
}
else
return status;
}
/**
* This method connects to server through HTTP request .
*/
private static String connect(String url){
// Create the httpclient
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
// return string
String returnString = null;
try {
// Open the webpage.
response = httpclient.execute(httpget);
// if(response.getStatusLine().getStatusCode() == 200){
if(true) {
// Connection was established. Get the content.
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
// Load the requested page converted to a string into a JSONObject.
// JSONObject myAwway = new JSONObject(convertStreamToString(instream));
returnString = convertStreamToString(instream);
// Log.e(TAG,"instream : "+convertStreamToString(instream));
// Log.e(TAG,"myawway : "+ myAwway);
// Get the query value'
//String query = myAwway.getString("query");
// JSONObject menuObject =myAwway.getJSONObject("photos");
// Make array of the suggestions
// JSONArray suggestions =menuObject.getJSONArray("photo");
// Build the return string.
// returnString = "Found: " + suggestions.length() ;
// for (int i = 0; i < suggestions.length(); i++) {
// returnString += "\n\t" +(suggestions.getJSONObject(i).getString("id").toString());
// }
// returnString = "Found";
// Cose the stream.
instream.close();
}
}
else {
// code here for a response othet than 200. A response 200 means the webpage was ok
// Other codes include 404 - not found, 301 - redirect etc...
// Display the response line.
returnString = "Unable to load page - " + response.getStatusLine();
}
return returnString ;
}
catch (IOException ex) {
// thrown by line 80 - getContent();
// Connection was not established
returnString = "Connection failed; " + ex.getMessage();
}
// catch (JSONException ex){
// JSON errors
// returnString = "JSON failed; " + ex.getMessage();
// }
return returnString;
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Log.e(TAG,"sb string : "+ sb.toString());
return sb.toString();
}
/**
* method to parse login status coming from server
*
*/
public static String parseStatus(String jsonString) {
String login_statuscode=null;
String status_msg=null;
try {
JSONObject jObject = new JSONObject(jsonString);
login_statuscode=jObject.getString("status_code");
status_msg=jObject.getString("status_msg");
Log.d("login status", ""+jObject.getString("status_code"));
}
catch (JSONException e) {
e.printStackTrace();
}
return login_statuscode;
}
public static List<ServiceProvider> parseMySPList(String jsonString) {
mMyProlist = new ArrayList<ServiceProvider>();
try {
int noOfUserComments;
int noOfEmailids;
int noOfPhnos;
int noOfServices;
JSONObject jObject = new JSONObject(jsonString);
JSONArray menuitemArray1 = jObject.getJSONArray("MyServiceProvider");
/*
{"MyServiceProvider":[["2002_chakri_edu","Chakrapani","Chakrapani provides technical guidance for CSE Students
","India","hyderabad","4","0","Chakrapani","ICICI","12345555555",[["54843958"]],[["chakri@gmail.com"]],
[[null]],[["7001","100.0","Teaches Computer Engineering Subjects","Computer Engineering by Chakri"]]],[
"2010_sumir_medical","Sumir Bharathi","Sumir provides services on psychology","india","hyderabad","4","0",
"Sumir Bharathi","ICICI","4543759459",[["4358345"]],[["sumir@gmail.com"]]
,[[null]],[["7009","67.89","This course provides introduction to psychology","psychology_introductory_lectur"]]]]}
*/
Log.d("",""+menuitemArray1.length());
UserComments userComments;
Phnos pHno;
ArrayList<UserComments> usercommentsList=new ArrayList<UserComments>();
ArrayList<Phnos> PhnosList=new ArrayList<Phnos>();
Service1 service;
ArrayList<Service1> servicesList=new ArrayList<Service1>();
EmailIds emailid;
ArrayList<EmailIds> emailidList=new ArrayList<EmailIds>();
for(int i=0 ;i<menuitemArray1.length();i++){
ServiceProvider pfl=new ServiceProvider();
JSONArray tempArray = menuitemArray1.getJSONArray(i);
Log.e("menuitemArray1 size",""+menuitemArray1.length());
Log.e("tempArray.length()",""+tempArray.length());
int j=0;
int k=0;
Log.d("Myspdetails", tempArray.getString(k));
Log.d("Myspdetails", tempArray.getString(++k));
Log.d("Myspdetails", tempArray.getString(++k));
Log.d("Myspdetails", tempArray.getString(++k));
Log.d("Myspdetails", tempArray.getString(++k));
Log.d("Myspdetails", tempArray.getString(++k));
Log.d("Myspdetails", tempArray.getString(++k));
Log.d("Myspdetails", tempArray.getString(++k));
Log.d("Myspdetails", tempArray.getString(++k));
Log.d("Myspdetails", tempArray.getString(++k));
//Log.d("user comments size", tempArray.getString(++k));
k=0;
pfl.profile_id=tempArray.getString(k);
pfl.profile_name=tempArray.getString(++k);
pfl.profile_des=tempArray.getString(++k);
pfl.country=tempArray.getString(++k);
pfl.city=tempArray.getString(++k);
pfl.rating=tempArray.getString(++k);
pfl.is_online=tempArray.getString(++k);
pfl.acname=tempArray.getString(++k);
pfl.bankname=tempArray.getString(++k);
pfl.acno=tempArray.getString(++k);
// noOfUserComments = Integer.parseInt(tempArray.getString(++k));
JSONArray tempArray3 =tempArray.getJSONArray(++k);
for( j=0; j<tempArray3.length(); j++){
JSONArray tempArray31 =tempArray3.getJSONArray(j);
pHno=new Phnos(null);
int l=0;
pHno.phno=tempArray31.getString(l);
pHno.profileid=pfl.profile_id;
Log.e("pHno.profileid",""+pHno.profileid);
Log.e("pHno.phno",""+pHno.phno);
PhnosList.add(pHno);
}
JSONArray tempArray4=tempArray.getJSONArray(++k);
for( j=0; j<tempArray4.length(); j++){
JSONArray tempArray41 =tempArray4.getJSONArray(j);
emailid=new EmailIds();
int l=0;
emailid.emailid = tempArray41.getString(l);
emailid.profileid=pfl.profile_id;
Log.e("emailid.profilrid",""+emailid.profileid);
Log.e("emailid.emailid",""+emailid.emailid);
emailidList.add(emailid);
}
JSONArray tempArray1 =tempArray.getJSONArray(++k);
for( j=0; j<tempArray1.length(); j++){
JSONArray tempArray11 =tempArray1.getJSONArray(j);
userComments=new UserComments();
int l=0;
userComments.userComments = tempArray11.getString(l);
userComments.profileid=pfl.profile_id;
Log.e("userComments.profileid",""+userComments.profileid);
Log.e("userComments.userComments",""+userComments.userComments);
usercommentsList.add( userComments);
}
JSONArray tempArray2 =tempArray.getJSONArray(++k);
for( j=0; j<tempArray2.length(); j++){
JSONArray tempArray21 =tempArray2.getJSONArray(j);
int l=0;
service=new Service1();
service.sp_profile_id=pfl.profile_id;
service.service_id = tempArray21.getString(l);
Log.e("service.sp_profile_id",""+service.sp_profile_id);
Log.e("service.service_id",""+service.service_id);
service.service_charge = tempArray21.getString(++l);
Log.e("service_charge",""+service.service_charge);
service.service_name= tempArray21.getString(++l);
service.service_des= tempArray21.getString(++l);
servicesList.add(service);
}
pfl.usercommentsList=usercommentsList;
pfl.phnoList=PhnosList;
pfl.serviceList=servicesList;
pfl.email_idList=emailidList;
mMyProlist.add(pfl);
}
} catch (JSONException e) {
e.printStackTrace();
}
return mMyProlist;
}
public static void createMySPProfiles(DatabaseHelper mDBHelper, String key) {
SQLiteDatabase database = mDBHelper.getWritableDatabase();
ContentValues valueph= new ContentValues();
ContentValues valuemailid= new ContentValues();
ContentValues values3 = new ContentValues();
ContentValues nuprofiles= new ContentValues();
ContentValues valuecomments = new ContentValues();
database.execSQL("delete from nu_subscriptions");
int j=0;
int i =0;
database.execSQL("delete from SM_profile1 ");
Log.e(TAG+"all records deleted ","from SM_profile1");
ContentValues valueser = new ContentValues();
for(;i<mMySPProfiles.size();i++){
String profile_id = mMySPProfiles.get(i).profile_id;
// String category_id = mProfiles.get(i).category_id;
String profile_name=mMySPProfiles.get(i).profile_name;
//String profile_des = mProfiles.get(i).profile_des;
String country=mMySPProfiles.get(i).country;
String city = mMySPProfiles.get(i).city;
String acno=mMySPProfiles.get(i).acno;
String acname=mMySPProfiles.get(i).acname;
String bankname=mMySPProfiles.get(i).bankname;
String rating=mMySPProfiles.get(i).rating;
// String service_id=mProfiles.get(i).service_id;
String is_online=mMySPProfiles.get(i).is_online;
Log.d("profile_id",""+profile_id);
values3.put("profile_id",profile_id);
values3.put("is_online",is_online);
Log.d("profile_name",""+profile_name);
values3.put("profile_name",profile_name);
values3.put("acno",acno);
values3.put("acname",acname);
values3.put("bankname",bankname);
values3.put("country",country);
values3.put("city",city);
values3.put("rating",rating);
//values3.put("videoid",videoid);
database.insert("SM_profile1", null, values3);
}
i=0;
ArrayList<UserComments> usercomments = mMySPProfiles.get(i).usercommentsList;
ArrayList<Service1>serviceList=mMySPProfiles.get(i).serviceList;
ArrayList<EmailIds> emailList=mMySPProfiles.get(i).email_idList;
Log.e("emailList",""+emailList.size());
ArrayList<Phnos> phNoList=mMySPProfiles.get(i).phnoList;
Log.e(" phNoList",""+ phNoList.size());
database.execSQL("delete from SM_email_id1");
database.execSQL("delete from SM_phone_numbers");
for(j=0;j<usercomments.size();j++)
{
String userComments=usercomments.get(j).userComments;
String sp_profile_id = usercomments.get(j).profileid;
String profileid=sp_profile_id;
valuecomments .put("profile_id",sp_profile_id);
valuecomments .put("user_comments",userComments );
database.insert("SM_user_comments1", null,valuecomments);
}
for(j=0;j<emailList.size();j++)
{
String emailid=emailList.get(j).emailid;
String sp_profile_id =emailList.get(j).profileid;
//String profileid=profile_id;
valuemailid.put("profile_id", sp_profile_id);
valuemailid.put("email_id",emailid);
database.insert("SM_email_id1", null,valuemailid);
}
for(j=0;j<phNoList.size();j++)
{
//String sp_profile_id = mMySPProfiles.get(i).profile_id;
String phNo=phNoList.get(j).phno;
String profileid=phNoList.get(j).profileid;
valueph.put("profile_id",profileid);
valueph.put("contact_number",phNo);
database.insert("SM_phone_numbers", null,valueph);
}
for(j=0;j<serviceList.size();j++)
{
String sp_profile_id = serviceList.get(j).sp_profile_id;
String service_id=serviceList.get(j).service_id;
String service_name=serviceList.get(j).service_name;
// String service_des=serviceList.get(j).service_des;
String service_charge=serviceList.get(j).service_charge;
Log.e("sp_profile_id",""+sp_profile_id);
valueser.put("sp_profile_id",sp_profile_id);
valueser.put("service_id",service_id);
valueser.put("service_name",service_name);
Log.e(TAG,""+service_name);
// valueser.put("service_description",service_des);
valueser.put("service_charge",service_charge);
Log.e(TAG,""+service_charge);
valueser.put("nu_profile_id",key);
database.insert("nu_subscriptions", null,valueser);
}
//Log.e(TAG+"mMySPProfiles.size()",""+mMySPProfiles.size());
}
Some of important SQlite queries in android
/**
* method that get category data from database table
*
*/
public ArrayList<String>getCategories(){
SQLiteDatabase database = this.getWritableDatabase();
ArrayList<String> results = new ArrayList<String>();
Cursor data = database.rawQuery("SELECT category_name from catalog2 where parent_id=0;",null);
if (data != null)
{
Log.d("database",database.toString());
if (data.moveToFirst())
{
do
{
String catagoryName = data.getString(data.getColumnIndex("category_name"));
Log.e("catagery name",""+catagoryName);
results.add(catagoryName );
} while (data.moveToNext());
}
data.close();
return results;
}
else
return null;
}
/**
* method that get sub-category from database table, here we passing categoryName which search in catlog2 table and returns category_id, from it we search all these data from catlog table ie [category_name,category_id,parent_id, is_leaf]
*
*/
public ArrayList<Category>getSubCategories( CharSequence categoryName){
ArrayList<Category> results = new ArrayList<Category>();
SQLiteDatabase database = this.getWritableDatabase();
String parent=null;
Cursor data = database.query("catalog2", new String[] {"category_id"},new String("category_name"+"=?"),new String[]{categoryName.toString()}, null, null, null);
if (data.moveToFirst())
{
{
parent = data.getString(data.getColumnIndex("category_id"));
Log.e("parent",""+parent);
}
}
data.close();
data = database.rawQuery("SELECT category_name,category_id,parent_id, is_leaf from catalog2 where parent_id="+parent,null);
if (data.moveToFirst())
{
do
{
String category_id=data.getString(data.getColumnIndex("category_id"));
String catagoryName = data.getString(data.getColumnIndex("category_name"));
String parent_id = data.getString(data.getColumnIndex("parent_id"));
String isleaf=data.getString(data.getColumnIndex("is_leaf"));
Category c=new Category();
c.category_name=catagoryName;
Log.e("catagoryName",""+catagoryName);
c.category_id=category_id;
c.is_leaf=isleaf;
c.parent_id=parent_id;
results.add(c);
} while (data.moveToNext());
}
data.close();
database.close();
return results;
}
Code for getting multiple table data :
/**
* method that get service provider profile from database table
*
*/
public ArrayList<ServiceProvider> getProviderProfiles(String profile_id){
ArrayList<ServiceProvider> profiles = new ArrayList<ServiceProvider>();
SQLiteDatabase database = this.getWritableDatabase();
ArrayList<UserComments> usercommentsList=new ArrayList<UserComments>();
UserComments userComments;
EmailIds emailid;
ArrayList<EmailIds> emailidList=new ArrayList<EmailIds>();
String sp_profileid=null;
Service1 service;
ArrayList<Service1> servicesList=new ArrayList<Service1>();
ArrayList<Phnos> PhnosList=new ArrayList<Phnos>();
Phnos pHno;
Log.e("nu_profileid",""+profile_id);
// Cursor data2 =database.rawQuery("SELECT * form nu_subscriptions where nu_profile_id="+profile_id,null);
Cursor data2 = database.query("nu_subscriptions", new String[] {"sp_profile_id"},new String("nu_profile_id"+"=?"),new String[]{profile_id.toString()}, null, null, null);
if (data2!= null)
{
// Log.d(TAG+"database",database.toString());
if (data2.moveToFirst()){
do{
sp_profileid=data2.getString(data2.getColumnIndex("sp_profile_id"));
Log.e("sp_profileid",""+sp_profileid);
//Cursor data1 = database.rawQuery("select profile_name,profile_des,country,city,profile_id,rating,is_online,acno,bankname, acname from SM_profile1 where profile_id="+sp_profileid, null);
Cursor data1=database.query("SM_profile1", new String[] {"profile_name","profile_des","country","city","profile_id","rating","is_online","acno","bankname", "acname"},new String("profile_id"+"=?"),new String[]{sp_profileid.toString()}, null, null, null);
Cursor data4 = database.query("SM_email_id1", new String[] {"email_id"},new String("profile_id"+"=?"),new String[]{sp_profileid.toString()}, null, null, null);
Cursor data5 = database.query("SM_phone_numbers", new String[] {"contact_number"},new String("profile_id"+"=?"),new String[]{sp_profileid.toString()}, null, null, null);
Cursor data3 = database.query("SM_user_comments1", new String[] {"user_comments"},new String("profile_id"+"=?"),new String[]{sp_profileid.toString()}, null, null, null);
Cursor data6 = database.query("nu_subscriptions", new String[] {"service_id","service_name" ,"service_charge","sp_profile_id"},new String("sp_profile_id"+"=?"),new String[]{sp_profileid.toString()}, null, null, null);
ServiceProvider pf=new ServiceProvider();
if (data6.moveToFirst()){
do{
// servicesList=new ArrayList<Service1>();
//servicesList.clear();
String service_id= data6.getString(data6.getColumnIndex("service_id"));
Log.e("service_id",""+service_id);
String service_name= data6.getString(data6.getColumnIndex("service_name"));
String sp_profile_id= data6.getString(data6.getColumnIndex("sp_profile_id"));
//String payment_timestamp= data2.getString(data2.getColumnIndex("payment_timestamp"));
String service_charge= data6.getString(data6.getColumnIndex("service_charge"));
service=new Service1();
service.service_id =service_id ;
service.service_charge = service_charge;
service.service_name= service_name;
service.sp_profile_id=sp_profile_id;
// service.service_des= service_des;
servicesList.add(service);
pf.serviceList=servicesList;
//pf.serviceList.clear();
Log.e(TAG,""+pf.serviceList.size());
for(int i=0;i<pf.serviceList.size();i++){
Log.e(TAG,pf.serviceList.get(i).service_id);
}
}while (data6.moveToNext());
}
if (data4.moveToFirst()){
String emailid1=data4.getString(data4.getColumnIndex("email_id"));
emailid=new EmailIds();
Log.e(" emailid", emailid1);
emailid.emailid =emailid1;
emailidList.add(emailid);
pf.email_idList=emailidList;
}
if (data5.moveToFirst()){
String contactnumber=data5.getString(data5.getColumnIndex("contact_number"));
pHno=new Phnos(null);
Log.e("contactnumber",contactnumber);
pHno.phno =contactnumber;
PhnosList.add(pHno);
pf.phnoList=PhnosList;
}
if (data3.moveToFirst())
{
String userComment1=data3.getString(data3.getColumnIndex("user_comments"));
userComments=new UserComments();
userComments.userComments = userComment1;
usercommentsList.add( userComments);
pf.usercommentsList=usercommentsList;
}
if (data1!= null)
{
Log.d(TAG+"database",database.toString());
if (data1.moveToFirst()){
//do{
Log.d(TAG,"am in curser data1");
String provider = data1.getString(data1.getColumnIndex("profile_name"));
String Country = data1.getString(data1.getColumnIndex("country"));
String profileid = data1.getString(data1.getColumnIndex("profile_id"));
String rating = data1.getString(data1.getColumnIndex("rating"));
String is_online= data1.getString(data1.getColumnIndex("is_online"));
// String usercomments=data1.getString(data1.getColumnIndex("usercomments"));
String acname=data1.getString(data1.getColumnIndex("acname"));
String bankname=data1.getString(data1.getColumnIndex("bankname"));
String acno=data1.getString(data1.getColumnIndex("acno"));
pf.country=Country;
Log.d("pf.country",pf.country);
pf.profile_id=profileid;
Log.d("profile_id",pf.profile_id);
pf.profile_name=provider;
Log.d("profile_name",pf.profile_name);
pf.is_online=is_online;
pf.acname=acname;
pf.acno=acno;
pf.bankname=bankname;
pf.rating=rating;
//pf.videoid=videoid;
// Log.d(TAG,pf.videoid);
//}while (data1.moveToNext());
}
//database.close();
}
profiles.add(pf);
}while (data2.moveToNext());
Log.e(TAG+"profiles size",""+profiles.size());
data2.close();
// data1.close();
}
}
return profiles;
}
* method that get category data from database table
*
*/
public ArrayList<String>getCategories(){
SQLiteDatabase database = this.getWritableDatabase();
ArrayList<String> results = new ArrayList<String>();
Cursor data = database.rawQuery("SELECT category_name from catalog2 where parent_id=0;",null);
if (data != null)
{
Log.d("database",database.toString());
if (data.moveToFirst())
{
do
{
String catagoryName = data.getString(data.getColumnIndex("category_name"));
Log.e("catagery name",""+catagoryName);
results.add(catagoryName );
} while (data.moveToNext());
}
data.close();
return results;
}
else
return null;
}
/**
* method that get sub-category from database table, here we passing categoryName which search in catlog2 table and returns category_id, from it we search all these data from catlog table ie [category_name,category_id,parent_id, is_leaf]
*
*/
public ArrayList<Category>getSubCategories( CharSequence categoryName){
ArrayList<Category> results = new ArrayList<Category>();
SQLiteDatabase database = this.getWritableDatabase();
String parent=null;
Cursor data = database.query("catalog2", new String[] {"category_id"},new String("category_name"+"=?"),new String[]{categoryName.toString()}, null, null, null);
if (data.moveToFirst())
{
{
parent = data.getString(data.getColumnIndex("category_id"));
Log.e("parent",""+parent);
}
}
data.close();
data = database.rawQuery("SELECT category_name,category_id,parent_id, is_leaf from catalog2 where parent_id="+parent,null);
if (data.moveToFirst())
{
do
{
String category_id=data.getString(data.getColumnIndex("category_id"));
String catagoryName = data.getString(data.getColumnIndex("category_name"));
String parent_id = data.getString(data.getColumnIndex("parent_id"));
String isleaf=data.getString(data.getColumnIndex("is_leaf"));
Category c=new Category();
c.category_name=catagoryName;
Log.e("catagoryName",""+catagoryName);
c.category_id=category_id;
c.is_leaf=isleaf;
c.parent_id=parent_id;
results.add(c);
} while (data.moveToNext());
}
data.close();
database.close();
return results;
}
Code for getting multiple table data :
/**
* method that get service provider profile from database table
*
*/
public ArrayList<ServiceProvider> getProviderProfiles(String profile_id){
ArrayList<ServiceProvider> profiles = new ArrayList<ServiceProvider>();
SQLiteDatabase database = this.getWritableDatabase();
ArrayList<UserComments> usercommentsList=new ArrayList<UserComments>();
UserComments userComments;
EmailIds emailid;
ArrayList<EmailIds> emailidList=new ArrayList<EmailIds>();
String sp_profileid=null;
Service1 service;
ArrayList<Service1> servicesList=new ArrayList<Service1>();
ArrayList<Phnos> PhnosList=new ArrayList<Phnos>();
Phnos pHno;
Log.e("nu_profileid",""+profile_id);
// Cursor data2 =database.rawQuery("SELECT * form nu_subscriptions where nu_profile_id="+profile_id,null);
Cursor data2 = database.query("nu_subscriptions", new String[] {"sp_profile_id"},new String("nu_profile_id"+"=?"),new String[]{profile_id.toString()}, null, null, null);
if (data2!= null)
{
// Log.d(TAG+"database",database.toString());
if (data2.moveToFirst()){
do{
sp_profileid=data2.getString(data2.getColumnIndex("sp_profile_id"));
Log.e("sp_profileid",""+sp_profileid);
//Cursor data1 = database.rawQuery("select profile_name,profile_des,country,city,profile_id,rating,is_online,acno,bankname, acname from SM_profile1 where profile_id="+sp_profileid, null);
Cursor data1=database.query("SM_profile1", new String[] {"profile_name","profile_des","country","city","profile_id","rating","is_online","acno","bankname", "acname"},new String("profile_id"+"=?"),new String[]{sp_profileid.toString()}, null, null, null);
Cursor data4 = database.query("SM_email_id1", new String[] {"email_id"},new String("profile_id"+"=?"),new String[]{sp_profileid.toString()}, null, null, null);
Cursor data5 = database.query("SM_phone_numbers", new String[] {"contact_number"},new String("profile_id"+"=?"),new String[]{sp_profileid.toString()}, null, null, null);
Cursor data3 = database.query("SM_user_comments1", new String[] {"user_comments"},new String("profile_id"+"=?"),new String[]{sp_profileid.toString()}, null, null, null);
Cursor data6 = database.query("nu_subscriptions", new String[] {"service_id","service_name" ,"service_charge","sp_profile_id"},new String("sp_profile_id"+"=?"),new String[]{sp_profileid.toString()}, null, null, null);
ServiceProvider pf=new ServiceProvider();
if (data6.moveToFirst()){
do{
// servicesList=new ArrayList<Service1>();
//servicesList.clear();
String service_id= data6.getString(data6.getColumnIndex("service_id"));
Log.e("service_id",""+service_id);
String service_name= data6.getString(data6.getColumnIndex("service_name"));
String sp_profile_id= data6.getString(data6.getColumnIndex("sp_profile_id"));
//String payment_timestamp= data2.getString(data2.getColumnIndex("payment_timestamp"));
String service_charge= data6.getString(data6.getColumnIndex("service_charge"));
service=new Service1();
service.service_id =service_id ;
service.service_charge = service_charge;
service.service_name= service_name;
service.sp_profile_id=sp_profile_id;
// service.service_des= service_des;
servicesList.add(service);
pf.serviceList=servicesList;
//pf.serviceList.clear();
Log.e(TAG,""+pf.serviceList.size());
for(int i=0;i<pf.serviceList.size();i++){
Log.e(TAG,pf.serviceList.get(i).service_id);
}
}while (data6.moveToNext());
}
if (data4.moveToFirst()){
String emailid1=data4.getString(data4.getColumnIndex("email_id"));
emailid=new EmailIds();
Log.e(" emailid", emailid1);
emailid.emailid =emailid1;
emailidList.add(emailid);
pf.email_idList=emailidList;
}
if (data5.moveToFirst()){
String contactnumber=data5.getString(data5.getColumnIndex("contact_number"));
pHno=new Phnos(null);
Log.e("contactnumber",contactnumber);
pHno.phno =contactnumber;
PhnosList.add(pHno);
pf.phnoList=PhnosList;
}
if (data3.moveToFirst())
{
String userComment1=data3.getString(data3.getColumnIndex("user_comments"));
userComments=new UserComments();
userComments.userComments = userComment1;
usercommentsList.add( userComments);
pf.usercommentsList=usercommentsList;
}
if (data1!= null)
{
Log.d(TAG+"database",database.toString());
if (data1.moveToFirst()){
//do{
Log.d(TAG,"am in curser data1");
String provider = data1.getString(data1.getColumnIndex("profile_name"));
String Country = data1.getString(data1.getColumnIndex("country"));
String profileid = data1.getString(data1.getColumnIndex("profile_id"));
String rating = data1.getString(data1.getColumnIndex("rating"));
String is_online= data1.getString(data1.getColumnIndex("is_online"));
// String usercomments=data1.getString(data1.getColumnIndex("usercomments"));
String acname=data1.getString(data1.getColumnIndex("acname"));
String bankname=data1.getString(data1.getColumnIndex("bankname"));
String acno=data1.getString(data1.getColumnIndex("acno"));
pf.country=Country;
Log.d("pf.country",pf.country);
pf.profile_id=profileid;
Log.d("profile_id",pf.profile_id);
pf.profile_name=provider;
Log.d("profile_name",pf.profile_name);
pf.is_online=is_online;
pf.acname=acname;
pf.acno=acno;
pf.bankname=bankname;
pf.rating=rating;
//pf.videoid=videoid;
// Log.d(TAG,pf.videoid);
//}while (data1.moveToNext());
}
//database.close();
}
profiles.add(pf);
}while (data2.moveToNext());
Log.e(TAG+"profiles size",""+profiles.size());
data2.close();
// data1.close();
}
}
return profiles;
}
CRUD Database with Sqlite3 creating database using SQlite manager tool and accessing path
DBAdapter.java
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
public class DBAdapter extends SQLiteOpenHelper {
private static String DB_PATH = "";
private static final String DB_NAME = "user.sqlite";
private SQLiteDatabase myDataBase;
private final Context myContext;
private static DBAdapter mDBConnection;
/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and resources.
* @param context
*/
private DBAdapter(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
DB_PATH = "/data/data/"
+ context.getApplicationContext().getPackageName()
+ "/databases/";
// The Android's default system path of your application database is
// "/data/data/mypackagename/databases/"
}
/**
* getting Instance
* @param context
* @return DBAdapter
*/
public static synchronized DBAdapter getDBAdapterInstance(Context context) {
if (mDBConnection == null) {
mDBConnection = new DBAdapter(context);
}
return mDBConnection;
}
/**
* Creates an empty database on the system and rewrites it with your own database.
**/
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
// do nothing - database already exist
} else {
// By calling following method
// 1) an empty database will be created into the default system path of your application
// 2) than we overwrite that database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
* @return true if it exists, false if it doesn't
*/
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* Copies your database from your local assets-folder to the just created
* empty database in the system folder, from where it can be accessed and
* handled. This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
/**
* Open the database
* @throws SQLException
*/
public void openDataBase() throws SQLException {
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
/**
* Close the database if exist
*/
@Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
/**
* Call on creating data base for example for creating tables at run time
*/
@Override
public void onCreate(SQLiteDatabase db) {
}
/**
* can used for drop tables then call onCreate(db) function to create tables again - upgrade
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
// ----------------------- CRUD Functions ------------------------------
/**
* This function used to select the records from DB.
* @param tableName
* @param tableColumns
* @param whereClase
* @param whereArgs
* @param groupBy
* @param having
* @param orderBy
* @return A Cursor object, which is positioned before the first entry.
*/
public Cursor selectRecordsFromDB(String tableName, String[] tableColumns,
String whereClase, String whereArgs[], String groupBy,
String having, String orderBy) {
return myDataBase.query(tableName, tableColumns, whereClase, whereArgs,
groupBy, having, orderBy);
}
/**
* select records from db and return in list
* @param tableName
* @param tableColumns
* @param whereClase
* @param whereArgs
* @param groupBy
* @param having
* @param orderBy
* @return ArrayList<ArrayList<String>>
*/
public ArrayList<ArrayList<String>> selectRecordsFromDBList(String tableName, String[] tableColumns,
String whereClase, String whereArgs[], String groupBy,
String having, String orderBy) {
ArrayList<ArrayList<String>> retList = new ArrayList<ArrayList<String>>();
ArrayList<String> list = new ArrayList<String>();
Cursor cursor = myDataBase.query(tableName, tableColumns, whereClase, whereArgs,
groupBy, having, orderBy);
if (cursor.moveToFirst()) {
do {
list = new ArrayList<String>();
for(int i=0; i<cursor.getColumnCount(); i++){
list.add( cursor.getString(i) );
}
retList.add(list);
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return retList;
}
/**
* This function used to insert the Record in DB.
* @param tableName
* @param nullColumnHack
* @param initialValues
* @return the row ID of the newly inserted row, or -1 if an error occurred
*/
public long insertRecordsInDB(String tableName, String nullColumnHack,
ContentValues initialValues) {
return myDataBase.insert(tableName, nullColumnHack, initialValues);
}
/**
* This function used to update the Record in DB.
* @param tableName
* @param initialValues
* @param whereClause
* @param whereArgs
* @return true / false on updating one or more records
*/
public boolean updateRecordInDB(String tableName,
ContentValues initialValues, String whereClause, String whereArgs[]) {
return myDataBase.update(tableName, initialValues, whereClause,
whereArgs) > 0;
}
/**
* This function used to update the Record in DB.
* @param tableName
* @param initialValues
* @param whereClause
* @param whereArgs
* @return 0 in case of failure otherwise return no of row(s) are updated
*/
public int updateRecordsInDB(String tableName,
ContentValues initialValues, String whereClause, String whereArgs[]) {
return myDataBase.update(tableName, initialValues, whereClause, whereArgs);
}
/**
* This function used to delete the Record in DB.
* @param tableName
* @param whereClause
* @param whereArgs
* @return 0 in case of failure otherwise return no of row(s) are deleted.
*/
public int deleteRecordInDB(String tableName, String whereClause,
String[] whereArgs) {
return myDataBase.delete(tableName, whereClause, whereArgs);
}
// --------------------- Select Raw Query Functions ---------------------
/**
* apply raw Query
* @param query
* @param selectionArgs
* @return Cursor
*/
public Cursor selectRecordsFromDB(String query, String[] selectionArgs) {
return myDataBase.rawQuery(query, selectionArgs);
}
/**
* apply raw query and return result in list
* @param query
* @param selectionArgs
* @return ArrayList<ArrayList<String>>
*/
public ArrayList<ArrayList<String>> selectRecordsFromDBList(String query, String[] selectionArgs) {
ArrayList<ArrayList<String>> retList = new ArrayList<ArrayList<String>>();
ArrayList<String> list = new ArrayList<String>();
Cursor cursor = myDataBase.rawQuery(query, selectionArgs);
if (cursor.moveToFirst()) {
do {
list = new ArrayList<String>();
for(int i=0; i<cursor.getColumnCount(); i++){
list.add( cursor.getString(i) );
}
retList.add(list);
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return retList;
}
}
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
public class DBAdapter extends SQLiteOpenHelper {
private static String DB_PATH = "";
private static final String DB_NAME = "user.sqlite";
private SQLiteDatabase myDataBase;
private final Context myContext;
private static DBAdapter mDBConnection;
/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and resources.
* @param context
*/
private DBAdapter(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
DB_PATH = "/data/data/"
+ context.getApplicationContext().getPackageName()
+ "/databases/";
// The Android's default system path of your application database is
// "/data/data/mypackagename/databases/"
}
/**
* getting Instance
* @param context
* @return DBAdapter
*/
public static synchronized DBAdapter getDBAdapterInstance(Context context) {
if (mDBConnection == null) {
mDBConnection = new DBAdapter(context);
}
return mDBConnection;
}
/**
* Creates an empty database on the system and rewrites it with your own database.
**/
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
// do nothing - database already exist
} else {
// By calling following method
// 1) an empty database will be created into the default system path of your application
// 2) than we overwrite that database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
* @return true if it exists, false if it doesn't
*/
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* Copies your database from your local assets-folder to the just created
* empty database in the system folder, from where it can be accessed and
* handled. This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
/**
* Open the database
* @throws SQLException
*/
public void openDataBase() throws SQLException {
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
/**
* Close the database if exist
*/
@Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
/**
* Call on creating data base for example for creating tables at run time
*/
@Override
public void onCreate(SQLiteDatabase db) {
}
/**
* can used for drop tables then call onCreate(db) function to create tables again - upgrade
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
// ----------------------- CRUD Functions ------------------------------
/**
* This function used to select the records from DB.
* @param tableName
* @param tableColumns
* @param whereClase
* @param whereArgs
* @param groupBy
* @param having
* @param orderBy
* @return A Cursor object, which is positioned before the first entry.
*/
public Cursor selectRecordsFromDB(String tableName, String[] tableColumns,
String whereClase, String whereArgs[], String groupBy,
String having, String orderBy) {
return myDataBase.query(tableName, tableColumns, whereClase, whereArgs,
groupBy, having, orderBy);
}
/**
* select records from db and return in list
* @param tableName
* @param tableColumns
* @param whereClase
* @param whereArgs
* @param groupBy
* @param having
* @param orderBy
* @return ArrayList<ArrayList<String>>
*/
public ArrayList<ArrayList<String>> selectRecordsFromDBList(String tableName, String[] tableColumns,
String whereClase, String whereArgs[], String groupBy,
String having, String orderBy) {
ArrayList<ArrayList<String>> retList = new ArrayList<ArrayList<String>>();
ArrayList<String> list = new ArrayList<String>();
Cursor cursor = myDataBase.query(tableName, tableColumns, whereClase, whereArgs,
groupBy, having, orderBy);
if (cursor.moveToFirst()) {
do {
list = new ArrayList<String>();
for(int i=0; i<cursor.getColumnCount(); i++){
list.add( cursor.getString(i) );
}
retList.add(list);
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return retList;
}
/**
* This function used to insert the Record in DB.
* @param tableName
* @param nullColumnHack
* @param initialValues
* @return the row ID of the newly inserted row, or -1 if an error occurred
*/
public long insertRecordsInDB(String tableName, String nullColumnHack,
ContentValues initialValues) {
return myDataBase.insert(tableName, nullColumnHack, initialValues);
}
/**
* This function used to update the Record in DB.
* @param tableName
* @param initialValues
* @param whereClause
* @param whereArgs
* @return true / false on updating one or more records
*/
public boolean updateRecordInDB(String tableName,
ContentValues initialValues, String whereClause, String whereArgs[]) {
return myDataBase.update(tableName, initialValues, whereClause,
whereArgs) > 0;
}
/**
* This function used to update the Record in DB.
* @param tableName
* @param initialValues
* @param whereClause
* @param whereArgs
* @return 0 in case of failure otherwise return no of row(s) are updated
*/
public int updateRecordsInDB(String tableName,
ContentValues initialValues, String whereClause, String whereArgs[]) {
return myDataBase.update(tableName, initialValues, whereClause, whereArgs);
}
/**
* This function used to delete the Record in DB.
* @param tableName
* @param whereClause
* @param whereArgs
* @return 0 in case of failure otherwise return no of row(s) are deleted.
*/
public int deleteRecordInDB(String tableName, String whereClause,
String[] whereArgs) {
return myDataBase.delete(tableName, whereClause, whereArgs);
}
// --------------------- Select Raw Query Functions ---------------------
/**
* apply raw Query
* @param query
* @param selectionArgs
* @return Cursor
*/
public Cursor selectRecordsFromDB(String query, String[] selectionArgs) {
return myDataBase.rawQuery(query, selectionArgs);
}
/**
* apply raw query and return result in list
* @param query
* @param selectionArgs
* @return ArrayList<ArrayList<String>>
*/
public ArrayList<ArrayList<String>> selectRecordsFromDBList(String query, String[] selectionArgs) {
ArrayList<ArrayList<String>> retList = new ArrayList<ArrayList<String>>();
ArrayList<String> list = new ArrayList<String>();
Cursor cursor = myDataBase.rawQuery(query, selectionArgs);
if (cursor.moveToFirst()) {
do {
list = new ArrayList<String>();
for(int i=0; i<cursor.getColumnCount(); i++){
list.add( cursor.getString(i) );
}
retList.add(list);
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return retList;
}
}
gridview which scrolls horizontally with network call
/**
* Class Name : CategoryMenu
*
* Parent Class :Activity
*
* Interfaces: None
*
* Description:This class displays the categories and
subcategories menu to the user. Categories will bedisplayed
as a one line horizontal gallery and Subcategories as a list.
*/
import java.util.ArrayList;
import java.util.List;
import com.ServiceMessenger.R;
import com.inception.dataparser.Category;
import com.inception.dataparser.ServiceProvider;
import com.inception.dataparser.UserProfiles;
import com.inception.dataprovider.DatabaseHelper;
import com.inception.network.MessageAlertService;
import com.inception.network.NetworkService;
import com.inception.network.NetworkUtilService;
import com.inception.sm.ApplicationManager;
import com.inception.sm.Globals;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView.ScaleType;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
public class CategoryMenu extends Activity {
/** Called when the activity is first created. */
ArrayList<UserProfiles> mUserProfiles = new ArrayList<UserProfiles>();
public List<String> mList = null;
private ArrayList<ServiceProvider> mProfileList = new ArrayList<ServiceProvider>();
public static String mUProfilrid;
private static final int INDETERMINATE = 0;
String mProfileid;
/// public static boolean mLogin_status=false;
private int mLoadingFirst;
SharedPreferences mSettings;
SharedPreferences mSettings1;
public static SharedPreferences mLogin_status;
static Boolean mStatus;
private int mCatvs;
private int mCurrentv;
private int mCatv1;
private LayoutInflater mInflater;
private NotificationManager mNotificationManager;
private ProgressDialog mProgDlg;
private static ApplicationManager mAppMgr;
private DatabaseHelper mDBHelper;
final Messenger mMessenger = new Messenger(new IncomingHandler());
Messenger mService = null;
//wedgets
Intent i;
Bitmap viewBgrnd;
Integer[] mThumbIds;
ImageButton img ;
Button button;
ImageView img1;
TextView tx;
Button b1;
//gallery wedgets
private ScrollView nsv;
private HorizontalScrollView sv;
private LinearLayout llh;
private LinearLayout.LayoutParams layoutParamsTV;
private LinearLayout.LayoutParams layoutParamsLL;
private LinearLayout.LayoutParams layoutParamsLLD;
private LinearLayout llv;
static int total;
private Category mCat = new Category();
/**
* Class Name :IncomingHandler
*
* Parent Class :Handler
*
* Interfaces: None
*
* Description:Handler class for handling
*
* incoming messages from server
*/
class IncomingHandler extends Handler {
/**
* Callback method to handle messages coming from server
*
*/
@Override
public void handleMessage(Message msg) {
Log.e("UIAct","handleMessage");
switch (msg.what) {
case NetworkService.MSG_CATALOG_AVAILABLE:
mList= new ArrayList<String>();
Log.e("MSG_CATALOG_AVAILABLE",""+mList.size());
mList=mAppMgr.getCategories();
horizontalScrollGalleryLayout(mList);
mProgDlg.dismiss();
//mGallery.setAdapter(new ImageAdapter(CategoryMenu.this));
break;
default:
super.handleMessage(msg);
}
}
}
/**
* Callback method to get connection from server
*
*/
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mService = new Messenger(service);
try {
Log.e("UIAct","onServiceConnected");
Message msg = Message.obtain(null, NetworkService.MSG_REGISTER_CLIENT);
msg.replyTo = mMessenger;
mService.send(msg);
//Log.e("mCatv in 2nd if","xyz"+mCatvs);
//Log.e("mCurrentv in 2nd if",""+mCurrentv);
//msg.replyTo = mMessenger;
msg = Message.obtain(null, NetworkService.MSG_GET_CATALOG);
msg.replyTo = mMessenger;
mService.send(msg);
Log.d("connecting to","categories service");
// }
} catch (RemoteException e) {
// In this case the service has crashed before we could even do anything with it
}
}
/**
* Callback method to get disconnect from server
*
*/
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been unexpectedly disconnected - process crashed.
mService = null;
Log.e("UIAct","onServiceDisconnected");
}
};
/**
* Callback method to launch the Acitivity
*
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSettings = this.getSharedPreferences(Globals.PREFS_NAME, 0);
mLogin_status = this.getSharedPreferences(Globals.PREFS_NAME, 0);
mStatus=mLogin_status.getBoolean("status", false);
mSettings1 = this.getSharedPreferences(Globals.PREFS_NAME, 0);
Context context = getApplicationContext();
nsv=new ScrollView(this);
sv = new HorizontalScrollView(this);
llh = new LinearLayout(this);
llh.setOrientation(LinearLayout.HORIZONTAL);
layoutParamsTV = new LinearLayout.LayoutParams(80,80);
layoutParamsTV.setMargins(15, 30, 15, 15);
layoutParamsLL = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParamsLLD = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);
mDBHelper = new DatabaseHelper(this);
mAppMgr = ApplicationManager.getApplicationMgrInstance(this.getApplicationContext());
mList =new ArrayList<String>();
mList =mAppMgr.getCategories();
total=0;
//horizontalScrollGalleryLayout1(mList);
Log.i("mList",""+mList.size());
if(mList.size()==0){
boolean check_con=NetworkUtilService.getInstance(this).isOnline(this); Log.i("check_con",""+check_con);
if (NetworkUtilService.getInstance(this).isOnline(this)) {
Log.e("binding to","service");
showDialog(INDETERMINATE);
//mLoadingFirst=1;
bindService(new Intent(CategoryMenu.this, NetworkService.class), mConnection, Context.BIND_AUTO_CREATE);
Log.e("loading first time","for catalog");
//horizontalScrollGalleryLayout(mList);
mProgDlg.dismiss();
}
else
{
AlertDialog.Builder dialog1 = new AlertDialog.Builder(CategoryMenu.this);
dialog1.setTitle("ALERT");
dialog1.setMessage("No Connection! Try Later");
dialog1.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog1, int id) {
CategoryMenu.this.finish();
//dialog1.cancel();
}
});
/*dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});*/
AlertDialog alert =dialog1.create();
// Title for AlertDialog
alert.setTitle("OUT OF CONNECTION");
// Icon for AlertDialog
alert.setIcon(R.drawable.icon);
alert.show();
}
}
else
{
horizontalScrollGalleryLayout(mList);
Log.e("mList in else",""+mList.size());
// Log.e(mList.get(0).);
}
}
public void horizontalScrollGalleryLayout (List<String> mList3) {
Integer[] mThumbIds = {
R.drawable.gallery_photo_1,R.drawable.gallery_photo_2,R.drawable.gallery_photo_3,
R.drawable.gallery_photo_4,R.drawable.gallery_photo_5,R.drawable.gallery_photo_6,
R.drawable.gallery_photo_1,R.drawable.gallery_photo_2,R.drawable.gallery_photo_3,
R.drawable.gallery_photo_4,R.drawable.gallery_photo_2,
R.drawable.gallery_photo_1,R.drawable.gallery_photo_2,R.drawable.gallery_photo_3,
R.drawable.gallery_photo_4,R.drawable.gallery_photo_5,R.drawable.gallery_photo_6,
R.drawable.gallery_photo_1,R.drawable.gallery_photo_2,R.drawable.gallery_photo_3,
R.drawable.gallery_photo_4,R.drawable.gallery_photo_5,R.drawable.gallery_photo_6,
R.drawable.gallery_photo_1,R.drawable.gallery_photo_2,R.drawable.gallery_photo_3,
R.drawable.gallery_photo_4,R.drawable.gallery_photo_5,R.drawable.gallery_photo_6,
/* R.drawable.gallery_photo_1,R.drawable.gallery_photo_2,R.drawable.gallery_photo_3,
R.drawable.gallery_photo_4,R.drawable.gallery_photo_5,R.drawable.gallery_photo_6,
R.drawable.gallery_photo_1,R.drawable.gallery_photo_2,R.drawable.gallery_photo_3*/
};
Log.i("I got call","for creation of horizontalgallery");
sv = new HorizontalScrollView(this);
llh = new LinearLayout(this);
llh.setOrientation(LinearLayout.HORIZONTAL);
layoutParamsTV = new LinearLayout.LayoutParams(75,75);
layoutParamsTV.setMargins(15, 30, 15, 15);
layoutParamsLL = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParamsLLD = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);
Log.e("in horizantal","scroll view 1");
for(int k=0;k<mList3.size();k++)
{
if(mList3.size()==total)
{
break;
}
llv = new LinearLayout(this);
for (int i=0; i<3; i++) {
llv.setOrientation(LinearLayout.VERTICAL);
//button= new Button(this);
//button=new Button(this);
img1 = new ImageView(this);
tx = new TextView(this);
mCat = new Category();
try {
img1.setBackgroundResource(mThumbIds[total]);
img1.setTag(mList3.get(total));
tx.setText(mList3.get(total));
tx.setTextColor(Color.WHITE);
//tx.setPadding(25, 0, 15, 0);
tx.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
img1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// Perform action on click
//CharSequence cat = "Education";
CharSequence cat = (CharSequence) view.getTag();
Log.e("imgTag after category clicked",""+ cat);
CharSequence category = cat;
mCat=mAppMgr.getCategoryObjectFromId(category);
String isleaf = mCat.getIs_leaf();
String parent_id=mCat.getParent_id();
String cat_id=mCat.getCategory_id();
Log.e("isleaf",isleaf);
//Log.e("parent_id",parent_id);
if(isleaf.equals("false"))
{
Intent i=new Intent(CategoryMenu.this,ProfilesList.class);
//i.putExtra("subcat", category);
Log.d("false executed","Thanks");
i.putExtra("cat", category);
i.putExtra("view", Globals.CONST_SUBCATEGORY);
startActivity(i);
}
else
{
Intent i=new Intent(CategoryMenu.this,ProfilesList.class);
Log.d("true executed","Thanks");
i.putExtra("cat",cat_id);
i.putExtra("view", Globals.CONST_PROFILE);
startActivity(i);
}
//CharSequence category = cat;
//Log.e("category",""+category);
//i.putExtra("subcat", category);
//i.putExtra("view", Globals.CONST_PROFILE);
Log.e("am in","sub categories");
}
});
total++;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
llv.addView(img1,layoutParamsTV);
llv.addView(tx);
if(mList3.size()==total)
break;
//b1[k].setBackgroundResource(mThumbIds[k]);
}
//llv.addView(button, layoutParamsTV);
llh.addView(llv, layoutParamsLL);
llh.setBackgroundColor(Color.TRANSPARENT);
llh.setHorizontalScrollBarEnabled(false);
}
sv.addView(llh, layoutParamsLLD);
nsv.addView(sv);
sv.setHorizontalScrollBarEnabled(false);
nsv.setVerticalScrollBarEnabled(false);
//setContentView(sv);
setContentView(nsv);
}
/**
*Progress bar to show progress of fetching data from server
*/
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case INDETERMINATE: {
mProgDlg = new ProgressDialog(this);
mProgDlg.setTitle("Indeterminate");
mProgDlg.setMessage("Please wait while loading...");
mProgDlg.setIndeterminate(true);
mProgDlg.setCancelable(true);
return mProgDlg;
}
}
return null;
}
public void onDestroy() {
Log.i("CategoryMenu","onDestroy Called");
super.onDestroy();
try {
stopService(new Intent(CategoryMenu.this, MessageAlertService.class));
} catch (Throwable t) {
Log.e("CategoryMenu", "stopService", t);
}
}
}
* Class Name : CategoryMenu
*
* Parent Class :Activity
*
* Interfaces: None
*
* Description:This class displays the categories and
subcategories menu to the user. Categories will bedisplayed
as a one line horizontal gallery and Subcategories as a list.
*/
import java.util.ArrayList;
import java.util.List;
import com.ServiceMessenger.R;
import com.inception.dataparser.Category;
import com.inception.dataparser.ServiceProvider;
import com.inception.dataparser.UserProfiles;
import com.inception.dataprovider.DatabaseHelper;
import com.inception.network.MessageAlertService;
import com.inception.network.NetworkService;
import com.inception.network.NetworkUtilService;
import com.inception.sm.ApplicationManager;
import com.inception.sm.Globals;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView.ScaleType;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
public class CategoryMenu extends Activity {
/** Called when the activity is first created. */
ArrayList<UserProfiles> mUserProfiles = new ArrayList<UserProfiles>();
public List<String> mList = null;
private ArrayList<ServiceProvider> mProfileList = new ArrayList<ServiceProvider>();
public static String mUProfilrid;
private static final int INDETERMINATE = 0;
String mProfileid;
/// public static boolean mLogin_status=false;
private int mLoadingFirst;
SharedPreferences mSettings;
SharedPreferences mSettings1;
public static SharedPreferences mLogin_status;
static Boolean mStatus;
private int mCatvs;
private int mCurrentv;
private int mCatv1;
private LayoutInflater mInflater;
private NotificationManager mNotificationManager;
private ProgressDialog mProgDlg;
private static ApplicationManager mAppMgr;
private DatabaseHelper mDBHelper;
final Messenger mMessenger = new Messenger(new IncomingHandler());
Messenger mService = null;
//wedgets
Intent i;
Bitmap viewBgrnd;
Integer[] mThumbIds;
ImageButton img ;
Button button;
ImageView img1;
TextView tx;
Button b1;
//gallery wedgets
private ScrollView nsv;
private HorizontalScrollView sv;
private LinearLayout llh;
private LinearLayout.LayoutParams layoutParamsTV;
private LinearLayout.LayoutParams layoutParamsLL;
private LinearLayout.LayoutParams layoutParamsLLD;
private LinearLayout llv;
static int total;
private Category mCat = new Category();
/**
* Class Name :IncomingHandler
*
* Parent Class :Handler
*
* Interfaces: None
*
* Description:Handler class for handling
*
* incoming messages from server
*/
class IncomingHandler extends Handler {
/**
* Callback method to handle messages coming from server
*
*/
@Override
public void handleMessage(Message msg) {
Log.e("UIAct","handleMessage");
switch (msg.what) {
case NetworkService.MSG_CATALOG_AVAILABLE:
mList= new ArrayList<String>();
Log.e("MSG_CATALOG_AVAILABLE",""+mList.size());
mList=mAppMgr.getCategories();
horizontalScrollGalleryLayout(mList);
mProgDlg.dismiss();
//mGallery.setAdapter(new ImageAdapter(CategoryMenu.this));
break;
default:
super.handleMessage(msg);
}
}
}
/**
* Callback method to get connection from server
*
*/
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mService = new Messenger(service);
try {
Log.e("UIAct","onServiceConnected");
Message msg = Message.obtain(null, NetworkService.MSG_REGISTER_CLIENT);
msg.replyTo = mMessenger;
mService.send(msg);
//Log.e("mCatv in 2nd if","xyz"+mCatvs);
//Log.e("mCurrentv in 2nd if",""+mCurrentv);
//msg.replyTo = mMessenger;
msg = Message.obtain(null, NetworkService.MSG_GET_CATALOG);
msg.replyTo = mMessenger;
mService.send(msg);
Log.d("connecting to","categories service");
// }
} catch (RemoteException e) {
// In this case the service has crashed before we could even do anything with it
}
}
/**
* Callback method to get disconnect from server
*
*/
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been unexpectedly disconnected - process crashed.
mService = null;
Log.e("UIAct","onServiceDisconnected");
}
};
/**
* Callback method to launch the Acitivity
*
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSettings = this.getSharedPreferences(Globals.PREFS_NAME, 0);
mLogin_status = this.getSharedPreferences(Globals.PREFS_NAME, 0);
mStatus=mLogin_status.getBoolean("status", false);
mSettings1 = this.getSharedPreferences(Globals.PREFS_NAME, 0);
Context context = getApplicationContext();
nsv=new ScrollView(this);
sv = new HorizontalScrollView(this);
llh = new LinearLayout(this);
llh.setOrientation(LinearLayout.HORIZONTAL);
layoutParamsTV = new LinearLayout.LayoutParams(80,80);
layoutParamsTV.setMargins(15, 30, 15, 15);
layoutParamsLL = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParamsLLD = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);
mDBHelper = new DatabaseHelper(this);
mAppMgr = ApplicationManager.getApplicationMgrInstance(this.getApplicationContext());
mList =new ArrayList<String>();
mList =mAppMgr.getCategories();
total=0;
//horizontalScrollGalleryLayout1(mList);
Log.i("mList",""+mList.size());
if(mList.size()==0){
boolean check_con=NetworkUtilService.getInstance(this).isOnline(this); Log.i("check_con",""+check_con);
if (NetworkUtilService.getInstance(this).isOnline(this)) {
Log.e("binding to","service");
showDialog(INDETERMINATE);
//mLoadingFirst=1;
bindService(new Intent(CategoryMenu.this, NetworkService.class), mConnection, Context.BIND_AUTO_CREATE);
Log.e("loading first time","for catalog");
//horizontalScrollGalleryLayout(mList);
mProgDlg.dismiss();
}
else
{
AlertDialog.Builder dialog1 = new AlertDialog.Builder(CategoryMenu.this);
dialog1.setTitle("ALERT");
dialog1.setMessage("No Connection! Try Later");
dialog1.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog1, int id) {
CategoryMenu.this.finish();
//dialog1.cancel();
}
});
/*dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});*/
AlertDialog alert =dialog1.create();
// Title for AlertDialog
alert.setTitle("OUT OF CONNECTION");
// Icon for AlertDialog
alert.setIcon(R.drawable.icon);
alert.show();
}
}
else
{
horizontalScrollGalleryLayout(mList);
Log.e("mList in else",""+mList.size());
// Log.e(mList.get(0).);
}
}
public void horizontalScrollGalleryLayout (List<String> mList3) {
Integer[] mThumbIds = {
R.drawable.gallery_photo_1,R.drawable.gallery_photo_2,R.drawable.gallery_photo_3,
R.drawable.gallery_photo_4,R.drawable.gallery_photo_5,R.drawable.gallery_photo_6,
R.drawable.gallery_photo_1,R.drawable.gallery_photo_2,R.drawable.gallery_photo_3,
R.drawable.gallery_photo_4,R.drawable.gallery_photo_2,
R.drawable.gallery_photo_1,R.drawable.gallery_photo_2,R.drawable.gallery_photo_3,
R.drawable.gallery_photo_4,R.drawable.gallery_photo_5,R.drawable.gallery_photo_6,
R.drawable.gallery_photo_1,R.drawable.gallery_photo_2,R.drawable.gallery_photo_3,
R.drawable.gallery_photo_4,R.drawable.gallery_photo_5,R.drawable.gallery_photo_6,
R.drawable.gallery_photo_1,R.drawable.gallery_photo_2,R.drawable.gallery_photo_3,
R.drawable.gallery_photo_4,R.drawable.gallery_photo_5,R.drawable.gallery_photo_6,
/* R.drawable.gallery_photo_1,R.drawable.gallery_photo_2,R.drawable.gallery_photo_3,
R.drawable.gallery_photo_4,R.drawable.gallery_photo_5,R.drawable.gallery_photo_6,
R.drawable.gallery_photo_1,R.drawable.gallery_photo_2,R.drawable.gallery_photo_3*/
};
Log.i("I got call","for creation of horizontalgallery");
sv = new HorizontalScrollView(this);
llh = new LinearLayout(this);
llh.setOrientation(LinearLayout.HORIZONTAL);
layoutParamsTV = new LinearLayout.LayoutParams(75,75);
layoutParamsTV.setMargins(15, 30, 15, 15);
layoutParamsLL = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParamsLLD = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);
Log.e("in horizantal","scroll view 1");
for(int k=0;k<mList3.size();k++)
{
if(mList3.size()==total)
{
break;
}
llv = new LinearLayout(this);
for (int i=0; i<3; i++) {
llv.setOrientation(LinearLayout.VERTICAL);
//button= new Button(this);
//button=new Button(this);
img1 = new ImageView(this);
tx = new TextView(this);
mCat = new Category();
try {
img1.setBackgroundResource(mThumbIds[total]);
img1.setTag(mList3.get(total));
tx.setText(mList3.get(total));
tx.setTextColor(Color.WHITE);
//tx.setPadding(25, 0, 15, 0);
tx.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
img1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// Perform action on click
//CharSequence cat = "Education";
CharSequence cat = (CharSequence) view.getTag();
Log.e("imgTag after category clicked",""+ cat);
CharSequence category = cat;
mCat=mAppMgr.getCategoryObjectFromId(category);
String isleaf = mCat.getIs_leaf();
String parent_id=mCat.getParent_id();
String cat_id=mCat.getCategory_id();
Log.e("isleaf",isleaf);
//Log.e("parent_id",parent_id);
if(isleaf.equals("false"))
{
Intent i=new Intent(CategoryMenu.this,ProfilesList.class);
//i.putExtra("subcat", category);
Log.d("false executed","Thanks");
i.putExtra("cat", category);
i.putExtra("view", Globals.CONST_SUBCATEGORY);
startActivity(i);
}
else
{
Intent i=new Intent(CategoryMenu.this,ProfilesList.class);
Log.d("true executed","Thanks");
i.putExtra("cat",cat_id);
i.putExtra("view", Globals.CONST_PROFILE);
startActivity(i);
}
//CharSequence category = cat;
//Log.e("category",""+category);
//i.putExtra("subcat", category);
//i.putExtra("view", Globals.CONST_PROFILE);
Log.e("am in","sub categories");
}
});
total++;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
llv.addView(img1,layoutParamsTV);
llv.addView(tx);
if(mList3.size()==total)
break;
//b1[k].setBackgroundResource(mThumbIds[k]);
}
//llv.addView(button, layoutParamsTV);
llh.addView(llv, layoutParamsLL);
llh.setBackgroundColor(Color.TRANSPARENT);
llh.setHorizontalScrollBarEnabled(false);
}
sv.addView(llh, layoutParamsLLD);
nsv.addView(sv);
sv.setHorizontalScrollBarEnabled(false);
nsv.setVerticalScrollBarEnabled(false);
//setContentView(sv);
setContentView(nsv);
}
/**
*Progress bar to show progress of fetching data from server
*/
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case INDETERMINATE: {
mProgDlg = new ProgressDialog(this);
mProgDlg.setTitle("Indeterminate");
mProgDlg.setMessage("Please wait while loading...");
mProgDlg.setIndeterminate(true);
mProgDlg.setCancelable(true);
return mProgDlg;
}
}
return null;
}
public void onDestroy() {
Log.i("CategoryMenu","onDestroy Called");
super.onDestroy();
try {
stopService(new Intent(CategoryMenu.this, MessageAlertService.class));
} catch (Throwable t) {
Log.e("CategoryMenu", "stopService", t);
}
}
}
Subscribe to:
Posts (Atom)