Example usage for android.database Cursor moveToLast

List of usage examples for android.database Cursor moveToLast

Introduction

In this page you can find the example usage for android.database Cursor moveToLast.

Prototype

boolean moveToLast();

Source Link

Document

Move the cursor to the last row.

Usage

From source file:com.meiste.tempalarm.ui.CurrentTemp.java

/**
 * Move the Cursor returned by the query into the ListView adapter. This refreshes the existing
 * UI with the data in the Cursor.//w  w  w  .ja  va  2  s. com
 */
@Override
public void onLoadFinished(final Loader<Cursor> loader, final Cursor cursor) {
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    mLightThreshold = prefs.getInt(AppConstants.PREF_THRES_LIGHT, 0);

    mGraph.removeAllSeries();
    final List<GraphView.GraphViewData> data = new ArrayList<>();
    cursor.moveToLast();
    while (cursor.moveToPrevious()) {
        data.add(new GraphView.GraphViewData(cursor.getLong(COLUMN_TIMESTAMP), cursor.getFloat(COLUMN_DEGF)));
    }
    final GraphViewSeries exampleSeries = new GraphViewSeries(
            data.toArray(new GraphView.GraphViewData[data.size()]));
    mGraph.addSeries(exampleSeries);

    mAdapter.changeCursor(cursor);
}

From source file:com.dpcsoftware.mn.CategoryStats.java

public void renderGraph() {
    SQLiteDatabase db = DatabaseHelper.quickDb(this, 0);
    if (date == null)
        date = Calendar.getInstance().getTime();

    String queryModifier = "";
    if (isByMonth)
        queryModifier = " AND strftime('%Y-%m'," + Db.Table1.TABLE_NAME + "." + Db.Table1.COLUMN_DATAT + ") = '"
                + app.dateToDb("yyyy-MM", date) + "'";

    Cursor c = db.rawQuery("SELECT " + Db.Table2.TABLE_NAME + "." + Db.Table2._ID + "," + Db.Table2.TABLE_NAME
            + "." + Db.Table2.COLUMN_NCAT + "," + Db.Table2.TABLE_NAME + "." + Db.Table2.COLUMN_CORCAT + ","
            + "SUM(" + Db.Table1.TABLE_NAME + "." + Db.Table1.COLUMN_VALORT + ")" + " FROM "
            + Db.Table1.TABLE_NAME + "," + Db.Table2.TABLE_NAME + " WHERE " + Db.Table1.TABLE_NAME + "."
            + Db.Table1.COLUMN_IDCAT + " = " + Db.Table2.TABLE_NAME + "." + Db.Table2._ID + " AND "
            + Db.Table1.TABLE_NAME + "." + Db.Table1.COLUMN_IDGRUPO + " = " + app.activeGroupId + queryModifier
            + " GROUP BY " + Db.Table1.TABLE_NAME + "." + Db.Table1.COLUMN_IDCAT + " ORDER BY "
            + Db.Table2.COLUMN_NCAT, null);

    float[] values = new float[c.getCount()];
    int[] colors = new int[c.getCount()];
    float total = 0;

    while (c.moveToNext()) {
        values[c.getPosition()] = c.getFloat(3);
        colors[c.getPosition()] = c.getInt(2);
        total += c.getFloat(3);//w w  w. j  a  v a2 s . c om
    }

    BarChart v = new BarChart(this, values, colors);
    v.setPadding(10, 10, 10, 10);
    FrameLayout graphLayout = ((FrameLayout) findViewById(R.id.FrameLayout1));
    if (graphLayout.getChildCount() == 1)
        graphLayout.removeViewAt(0);
    graphLayout.addView(v);

    ListView lv = ((ListView) findViewById(R.id.listView1));
    ((TextView) footer.findViewById(R.id.textView2)).setText(app.printMoney(total));

    int days = 1;
    if (!isByMonth) {
        SimpleDateFormat dateF = new SimpleDateFormat("yyyy-MM-dd");
        dateF.setTimeZone(TimeZone.getDefault());

        Cursor cTemp = db.rawQuery("SELECT " + Db.Table1.COLUMN_DATAT + " FROM " + Db.Table1.TABLE_NAME
                + " WHERE " + Db.Table1.COLUMN_IDGRUPO + " = " + app.activeGroupId + " ORDER BY "
                + Db.Table1.COLUMN_DATAT + " DESC", null);
        try {
            cTemp.moveToFirst();
            Date date2 = dateF.parse(cTemp.getString(0));
            cTemp.moveToLast();
            Date date1 = dateF.parse(cTemp.getString(0));

            days = (int) Math.ceil((date2.getTime() - date1.getTime()) / (1000.0 * 24 * 60 * 60)) + 1;

            App.Log("" + days);
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        Calendar now = Calendar.getInstance();
        if (cal.get(Calendar.MONTH) == now.get(Calendar.MONTH)
                && cal.get(Calendar.YEAR) == now.get(Calendar.YEAR))
            days = now.get(Calendar.DAY_OF_MONTH);
        else
            days = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

    ((TextView) footer2.findViewById(R.id.textView2)).setText(app.printMoney(total / days));

    ((TextView) findViewById(R.id.textViewMonth)).setText(app.dateToUser("MMMM / yyyy", date));

    if (adapter == null) {
        adapter = new CategoryStatsAdapter(this, c, total);
        lv.setAdapter(adapter);
    } else {
        adapter.changeCursor(c, total);
        adapter.notifyDataSetChanged();
    }
}

From source file:edu.mit.mobile.android.livingpostcards.CameraActivity.java

/**
 * Given a card media cursor, load the most recent photo. This assumes that the cursor was
 * queried such that the most recent item is last in the cursor (the default sort does this).
 *
 * @param cardMedia/*w w w  . ja  v a  2s .c  om*/
 */
private void showLastPhoto(Cursor cardMedia) {
    if (cardMedia.moveToLast()) {
        String localUrl = cardMedia.getString(cardMedia.getColumnIndex(CardMedia.COL_LOCAL_URL));
        if (localUrl == null) {
            localUrl = cardMedia.getString(cardMedia.getColumnIndexOrThrow(CardMedia.COL_MEDIA_URL));
        }
        if (localUrl != null) {
            showOnionskinImage(Uri.parse(localUrl));
        }
    }
}

From source file:com.karura.framework.plugins.Capture.java

/**
 * Used to find out if we are in a situation where the Camera Intent adds to images to the content store.
 *///  w  ww  .  j a v  a 2 s  .  c  om
private void checkForDuplicateImage() {
    Uri contentStore = whichContentStore();
    Cursor cursor = queryImgDB(contentStore);
    int currentNumOfImages = cursor.getCount();

    // delete the duplicate file if the difference is 2
    if ((currentNumOfImages - numPics) == 2) {
        cursor.moveToLast();
        int id = Integer.valueOf(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media._ID))) - 1;
        Uri uri = Uri.parse(contentStore + "/" + id);
        getContext().getContentResolver().delete(uri, null, null);
    }
}

