Example usage for android.database.sqlite SQLiteDatabase rawQuery

List of usage examples for android.database.sqlite SQLiteDatabase rawQuery

Introduction

In this page you can find the example usage for android.database.sqlite SQLiteDatabase rawQuery.

Prototype

public Cursor rawQuery(String sql, String[] selectionArgs) 

Source Link

Document

Runs the provided SQL and returns a Cursor over the result set.

Usage

From source file:net.e_fas.oss.tabijiman.MapsActivity.java

@Override
public void parsed(ArrayList<HashMap> data, String category) {

    String Hash = AppSetting.Encrypt(String.valueOf(data));

    switch (category) {
    case "frame":
        if (AppSetting.isHashChanged(Hash, AppSetting.getUdFrameHash())) {

            e_print("make a new frame_dic in delegate.parsed");
            AppSetting.setUdFrameHash(Hash);

        } else {//from   ww  w . j  ava 2s .  co m
            e_print("Already Inserted Frame Data");
            setMarker(category);
            return;
        }
    case "place":
        if (AppSetting.isHashChanged(Hash, AppSetting.getUdPlaceHash())) {

            e_print("make a new place_dic in delegate.parsed");
            AppSetting.setUdPlaceHash(Hash);

        } else {
            e_print("Already Inserted Place Data");
            setMarker(category);
            return;
        }
    }

    String sql;
    print("Success");
    print("category >> " + category);

    if (category.equals("frame")) {

        e_print("delete all data from frameTable");
        db.execSQL("delete from frame");

    } else {

        e_print("delete all data from placeTable");
        db.execSQL("delete from place");
    }

    for (HashMap test : data) {

        if (category.equals("frame") && !test.containsKey("status")) {

            print("switch - frame");

            String name = test.containsKey("name") ? test.get("name").toString() : "";
            String desc = test.containsKey("desc") ? test.get("desc").toString() : "";
            String lat = test.containsKey("lat") ? test.get("lat").toString() : "";
            String lng = test.containsKey("lng") ? test.get("lng").toString() : "";
            String img = test.containsKey("img") ? test.get("img").toString() : "";
            String area = test.containsKey("area") ? test.get("area").toString() : "";

            sql = "REPLACE INTO frame( name, desc, lat, lng, img, area, getFlag ) VALUES("
                    + DatabaseUtils.sqlEscapeString(name) + "," + DatabaseUtils.sqlEscapeString(desc) + ","
                    + DatabaseUtils.sqlEscapeString(lat) + "," + DatabaseUtils.sqlEscapeString(lng) + ","
                    + DatabaseUtils.sqlEscapeString(img) + "," + DatabaseUtils.sqlEscapeString(area) + ","
                    + DatabaseUtils.sqlEscapeString(String.valueOf(0)) + ")";

            print("SQL_QUERY >> " + sql);

            //DB()??
            SQLiteDatabase dbRead = helper.getReadableDatabase();
            //SQL
            String select_sql = "SELECT `name`, `lat`, `lng` FROM frame WHERE `name` = ? AND `lat` = ? AND `lng` = ?";
            //SQL?
            Cursor cursor = dbRead.rawQuery(select_sql, new String[] { name, lat, lng });
            //???
            cursor.moveToFirst();

            if (cursor.getCount() == 0) {
                db.execSQL(sql);
                print("frame_insert >> true");
            } else {
                print("frame_insert >> false");
            }

            cursor.close();
        } else if (category.equals("place")) {

            print("switch - place");

            String name = test.containsKey("name") ? test.get("name").toString() : "";
            String address = test.containsKey("address") ? test.get("address").toString() : "";
            String desc = test.containsKey("desc") ? test.get("desc").toString() : "";
            String lat = test.containsKey("lat") ? test.get("lat").toString() : "";
            String lng = test.containsKey("lng") ? test.get("lng").toString() : "";
            String img = test.containsKey("img") ? test.get("img").toString() : "";

            sql = "REPLACE INTO place( name, address, desc, lat, lng, img, getFlag ) VALUES("
                    + DatabaseUtils.sqlEscapeString(name) + "," + DatabaseUtils.sqlEscapeString(address) + ","
                    + DatabaseUtils.sqlEscapeString(desc) + "," + DatabaseUtils.sqlEscapeString(lat) + ","
                    + DatabaseUtils.sqlEscapeString(lng) + "," + DatabaseUtils.sqlEscapeString(img) + ","
                    + DatabaseUtils.sqlEscapeString(String.valueOf(1)) + ")";

            print("SQL_QUERY >> " + sql);

            //DB()??
            SQLiteDatabase dbRead = helper.getReadableDatabase();
            //SQL
            String select_sql = "SELECT `name`, `lat`, `lng` FROM place WHERE `name` = ? AND `lat` = ? AND `lng` = ?";
            print("select_sql >> " + select_sql);
            //SQL?
            Cursor cursor = dbRead.rawQuery(select_sql, new String[] { name, lat, lng });

            print("cursor_count >> " + cursor.getCount());

            if (cursor.getCount() == 0) {
                db.execSQL(sql);
                print("place_insert >> true");
            } else {
                print("place_insert >> false");
            }

            cursor.close();
        }
    }

    print("setMarker >> true");
    setMarker(category);
}

