Thursday, November 3, 2011

Sending multipar request to server in Android (like image and data)

/**
     * here list of user accounts and 6 phone numbers,6 emailids,and Service provicers information are sending .
     * This method creates Account at server and returns acknowledge
     * of creation of successful account.
     * @throws JSONException
     */

    public String getcreatedAccount(final String lid2, final String pwd2,final String uname,
            final String city2,final String country2,
            ArrayList<Phnos> mPhnolist,ArrayList<EmailIds> mEmailidlist,final String issp,final String refid,final String mcity,final String mcnt,final String pdes,ArrayList<Service1> serviceList,final String mid,final String memailid,final String mstreet,final String mpost,final String selectcat,String imgData) throws JSONException {
        Log.e("mcity",""+mcity);
        Log.e("pdes",""+pdes);
        String mRes=null;
        //mDBHelper =mAppMgr.getDbHelper();

        //mRes = mDBHelper.createAccountfun(account) ;
        ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
        postParameters.add(new BasicNameValuePair("client", "mc"));
        postParameters.add(new BasicNameValuePair("loginId", lid2));
        postParameters.add(new BasicNameValuePair("password", pwd2));
        postParameters.add(new BasicNameValuePair("profileName",uname));
        if(mPhnolist.size()!=0){
           
            //String json=jsonRequestConstructor(mPhnolist);
            //postParameters.add(new BasicNameValuePair("phlist",json));
           

        }
        if(mEmailidlist.size()!=0){
        //String json2=jsonRequestConstructorForemailid(mEmailidlist);
        //postParameters.add(new BasicNameValuePair("emaillist",json2));

    }
        postParameters.add(new BasicNameValuePair("city",city2));
        postParameters.add(new BasicNameValuePair("country",country2));
        postParameters.add(new BasicNameValuePair("mailid_primary",mEmailidlist.get(0).emailid));
        if(mEmailidlist.size()>=2){
        postParameters.add(new BasicNameValuePair("mailid_other1",mEmailidlist.get(1).emailid));
        }
        if(mEmailidlist.size()>=3){
        postParameters.add(new BasicNameValuePair("mailid_other2",mEmailidlist.get(2).emailid));
        }
        if(mEmailidlist.size()>=4){
        postParameters.add(new BasicNameValuePair("mailid_other3",mEmailidlist.get(3).emailid));
        }
        if(mEmailidlist.size()>=5){
        postParameters.add(new BasicNameValuePair("mailid_other4",mEmailidlist.get(4).emailid));
        }
        if(mEmailidlist.size()>=6){
        postParameters.add(new BasicNameValuePair("mailid_other5",mEmailidlist.get(5).emailid));
        }
       
        postParameters.add(new BasicNameValuePair("type_primary",mPhnolist.get(0).phno));
       
        if(mPhnolist.size()>=2){
        postParameters.add(new BasicNameValuePair("type_other1",mPhnolist.get(1).phno));
        }
        if(mPhnolist.size()>=3){
        postParameters.add(new BasicNameValuePair("type_other2",mPhnolist.get(2).phno));
        }
        if(mPhnolist.size()>=4){
        postParameters.add(new BasicNameValuePair("type_other3",mPhnolist.get(3).phno));
        }
        if(mPhnolist.size()>=5){
        postParameters.add(new BasicNameValuePair("type_other4",mPhnolist.get(4).phno));
        }
        if(mPhnolist.size()>=6){
        postParameters.add(new BasicNameValuePair("type_other5",mPhnolist.get(5).phno));
        }
        postParameters.add(new BasicNameValuePair("reference_id",refid));
        postParameters.add(new BasicNameValuePair("catalog_version_id",Integer.toString(mCatv)));
        postParameters.add(new BasicNameValuePair("isServiceProvider",issp));
        if(issp.equals("1")){
            postParameters.add(new BasicNameValuePair("spProfileDesc",pdes));
            if(serviceList.size()!=0){
            postParameters.add(new BasicNameValuePair("service_name",serviceList.get(0).service_name));
            Log.e("serviceList.get(0).service_name",""+serviceList.get(0).service_name);
            postParameters.add(new BasicNameValuePair("service_desc",serviceList.get(0).service_des));
            Log.e("serviceList.get(0).service_des",""+serviceList.get(0).service_des);
           
            postParameters.add(new BasicNameValuePair("service_duration",serviceList.get(0).timeslot));//mcharge
            Log.e("serviceList.get(0).timeslot",""+serviceList.get(0).timeslot);
            postParameters.add(new BasicNameValuePair("service_charge",serviceList.get(0).service_charge));
            Log.e("serviceList.get(0).service_charge",""+serviceList.get(0).service_charge);
            }
            postParameters.add(new BasicNameValuePair("merchant_acc_id",mid));
            Log.e("merchant_acc_id",mid);
            postParameters.add(new BasicNameValuePair("merchant_city",mcity));
            Log.e("merchant_city",mcity);
            postParameters.add(new BasicNameValuePair("merchant_emai_id",memailid));
            Log.e("merchant_emai_id",memailid);
            postParameters.add(new BasicNameValuePair("merchant_country",mcnt));
           
            Log.e("merchant_country",""+mcnt);
            postParameters.add(new BasicNameValuePair("merchant_street_add",mstreet));//mcharge
            Log.e("mstreet",""+mstreet);
            postParameters.add(new BasicNameValuePair("merchant_postal_code",mpost));
        Log.e("merchant_postal_code",mpost);
        postParameters.add(new BasicNameValuePair("select_category",selectcat));
            Log.e("selectcat",""+selectcat);
           

        }   


        String response = null;
        try {
            response = CustomHttpClient.executeHttpPost1(SM_SERVER_URL_PREFIX+"register", postParameters);
            String res=response.toString();
            mRes= res.replaceAll("\\s+","");
            res1=new RegistrationRes();
            res1=JSONSMParser.parseRegisrationstatus( mRes);
            Log.e("res1.status_code",""+res1.status_code);
            Log.e("login res",""+mRes);

        }
        catch (Exception e) {
            Log.e("exception",e.toString());
        }
       

        return res1.status_code;


    }