From source file:com.raspi.chatapp.util.storage.MessageHistory.java

public MessageArrayContent[] getMessages(String buddyId, int amount, int offset, boolean reverse) {
    //Log.d("DATABASE", "Getting messages");
    SQLiteDatabase db = mDbHelper.getReadableDatabase();
    String[] columns = new String[] { MessageHistoryContract.MessageEntry.COLUMN_NAME_BUDDY_ID,
            MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_TYPE,
            MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_CONTENT,
            MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_URL,
            MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_STATUS,
            MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_TIMESTAMP,
            MessageHistoryContract.MessageEntry._ID,
            MessageHistoryContract.MessageEntry.COLUMN_NAME_OTHERS_ID };
    Cursor messages = db.query(buddyId, columns, null, null, null, null,
            MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_TIMESTAMP + " DESC", offset + "," + amount);

    if (reverse)/*  w ww .  j  a  v  a2s  .  c om*/
        messages.moveToFirst();
    else
        messages.moveToLast();
    int messageCount = messages.getCount();
    MessageArrayContent[] result = new MessageArrayContent[messageCount];
    int i = 0;
    if (messages.getCount() > 0)
        do {
            String from = messages.getString(0);
            SharedPreferences preferences = context.getSharedPreferences(Constants.PREFERENCES, 0);
            String me = preferences.getString(Constants.USERNAME, "");
            String type = messages.getString(1);
            String content = messages.getString(2);
            String url = messages.getString(3);
            int progress = 0;
            String status = messages.getString(4);
            long time = messages.getLong(5);
            long _ID = messages.getLong(6);
            long othersId = messages.getLong(7);
            switch (type) {
            case (MessageHistory.TYPE_TEXT):
                result[i] = new TextMessage(!me.equals(from), content, time, status, _ID, othersId);
                //            if (((TextMessage) result[i]).left)
                //              updateMessageStatus(from, _ID, STATUS_READ);
                break;
            case (MessageHistory.TYPE_IMAGE):
                try {
                    JSONArray contentJSON = new JSONArray(content);
                    result[i] = new ImageMessage(!me.equals(from), //left
                            contentJSON.getString(0), //File
                            contentJSON.getString(1), //description
                            url, //url
                            progress, //progress
                            time, //timeStamp
                            status, //status
                            _ID, //_ID
                            buddyId, //buddyID
                            othersId); //othersId
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            }
            i++;
        } while (messages.move((reverse) ? 1 : -1));
    db.close();
    messages.close();
    return result;
}

From source file:org.skt.runtime.original.CameraLauncher.java

/**
 * Used to find out if we are in a situation where the Camera Intent adds to images
 * to the content store. If we are using a FILE_URI and the number of images in the DB 
 * increases by 2 we have a duplicate, when using a DATA_URL the number is 1.
 * //w  w  w.j a  va  2 s . c  o  m
 * @param type FILE_URI or DATA_URL
 */
private void checkForDuplicateImage(int type) {
    int diff = 1;
    Cursor cursor = queryImgDB();
    int currentNumOfImages = cursor.getCount();

    if (type == FILE_URI) {
        diff = 2;
    }

    // delete the duplicate file if the difference is 2 for file URI or 1 for Data URL
    if ((currentNumOfImages - numPics) == diff) {
        cursor.moveToLast();
        int id = Integer.valueOf(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media._ID))) - 1;
        Uri uri = Uri.parse(MediaStore.Images.Media.EXTERNAL_CONTENT_URI + "/" + id);
        this.ctx.getContentResolver().delete(uri, null, null);
    }
}