From source file:com.HskPackage.HskNamespace.HSK1ProjectActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);//from w  ww  . j  ava2s  . c o m

    final TextView codice = (TextView) findViewById(R.id.codice);
    final Button carattere = (Button) findViewById(R.id.carattere);
    final TextView fonetica = (TextView) findViewById(R.id.fonetica);
    final TextView significato = (TextView) findViewById(R.id.significato);

    /*********** CREATE A DATABASE ******************************************************/
    final String DB_PATH = "/data/data/com.HskPackage.HskNamespace/";
    final String DB_NAME = "chineseX.db";
    SQLiteDatabase db = null;

    boolean exists = (new File(DB_PATH + DB_NAME)).exists();

    AssetManager assetManager = getAssets();

    if (!exists) {
        try {
            InputStream in = assetManager.open(DB_NAME);
            OutputStream out = new FileOutputStream(DB_PATH + DB_NAME);
            copyFile(in, out);
            in.close();
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        File dbFile = new File(DB_PATH + DB_NAME);
        db = SQLiteDatabase.openOrCreateDatabase(dbFile, null);
    } else {
        File dbFile = new File(DB_PATH + DB_NAME);
        db = SQLiteDatabase.openOrCreateDatabase(dbFile, null);
    }

    final Integer valore = 1;
    //String query = "SELECT * FROM chineseX";
    String query = "SELECT * FROM chineseX where _id = ? ";
    String[] selectionArgs = { valore.toString() };
    Cursor cursor = null;
    cursor = db.rawQuery(query, selectionArgs);
    //cursor = db.rawQuery(query, null);
    int count = cursor.getCount();
    System.out.println("il numero di dati contenuti nel database " + count);
    while (cursor.moveToNext()) {
        long id = cursor.getLong(0);
        System.out.println("Questo  l'ID ====>" + id);
        scodice = cursor.getString(1);
        codice.setText(scodice);
        System.out.println("Questo  il codice ====>" + codice);
        scarattere = cursor.getString(2);
        carattere.setText(scarattere);
        System.out.println("Questo  il carattere ====>" + carattere);
        sfonetica = cursor.getString(3);
        fonetica.setText(sfonetica);
        System.out.println("Questo  il fonet ====>" + fonetica);

        ssignificato = cursor.getString(4);
        significato.setText("?? - Visualizza Significato");
        System.out.println("Questo  il carattere ====>" + ssignificato);
    }
    //fine
    db.close();

    //set up sound button
    final MediaPlayer mpButtonClick = MediaPlayer.create(this, R.raw.hangout_ringtone);

    //final MediaPlayer chword001 = MediaPlayer.create(this, R.raw.ayi001);

    /*
                    
            // set up change Images 
                    
            miaImmagine = (ImageView) findViewById(R.id.Image); 
            // dichiaro  l'oggetto image view
                 
            miaImmagine.setImageResource(R.drawable.uno1);
            // associo l'immagine alla  figura uno
               
            // setto un evento di cattura del click sull'immagine
            miaImmagine.setOnClickListener( new OnClickListener() 
            {
                public void onClick(View arg0) {
                   //chword001.start();
                }       
            }) ;
          */

    final Intent first = new Intent(this, Activity2.class);
    final Intent immagine = new Intent(this, Activity3.class);

    /*
     * Un intent  definito nella javadoc della classe android.content.Intent come una 
     * "descrizione astratta dell'operazione da eseguire".
     * E un intent ESPLICITO perch cosciamo il destinatario.
     * Passiamo come parametri il context attuale ed la classe che identifica l'activity di destinazione.
     * E' importante che la classe sia registrata nell'AndroidManifest.xml
     * */

    Button b = (Button) this.findViewById(R.id.button1);
    Button b2 = (Button) this.findViewById(R.id.button2);
    Button b3 = (Button) this.findViewById(R.id.carattere);

    b.setOnClickListener(new OnClickListener() {
        public void onClick(View arg0) {
            Integer valore = 1;
            valore = valore + 1;
            if (valore >= 153) {
                valore = 1;
            }

            System.out.println("AVANTI" + valore);
            first.putExtra("AVANTI", valore);
            startActivity(first);
            finish();
            mpButtonClick.start();
        }
    });

    b2.setOnClickListener(new OnClickListener() {
        public void onClick(View arg0) {

            Integer valore = 153;

            System.out.println("AVANTI == >" + valore);
            first.putExtra("AVANTI", valore);
            startActivity(first);
            finish();
            mpButtonClick.start();
        }
    });

    b3.setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) {

            Integer valore = 1;

            System.out.println("AVANTI" + valore);

            immagine.putExtra("AVANTI", valore);

            startActivity(immagine);
            finish();
            mpButtonClick.start();
        }
    });
}