//following is supporting class for executeHttp request and response

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;

import java.net.HttpURLConnection;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;

import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;


import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.util.Log;

public class CustomHttpClient {
    /** The time it takes for our client to timeout */
    public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds

    /** Single instance of our HttpClient */
    private static HttpClient mHttpClient;
    private static Bitmap bitmap;
    /**
     * Get our single instance of our HttpClient object.
     *
     * @return an HttpClient object with connection parameters set
     */
    private static HttpClient getHttpClient() {
        if (mHttpClient == null) {
            mHttpClient = new DefaultHttpClient();
            final HttpParams params = mHttpClient.getParams();
           
            HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
            HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
            ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
        }
        return mHttpClient;
    }

    /**
     * Performs an HTTP Post request to the specified url with the
     * specified parameters.
     *
     * @param url The web address to post the request to
     * @param postParameters The parameters to send via the request
     * @return The result of the request
     * @throws Exception
     */
    public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
        BufferedReader in = null;
        try {
            HttpClient client = getHttpClient();
          
            HttpPost request = new HttpPost(url);
          
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
            Log.e( "postParameters",""+ postParameters);
            Log.e("formEntity",""+formEntity);

            /*    MultipartEntity entity = new MultipartEntity(
                    HttpMultipartMode.BROWSER_COMPATIBLE);

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(CompressFormat.JPEG, 100, bos);
            byte[] data = bos.toByteArray();
            entity.addPart("returnformat", new StringBody("json"));
            entity.addPart("uploaded", new ByteArrayBody(data,
                    "myImage.jpg"));*/
            request.setEntity(formEntity);
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            String result = sb.toString();
            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
//this bewlow code to send image and data with multipart request
    public static String executeHttpPost1(String url,ArrayList<NameValuePair> postParameters ) throws Exception {
        HttpPost post = new HttpPost(url);
     Bitmap bitmap; 
        String Result_STR=null;
        HttpClient client = new DefaultHttpClient();
        HttpEntity resmarkMessagesReadFrom =null;
        MultipartEntity reqmarkMessagesReadFrom = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        try {
            Log.e("postParameters.size()",""+postParameters.size());
            for(int i=0;i<postParameters.size();i++){
                Log.e("parameters",""+postParameters.get(i).getName()+""+postParameters.get(i).getValue());
            reqmarkMessagesReadFrom.addPart(postParameters.get(i).getName(), new StringBody(postParameters.get(i).getValue()));
            if(postParameters.get(i).getName().equals("imgpath")){
                  bitmap = BitmapFactory.decodeFile(postParameters.get(i).getValue()); 
             
                     // you can change the format of you image compressed for what do you want; 
                    //now it is set up to 640 x 480; 
             
                       Bitmap bmpCompressed = Bitmap.createScaledBitmap(bitmap, 640, 480, true); 
                       ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
                 
                  // CompressFormat set up to JPG, you can change to PNG or whatever you want; 
             
                    bmpCompressed.compress(CompressFormat.JPEG, 100, bos); 
                        byte[] data = bos.toByteArray();
                        reqmarkMessagesReadFrom.addPart("myImage", new ByteArrayBody(data, "temp.jpg")); 
                         
                               
            }
            post.setEntity(reqmarkMessagesReadFrom);
           
            }
             HttpResponse response = client.execute(post);
              resmarkMessagesReadFrom = response.getEntity();
            if (resmarkMessagesReadFrom != null) {
                Result_STR=EntityUtils.toString(resmarkMessagesReadFrom);
               // mMSGBox.setText(Result_STR);
            }
        }
        finally {
           
            }
       
return Result_STR;
    }
   
    /**
     * Performs an HTTP GET request to the specified url.
     *
     * @param url The web address to post the request to
     * @return The result of the request
     * @throws Exception
     */
    public static String executeHttpGet(String url) throws Exception {
        BufferedReader in = null;
        try {
            HttpClient client = getHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI(url));
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            String result = sb.toString();
            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Friday, October 28, 2011

Advance listview with image and text

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>

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());

    }

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;
    }


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;
       }

}