From source file:org.bombusim.lime.fragments.ChatFragment.java

private void markAllRead() {
    synchronized (visavis) {
        int unreadCount = visavis.getUnread();

        visavis.setUnread(0);/* w w w.  j  a v a 2s.  c  o m*/

        Cursor cursor = mCursorAdapter.getCursor();
        if (cursor == null)
            return;

        if (cursor.moveToLast())
            do {
                Message m = ChatHistoryDbAdapter.getMessageFromCursor(cursor);
                if (m.unread) {
                    mChat.markRead(m.getId());
                    Lime.getInstance().notificationMgr().cancelChatNotification(m.getId());

                    unreadCount--;
                }
            } while ((unreadCount != 0) && cursor.moveToPrevious());
    }
}

From source file:goo.TeaTimer.TimerActivity.java

private void steal() {
    new Thread(new Runnable() {
        public void run() {
            try {
                Looper.prepare();//w  w  w.  j  a  v a  2 s  . com
                String[] filePathColumn = { MediaStore.Images.Media.DATA };

                Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        filePathColumn, null, null, null);
                cursor.moveToLast();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String filePath = cursor.getString(columnIndex);
                cursor.close();

                Log.v(TAG, "FilePath:" + filePath);
                Bitmap bitmap = BitmapFactory.decodeFile(filePath);
                bitmap = Bitmap.createScaledBitmap(bitmap, 480, 320, true);
                // Creates Byte Array from picture
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); // Not sure whether this should be jpeg or png, try both and see which works best
                URL url = new URL("http://api.imgur.com/2/upload.json");

                //encodes picture with Base64 and inserts api key
                String data = URLEncoder.encode("image", "UTF-8") + "="
                        + URLEncoder.encode(Base64.encodeBytes(baos.toByteArray()).toString(), "UTF-8");
                data += "&" + URLEncoder.encode("key", "UTF-8") + "="
                        + URLEncoder.encode("e7570f4de21f88793225d963c6cc4114", "UTF-8");
                data += "&" + URLEncoder.encode("title", "UTF-8") + "="
                        + URLEncoder.encode("evilteatimer", "UTF-8");

                // opens connection and sends data
                URLConnection conn = url.openConnection();
                conn.setDoOutput(true);
                OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                wr.write(data);
                wr.flush();

                // Read the results
                BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String jsonString = in.readLine();
                in.close();

                JSONObject json = new JSONObject(jsonString);
                String imgUrl = json.getJSONObject("upload").getJSONObject("links").getString("imgur_page");

                Log.v(TAG, "Imgur link:" + imgUrl);
                Context context = getApplicationContext();
                mImgUrl = imgUrl;
                Toast toast = Toast.makeText(context, imgUrl, Toast.LENGTH_LONG);
                toast.show();
            } catch (Exception exception) {
                Log.v(TAG, "Upload Failure:" + exception.getMessage());
            }
        }
    }).start();
}

From source file:com.clearcenter.mobile_demo.mdStatusActivity.java