From source file:com.openerp.orm.ORM.java

/**
 * Database tables./*from  w w  w  . j ava2s. co  m*/
 * 
 * @return the string[]
 */
public String[] databaseTables() {
    String[] tables_list = null;
    List<String> tables = new ArrayList<String>();
    SQLiteDatabase db = getWritableDatabase();
    Cursor cursor = db.rawQuery("SELECT * FROM sqlite_master WHERE type='table';", null);
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        String tableName = cursor.getString(1);
        if (!tableName.equals("android_metadata") && !tableName.equals("sqlite_sequence"))
            tables.add(tableName);
        cursor.moveToNext();
    }
    cursor.close();
    tables_list = tables.toArray(new String[tables.size()]);
    return tables_list;
}

From source file:net.e_fas.oss.tabijiman.MapsActivity.java

@Override
public void onMapReady(GoogleMap googleMap) {

    e_print("onMapReady");
    mMap = googleMap;/*from w  w  w . j  a  v  a2 s  . co  m*/

    GoFukuiButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            CameraPosition cameraPos = new CameraPosition.Builder().target(new LatLng(36.0642988, 136.220012))
                    .zoom(10.0f).bearing(0).build();
            mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPos));
            GoFukuiButton.setVisibility(View.GONE);
        }
    });

    CameraPosition cameraPos = new CameraPosition.Builder().target(new LatLng(36.0614444, 136.2229937))
            .zoom(zoomLevel).bearing(0).build();
    mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPos));

    // ??
    mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(Marker marker) {
            Toast.makeText(getApplicationContext(), marker.getTitle(), Toast.LENGTH_LONG).show();
            return false;
        }
    });

    mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
        @Override
        public View getInfoWindow(Marker marker) {
            return null;
        }

        @Override
        public View getInfoContents(Marker marker) {

            View view = getLayoutInflater().inflate(R.layout.info_window, null);
            // 
            TextView title = (TextView) view.findViewById(R.id.info_title);
            title.setText(marker.getTitle());
            e_print("marker_Snippet >> " + marker.getSnippet());

            if (marker.getSnippet() == null) {
                view.findViewById(R.id.info_address).setVisibility(View.GONE);
            } else {
                TextView address = (TextView) view.findViewById(R.id.info_address);
                address.setText(marker.getSnippet());
            }
            return view;
        }
    });

    mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
        @Override
        public void onInfoWindowClick(Marker marker) {

            e_print("title_name >> " + marker.getTitle());

            //DB()??
            SQLiteDatabase dbRead = helper.getReadableDatabase();

            //SQL
            String select_frame_sql = "SELECT * FROM frame WHERE `name` = ? AND `lat` = ? AND `lng` = ?";
            String select_place_sql = "SELECT * FROM place WHERE `name` = ? AND `lat` = ? AND `lng` = ?";
            //SQL?
            Cursor cursor = dbRead.rawQuery(select_place_sql,
                    new String[] { marker.getTitle(), String.valueOf(marker.getPosition().latitude),
                            String.valueOf(marker.getPosition().longitude) });

            e_print("cursor_count >> " + cursor.getCount());

            if (cursor.getCount() != 0) {

                cursor.moveToFirst();

                e_print("lat >> " + marker.getPosition().latitude + " lng >> "
                        + marker.getPosition().longitude);

                Intent MoreInfo = new Intent(getApplicationContext(), MoreInfo.class);
                MoreInfo.putExtra("id", cursor.getInt(cursor.getColumnIndex("_id")));
                MoreInfo.putExtra("cat", "place");

                cursor.close();

                startActivity(MoreInfo);
            } else {

                cursor.close();

                //SQL?
                Cursor cursor2 = dbRead.rawQuery(select_frame_sql,
                        new String[] { marker.getTitle(), String.valueOf(marker.getPosition().latitude),
                                String.valueOf(marker.getPosition().longitude) });
                cursor2.moveToFirst();

                /*
                 * distance[0] = [??]
                 * distance[1] = [???]
                 * distance[2] = [???]
                 */
                float[] distance = getDistance(nowLocation.latitude, nowLocation.longitude,
                        marker.getPosition().latitude, marker.getPosition().longitude);

                Intent MoreInfo = new Intent(getApplicationContext(), MoreInfo.class);
                MoreInfo.putExtra("dist", distance[0]);
                MoreInfo.putExtra("id", cursor2.getInt(cursor2.getColumnIndex("_id")));
                MoreInfo.putExtra("cat", "frame");

                cursor2.close();

                startActivity(MoreInfo);
            }

        }
    });

    mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
        @Override
        public boolean onMyLocationButtonClick() {
            Location location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            e_print("MyLocation >> " + location);

            Toast.makeText(getApplicationContext(), "location >> " + location, Toast.LENGTH_SHORT).show();
            return false;
        }
    });

    mMap.setMyLocationEnabled(true);
    // MyLocationButton?
    UiSettings settings = mMap.getUiSettings();
    settings.setMyLocationButtonEnabled(true);

    //??
    View locationButton = ((View) super.findViewById(Integer.parseInt("1")).getParent())
            .findViewById(Integer.parseInt("2"));

    RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams) locationButton.getLayoutParams();
    rlp.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
    rlp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
    rlp.setMargins(0, 0, 180, 180);

    print("mMap >> insert");

    for (String provider : providers) {

        e_print("enable_providers >> " + provider);
        mLocationManager.requestLocationUpdates(provider, 3000, 0, this);
    }

    if (mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {

        e_print("Provider_enable >> NETWORK");

        mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 0, this);

    } else if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {

        e_print("Providers_enable >> GPS");

        mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, this);
    } else {

        e_print("All_Providers_Disable");

    }
}

From source file:com.openerp.orm.ORM.java

public List<HashMap<String, Object>> executeSQL(String sqlQuery, String[] args) {
    SQLiteDatabase db = getWritableDatabase();

    List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();

    Cursor cursor = db.rawQuery(sqlQuery.toString(), args);
    String[] columns = cursor.getColumnNames();
    if (cursor.moveToFirst()) {
        do {//  ww w.ja va 2  s.  c  o  m
            HashMap<String, Object> row = new HashMap<String, Object>();
            if (cursor.getColumnIndex("oea_name") > 0) {
                if (!cursor.getString(cursor.getColumnIndex("oea_name")).equals(user_name)) {
                    continue;
                }
            } else {
                Log.e("ORM::executeSQL() - Column name missing",
                        "You must have to provide oea_name column in your sql syntax.");
                return null;
            }
            for (String key : columns) {
                row.put(key, cursor.getString(cursor.getColumnIndex(key)));
            }
            data.add(row);
        } while (cursor.moveToNext());
    }
    db.close();
    cursor.close();
    return data;
}

From source file:org.rapidandroid.activity.chart.form.FormDataBroker.java

private JSONGraphData loadNumericLine() {
    Date startDateToUse = getStartDate();

    SQLiteDatabase db = rawDB.getReadableDatabase();

    String fieldcol = RapidSmsDBConstants.FormData.COLUMN_PREFIX + fieldToPlot.getName();
    StringBuilder rawQuery = new StringBuilder();
    rawQuery.append("select rapidandroid_message.time, " + fieldcol);
    rawQuery.append(" from ");
    rawQuery.append(RapidSmsDBConstants.FormData.TABLE_PREFIX + mForm.getPrefix());

    rawQuery.append(" join rapidandroid_message on (");
    rawQuery.append(RapidSmsDBConstants.FormData.TABLE_PREFIX + mForm.getPrefix());
    rawQuery.append(".message_id = rapidandroid_message._id");
    rawQuery.append(") ");

    if (startDateToUse.compareTo(Constants.NULLDATE) != 0 && mEndDate.compareTo(Constants.NULLDATE) != 0) {
        rawQuery.append(" WHERE rapidandroid_message.time > '" + Message.SQLDateFormatter.format(startDateToUse)
                + "' AND rapidandroid_message.time < '" + Message.SQLDateFormatter.format(mEndDate) + "' ");
    }/*from  w  w w. jav  a2 s.c  o  m*/

    rawQuery.append(" order by rapidandroid_message.time ASC");

    // the string value is column 0
    // the magnitude is column 1

    Cursor cr = db.rawQuery(rawQuery.toString(), null);
    int barCount = cr.getCount();

    if (barCount == 0) {
        cr.close();
    } else {
        Date[] xVals = new Date[barCount];
        int[] yVals = new int[barCount];
        cr.moveToFirst();
        int i = 0;
        do {
            try {
                xVals[i] = Message.SQLDateFormatter.parse(cr.getString(0));
                yVals[i] = cr.getInt(1);
            } catch (Exception ex) {

            }
            i++;
        } while (cr.moveToNext());

        // xaxis: { ticks: [0, [Math.PI/2, "\u03c0/2"], [Math.PI, "\u03c0"],
        // [Math.PI * 3/2, "3\u03c0/2"], [Math.PI * 2, "2\u03c0"]]},

        try {
            return new JSONGraphData(prepareDateData(xVals, yVals),
                    loadOptionsForDateGraph(xVals, false, DateDisplayTypes.Daily));
        } catch (Exception ex) {

        } finally {
            if (!cr.isClosed()) {
                cr.close();
            }
        }

    }
    // either there was no data or something bad happened
    return new JSONGraphData(getEmptyData(), new JSONObject());
}