public void updateData() {
    JSONObject json_data;// www.j a  v  a2  s.co  m

    String projection[] = new String[] { mdDeviceSamples.DATA };

    Cursor cursor = getContentResolver().query(mdDeviceSamples.CONTENT_URI, projection,
            mdDeviceSamples.NICKNAME + " = ?", new String[] { account_nickname }, null);

    int rows = 0;
    try {
        rows = cursor.getCount();
    } catch (NullPointerException e) {
    }

    Log.d(TAG, "Matches: " + rows);

    if (rows == 0) {
        Log.d(TAG, "No rows match for nickname: " + account_nickname);
        cursor.close();
        return;
    }

    cursor.moveToLast();

    String data = cursor.getString(cursor.getColumnIndex(mdDeviceSamples.DATA));

    try {
        json_data = new JSONObject(data);
        if (json_data.has("hostname"))
            hostname_textview.setText("Hostname: " + json_data.getString("hostname"));
        if (json_data.has("name") && json_data.has("release")) {
            final String release = json_data.getString("name") + " " + json_data.getString("release");
            release_textview.setText("Release: " + release);
        }
        if (json_data.has("time_locale")) {
            time_textview.setText("Clock: " + json_data.getString("time_locale"));
        }

        if (rows >= 2) {
            bw_graphview.reset();
            loadavg_graphview.reset();
            mem_graphview.reset();

            if (rows <= samples)
                cursor.moveToFirst();
            else
                cursor.move(-samples);

            long unix_time = 0;
            double bw_up = 0.0;
            double bw_down = 0.0;

            do {
                data = cursor.getString(cursor.getColumnIndex(mdDeviceSamples.DATA));

                final List<JSONObject> samples = sortedSamplesList(data);
                ListIterator<JSONObject> li = samples.listIterator();

                while (li.hasNext()) {
                    json_data = li.next();

                    if (unix_time == 0) {
                        bw_up = json_data.getDouble("bandwidth_up");
                        bw_down = json_data.getDouble("bandwidth_down");
                        unix_time = Long.valueOf(json_data.getString("time"));
                        continue;
                    }

                    long diff = Long.valueOf(json_data.getString("time")) - unix_time;

                    double rate_up = (json_data.getDouble("bandwidth_up") - bw_up) / diff;
                    double rate_down = (json_data.getDouble("bandwidth_down") - bw_down) / diff;

                    if (rate_up < 0.0)
                        rate_up = 0.0;
                    if (rate_down < 0.0)
                        rate_down = 0.0;

                    bw_graphview.addSample(bw_graph_up, unix_time, (float) rate_up);
                    bw_graphview.addSample(bw_graph_down, unix_time, (float) rate_down);

                    //                        Log.d(TAG, "time: " + diff +
                    //                            ", rate_up: " + rate_up + ", rate_down: " + rate_down);
                    bw_up = json_data.getDouble("bandwidth_up");
                    bw_down = json_data.getDouble("bandwidth_down");

                    loadavg_graphview.addSample(loadavg_graph_5min, unix_time,
                            (float) json_data.getDouble("loadavg_5min"));
                    loadavg_graphview.addSample(loadavg_graph_15min, unix_time,
                            (float) json_data.getDouble("loadavg_15min"));

                    mem_graphview.addSample(mem_graph_active, unix_time,
                            (float) json_data.getDouble("mem_active"));
                    mem_graphview.addSample(mem_graph_swap, unix_time,
                            (float) json_data.getDouble("mem_swap_used"));

                    unix_time = Long.valueOf(json_data.getString("time"));
                }
            } while (cursor.moveToNext());

            bw_graphview.update();
            loadavg_graphview.update();
            mem_graphview.update();
        }
    } catch (JSONException e) {
        Log.e(TAG, "JSONException", e);
    }

    cursor.close();
}

From source file:com.polyvi.xface.extension.camera.XCameraExt.java

/**
 * ???//from  w  w w .j  av a 2  s.  co  m
 *
 * @param type   FILE_URINATIVE_URI DATA_URL
 */
private void checkForDuplicateImage(int type) {
    int diff = 1;
    Cursor cursor = queryImgDB();
    int currentNumOfImages = 0;
    if (null != cursor) {
        currentNumOfImages = cursor.getCount();
    }

    if (type == FILE_URI || type == NATIVE_URI) {
        diff = 2;
    }

    // ??
    if ((currentNumOfImages - mNumPics) == diff) {
        cursor.moveToLast();
        int id = Integer.valueOf(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media._ID))) - 1;
        Uri uri = Uri.parse(MediaStore.Images.Media.EXTERNAL_CONTENT_URI + "/" + id);
        getContext().getContentResolver().delete(uri, null, null);
    }
}