From source file:org.rapidandroid.activity.chart.form.FormDataBroker.java

/**
 * Should return a two element array - the first element is the data, the
 * second are the options//  w  w  w .j  a  v a  2 s . co  m
 * 
 * @return
 */
private JSONGraphData loadHistogramFromField() {
    // JSONObject result = new JSONObject();
    SQLiteDatabase db = rawDB.getReadableDatabase();

    String fieldcol = RapidSmsDBConstants.FormData.COLUMN_PREFIX + fieldToPlot.getName();
    StringBuilder rawQuery = new StringBuilder();
    rawQuery.append("select " + fieldcol);
    rawQuery.append(", count(*) from ");
    rawQuery.append(RapidSmsDBConstants.FormData.TABLE_PREFIX + mForm.getPrefix());

    rawQuery.append(" join rapidandroid_message on (");
    rawQuery.append(RapidSmsDBConstants.FormData.TABLE_PREFIX + mForm.getPrefix());
    rawQuery.append(".message_id = rapidandroid_message._id");
    rawQuery.append(") ");

    if (mStartDate.compareTo(Constants.NULLDATE) != 0 && mEndDate.compareTo(Constants.NULLDATE) != 0) {
        rawQuery.append(" WHERE rapidandroid_message.time > '" + Message.SQLDateFormatter.format(mStartDate)
                + "' AND rapidandroid_message.time < '" + Message.SQLDateFormatter.format(mEndDate) + "' ");
    }

    rawQuery.append(" group by " + fieldcol);
    rawQuery.append(" order by " + fieldcol);

    // the string value is column 0
    // the magnitude is column 1

    Cursor cr = db.rawQuery(rawQuery.toString(), null);
    int barCount = cr.getCount();

    if (barCount != 0) {
        String[] xVals = new String[barCount];
        int[] yVals = new int[barCount];
        cr.moveToFirst();
        int i = 0;
        do {
            xVals[i] = cr.getString(0);
            yVals[i] = cr.getInt(1);
            i++;
        } while (cr.moveToNext());

        // xaxis: { ticks: [0, [Math.PI/2, "\u03c0/2"], [Math.PI, "\u03c0"],
        // [Math.PI * 3/2, "3\u03c0/2"], [Math.PI * 2, "2\u03c0"]]},

        try {
            // result.put("label", fieldToPlot.getName());
            // result.put("data", prepareData(xVals, yVals));
            // result.put("bars", getShowTrue());
            // result.put("xaxis", getXaxisOptions(xVals));
            return new JSONGraphData(prepareHistogramData(xVals, yVals), loadOptionsForHistogram(xVals));
        } catch (Exception ex) {

        } finally {
            if (!cr.isClosed()) {
                cr.close();
            }
            if (db.isOpen()) {
                db.close();
            }
        }
    }
    // either there was no data or something bad happened
    return new JSONGraphData(getEmptyData(), new JSONObject());
}

From source file:com.fitforbusiness.nafc.dashboard.DashBoardFragment.java

private void loadSessions(String date) {

    Calendar calendar = Calendar.getInstance();
    date = String.format("%d-%02d-%02d", calendar.get(Calendar.YEAR), (calendar.get(Calendar.MONTH) + 1),
            calendar.get(Calendar.DAY_OF_MONTH));
    Date stDate = null;//from w ww.  j  a  v a2 s.c o m
    Date edDate = null;
    try {
        stDate = new SimpleDateFormat("yyyy-MM-dd").parse(date);
        stDate.setTime(stDate.getTime() - 1000);
        edDate = new SimpleDateFormat("yyyy-MM-dd").parse(date);
        edDate.setTime(edDate.getTime() + (24 * 60 * 60 * 1000));
        edDate.setTime(edDate.getTime() - 1000);
    } catch (Exception e) {
        e.printStackTrace();
        return;
    }

    ArrayList<HashMap<String, Object>> mapArrayList = new ArrayList<>();
    SQLiteDatabase sqlDB;
    try {
        sqlDB = DatabaseHelper.instance().getReadableDatabase();

        String query = "select  " + Table.Sessions.ID + " , " + Table.Sessions.START_DATE + " , "
                + Table.Sessions.START_TIME + " , " + Table.Sessions.SESSION_STATUS + " , "
                + Table.Sessions.GROUP_ID + " , " + Table.Sessions.IS_NATIVE + " , "
                + Table.Sessions.RECURRENCE_RULE + " , " + Table.Sessions.TITLE + " , "
                + Table.Sessions.SESSION_TYPE + "  " + " from " + Table.Sessions.TABLE_NAME + " where "
                + Table.DELETED + " = 0 " + " and ( " + Table.Sessions.START_DATE + " =  datetime(\'" + date
                + "\') " + " OR  " + Table.Sessions.RECURRENCE_RULE + " IS NOT NULL " + "       OR "
                + Table.Sessions.RECURRENCE_RULE + " != '' ) ";

        Log.d("query is ", query);
        assert sqlDB != null;
        Cursor cursor = sqlDB.rawQuery(query, null);

        Log.d("Calendar", "Month Count = " + cursor.getCount());

        LinkedHashMap<String, Object> row;
        while (cursor.moveToNext()) {

            if (cursor.getString(cursor.getColumnIndex(Table.Sessions.RECURRENCE_RULE)) == null
                    || cursor.getString(cursor.getColumnIndex(Table.Sessions.RECURRENCE_RULE)).equals("")) {

                row = new LinkedHashMap<String, Object>();

                long groupSessionId = cursor.getInt(cursor.getColumnIndex(Table.Sessions.GROUP_ID));
                int session_type = cursor.getInt(cursor.getColumnIndex(Table.Sessions.SESSION_TYPE));
                rowData = getImageName(groupSessionId + "", session_type);

                row.put("_id", cursor.getString(cursor.getColumnIndex(Table.Sessions.ID)));
                row.put("name",
                        Utils.dateConversionForRow(
                                cursor.getString(cursor.getColumnIndex(Table.Sessions.START_DATE))) + " "
                                + Utils.timeFormatAMPM(
                                        cursor.getString(cursor.getColumnIndex(Table.Sessions.START_TIME))));

                row.put("rowId", groupSessionId);
                row.put("type", session_type);

                if (cursor.getInt(cursor.getColumnIndex(Table.Sessions.IS_NATIVE)) == 1) {

                    row.put("secondLabel", cursor.getString(cursor.getColumnIndex(Table.Sessions.TITLE)));
                    row.put("thirdLabel", getActivity().getString(R.string.lblNativeStatus));
                    Log.d("Calendar", "native events");
                } else if (rowData.getImageName() != null && rowData.getImageName().length() > 0) {
                    row.put("photo", rowData.getImageName());
                    row.put("secondLabel", rowData.getPersonName());
                    row.put("thirdLabel",
                            status[cursor.getInt(cursor.getColumnIndex(Table.Sessions.SESSION_STATUS))]);

                    Log.d("Calendar", "app events");
                }
                Log.d("Calendar", (String) row.get("secondLabel"));
                mapArrayList.add(row);
            } else {
                String rule = cursor.getString(cursor.getColumnIndex(Table.Sessions.RECURRENCE_RULE));

                RecurrenceRule recRule = new RecurrenceRule(rule);
                RecurrenceRule.Freq freq = recRule.getFreq();

                Date d = new SimpleDateFormat("dd MMM yyyy").parse(Utils.formatConversionSQLite(
                        cursor.getString(cursor.getColumnIndex(Table.Sessions.START_DATE))));

                switch (freq) {
                case MONTHLY:
                    d.setMonth(stDate.getMonth());
                case YEARLY:
                    d.setYear(stDate.getYear());
                }

                if (freq == RecurrenceRule.Freq.MONTHLY || freq == RecurrenceRule.Freq.YEARLY) {
                    if (!(d.after(stDate) && d.before(edDate)))
                        continue;
                }

                ArrayList<Calendar> dates;
                dates = CalendarMonthViewFragment.ruleOccurONDate(rule, stDate, edDate);

                Log.e("RecurRule", "size = " + dates.size());

                if (dates.size() > 0) {
                    row = new LinkedHashMap<String, Object>();

                    if (freq == RecurrenceRule.Freq.DAILY || freq == RecurrenceRule.Freq.WEEKLY) {
                        if (d.after(dates.get(0).getTime()))
                            continue;
                    }

                    long groupSessionId = cursor.getInt(cursor.getColumnIndex(Table.Sessions.GROUP_ID));
                    int session_type = cursor.getInt(cursor.getColumnIndex(Table.Sessions.SESSION_TYPE));
                    rowData = getImageName(groupSessionId + "", session_type);
                    row.put("_id", cursor.getString(cursor.getColumnIndex(Table.Sessions.ID)));
                    row.put("name", Utils.formatConversionDateOnly(stDate) + " " + Utils.timeFormatAMPM(
                            cursor.getString(cursor.getColumnIndex(Table.Sessions.START_TIME))));

                    row.put("rowId", groupSessionId);
                    row.put("type", session_type);

                    if (cursor.getInt(cursor.getColumnIndex(Table.Sessions.IS_NATIVE)) == 1) {

                        row.put("secondLabel", cursor.getString(cursor.getColumnIndex(Table.Sessions.TITLE)));
                        row.put("thirdLabel", getActivity().getString(R.string.lblNativeStatus));
                        Log.d("Calendar", "native events");
                    } else if (rowData.getImageName() != null && rowData.getImageName().length() > 0) {
                        row.put("photo", rowData.getImageName());
                        row.put("secondLabel", rowData.getPersonName());
                        row.put("thirdLabel",
                                status[cursor.getInt(cursor.getColumnIndex(Table.Sessions.SESSION_STATUS))]);

                        Log.d("Calendar", "app events");
                    }
                    Log.d("Calendar", (String) row.get("secondLabel"));
                    mapArrayList.add(row);
                }
            }
        }
        cursor.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    CustomAsyncTaskListAdapter adapter = new CustomAsyncTaskListAdapter(getActivity(),
            R.layout.calendar_day_view_session_row, R.id.ivRowImage, R.id.tvFirstName, R.id.tvSecondLabel,
            R.id.tvThirdLabel, mapArrayList);
    sessionList.setAdapter(adapter);
}

From source file:com.openerp.orm.ORM.java

/**
 * Execute sql query as per user requirement.
 * /* w  ww.j a va  2  s  .c  o  m*/
 * @param model
 *            the model
 * @param columns
 *            the columns
 * @param where
 *            the where
 * @param args
 *            the args query arguments
 * @return the cursor of results
 */
public List<HashMap<String, Object>> executeSQL(String model, String[] columns, String[] where, String[] args) {
    SQLiteDatabase db = getWritableDatabase();
    StringBuffer sqlQuery = new StringBuffer();
    sqlQuery.append("SELECT ");
    sqlQuery.append(TextUtils.join(",", columns));
    sqlQuery.append(" FROM ");
    sqlQuery.append(modelToTable(model));
    sqlQuery.append(" WHERE ");
    sqlQuery.append(TextUtils.join(" ", where));

    List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();

    Cursor cursor = db.rawQuery(sqlQuery.toString(), args);
    if (cursor.moveToFirst()) {
        do {
            HashMap<String, Object> row = new HashMap<String, Object>();
            for (String key : columns) {
                row.put(key, cursor.getString(cursor.getColumnIndex(key)));
            }
            data.add(row);
        } while (cursor.moveToNext());
    }
    db.close();
    cursor.close();
    return data;

}

From source file:org.dharmaseed.android.PlayTalkActivity.java

private Cursor getCursor() {
    SQLiteDatabase db = dbManager.getReadableDatabase();
    String query = String.format(
            "SELECT %s, %s.%s, %s, %s, %s, %s, %s, %s, %s, %s.%s AS teacher_name, %s.%s AS center_name, "
                    + "%s.%s FROM %s, %s, %s WHERE %s.%s=%s.%s AND %s.%s=%s.%s AND %s.%s=%s",
            DBManager.C.Talk.TITLE, DBManager.C.Talk.TABLE_NAME, DBManager.C.Talk.DESCRIPTION,
            DBManager.C.Talk.AUDIO_URL, DBManager.C.Talk.DURATION_IN_MINUTES, DBManager.C.Talk.RECORDING_DATE,
            DBManager.C.Talk.UPDATE_DATE, DBManager.C.Talk.RETREAT_ID, DBManager.C.Talk.FILE_PATH,
            DBManager.C.Talk.TEACHER_ID, DBManager.C.Teacher.TABLE_NAME, DBManager.C.Teacher.NAME,
            DBManager.C.Center.TABLE_NAME, DBManager.C.Center.NAME,

            DBManager.C.Teacher.TABLE_NAME, DBManager.C.Teacher.ID,

            // FROM
            DBManager.C.Talk.TABLE_NAME, DBManager.C.Teacher.TABLE_NAME, DBManager.C.Center.TABLE_NAME,

            // WHERE
            DBManager.C.Talk.TABLE_NAME, DBManager.C.Talk.TEACHER_ID, DBManager.C.Teacher.TABLE_NAME,
            DBManager.C.Teacher.ID,//from w w  w  .ja  v  a  2 s.  c  om

            DBManager.C.Talk.TABLE_NAME, DBManager.C.Talk.VENUE_ID, DBManager.C.Center.TABLE_NAME,
            DBManager.C.Center.ID,

            DBManager.C.Talk.TABLE_NAME, DBManager.C.Talk.ID, talkID);

    return db.rawQuery(query, null);
}