Example usage for android.database Cursor getCount

List of usage examples for android.database Cursor getCount

Introduction

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

Prototype

int getCount();

Source Link

Document

Returns the numbers of rows in the cursor.

Usage

From source file:com.aniruddhc.acemusic.player.AsyncTasks.AsyncGetAlbumArtTask.java

@Override
protected Integer doInBackground(String... params) {
    /************************************************************************************************
     * RETRIEVE THE HTTP SEARCH RESPONSE FROM ITUNES SERVERS.
     ************************************************************************************************/

    //First, we'll make a HTTP request to iTunes' servers with the album and artist name.
    if (params.length == 2) {
        artist = params[0];//from  ww w  .j a v a2s . c  o  m
        album = params[1];

        //Create duplicate strings that will be filtered out for the URL.
        urlArtist = artist;
        urlAlbum = album;

        //Remove any unacceptable characters.
        if (urlArtist.contains("#")) {
            urlArtist = urlArtist.replace("#", "");
        }

        if (urlArtist.contains("$")) {
            urlArtist = urlArtist.replace("$", "");
        }

        if (urlArtist.contains("@")) {
            urlArtist = urlArtist.replace("@", "");
        }

        if (urlAlbum.contains("#")) {
            urlAlbum = urlAlbum.replace("#", "");
        }

        if (urlAlbum.contains("$")) {
            urlAlbum = urlAlbum.replace("$", "");
        }

        if (urlAlbum.contains("@")) {
            urlAlbum = urlAlbum.replace("@", "");
        }

        //Replace any spaces in the artist and album fields with "%20".
        if (urlArtist.contains(" ")) {
            urlArtist = urlArtist.replace(" ", "%20");
        }

        if (urlAlbum.contains(" ")) {
            urlAlbum = urlAlbum.replace(" ", "%20");
        }

    }

    //Construct the url for the HTTP request.
    URL uri = null;
    try {
        uri = new URL("http://itunes.apple.com/search?term=" + urlArtist + "+" + urlAlbum + "&entity=album");
    } catch (MalformedURLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        return 1;
    }

    try {
        //Create a new HTTP connection.
        HttpURLConnection urlConnection = (HttpURLConnection) uri.openConnection();
        urlConnection.connect();

        //Set the destination directory for the xml file.
        File SDCardRoot = Environment.getExternalStorageDirectory();
        file = new File(SDCardRoot, "albumArt.xml");

        //Create the OuputStream that will be used to store the downloaded data into the file.
        FileOutputStream fileOutput = new FileOutputStream(file);

        //Create the InputStream that will read the data from the HTTP connection.
        InputStream inputStream = urlConnection.getInputStream();

        //Total size of target file.
        int totalSize = urlConnection.getContentLength();

        //Temp variable that stores the number of downloaded bytes.
        int downloadedSize = 0;

        //Create a buffer to store the downloaded bytes.
        byte[] buffer = new byte[1024];
        int bufferLength = 0;

        //Now read through the buffer and write the contents to the file.
        while ((bufferLength = inputStream.read(buffer)) > 0) {
            fileOutput.write(buffer, 0, bufferLength);
            downloadedSize += bufferLength;

        }

        //Close the File Output Stream.
        fileOutput.close();

    } catch (MalformedURLException e) {
        //TODO Auto-generated method stub
        e.printStackTrace();
        return 1;
    } catch (IOException e) {
        // TODO Auto-generated method stub
        e.printStackTrace();
        return 1;
    }

    //Create a File object that points to the downloaded file.
    File phpSource = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/albumArt.xml");
    String phpAsString = null;
    try {
        phpAsString = FileUtils.readFileToString(phpSource);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return 1;
    }

    //Extract the albumArt parameter from the PHP response.
    artworkURL = StringUtils.substringBetween(phpAsString, "\"artworkUrl100\":\"", "\",");
    if (artworkURL == null) {

        //Check and see if a lower resolution image available.
        artworkURL = StringUtils.substringBetween(phpAsString, "\"artworkUrl60\":\"", "\",");

        if (artworkURL == null) {
            URL_RETRIEVED = false;
            return 1;
        } else {
            //Replace "100x100" with "600x600" to retrieve larger album art images.
            artworkURL = artworkURL.replace("100x100", "600x600");
            URL_RETRIEVED = true;
        }

    } else {
        //Replace "100x100" with "600x600" to retrieve larger album art images.
        artworkURL = artworkURL.replace("100x100", "600x600");
        URL_RETRIEVED = true;
    }

    //Loop through the songs table and retrieve the data paths of all the songs (used to embed the artwork).

    //Replace any rogue apostrophes.
    if (album.contains("'")) {
        album = album.replace("'", "''");
    }

    if (artist.contains("'")) {
        artist = artist.replace("'", "''");
    }

    String selection = DBAccessHelper.SONG_ALBUM + "=" + "'" + album + "'" + " AND "
            + DBAccessHelper.SONG_ARTIST + "=" + "'" + artist + "'";

    String[] projection = { DBAccessHelper._ID, DBAccessHelper.SONG_FILE_PATH };

    Cursor cursor = mApp.getDBAccessHelper().getWritableDatabase().query(DBAccessHelper.MUSIC_LIBRARY_TABLE,
            projection, selection, null, null, null, null);

    if (cursor.getCount() != 0) {
        cursor.moveToFirst();
        dataURIsList.add(cursor.getString(1));

        while (cursor.moveToNext()) {
            dataURIsList.add(cursor.getString(1));
        }

    }

    cursor.close();

    if (URL_RETRIEVED == true) {
        artworkBitmap = mApp.getImageLoader().loadImageSync(artworkURL);

        File artworkFile = new File(Environment.getExternalStorageDirectory() + "/artwork.jpg");

        //Display the album art on the grid/listview so that the user knows that the download is complete.
        publishProgress();

        //Save the artwork.
        try {
            FileOutputStream out = new FileOutputStream(artworkFile);
            artworkBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            return 1;
        } finally {

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

                if (dataURIsList.get(i) != null) {

                    File audioFile = new File(dataURIsList.get(i));
                    AudioFile f = null;

                    try {
                        f = AudioFileIO.read(audioFile);
                    } catch (CannotReadException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (TagException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (ReadOnlyFileException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (InvalidAudioFrameException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    Tag tag = null;
                    try {
                        if (f != null) {
                            tag = f.getTag();
                        } else {
                            continue;
                        }

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

                    Artwork artwork = null;
                    try {
                        artwork = ArtworkFactory.createArtworkFromFile(artworkFile);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        setArtworkAsFile(artworkFile, dataURIsList.get(i));
                        continue;
                    } catch (Error e) {
                        e.printStackTrace();
                        setArtworkAsFile(artworkFile, dataURIsList.get(i));
                        continue;
                    }

                    if (artwork != null) {

                        try {
                            tag.setField(artwork);
                        } catch (FieldDataInvalidException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            setArtworkAsFile(artworkFile, dataURIsList.get(i));
                            continue;
                        } catch (Exception e) {
                            e.printStackTrace();
                            setArtworkAsFile(artworkFile, dataURIsList.get(i));
                            continue;
                        } catch (Error e) {
                            e.printStackTrace();
                            setArtworkAsFile(artworkFile, dataURIsList.get(i));
                            continue;
                        }

                    }

                    try {
                        f.commit();
                    } catch (CannotWriteException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        setArtworkAsFile(artworkFile, dataURIsList.get(i));
                        continue;
                    } catch (Error e) {
                        e.printStackTrace();
                        setArtworkAsFile(artworkFile, dataURIsList.get(i));
                        continue;
                    }

                    //Update the album art tag in Jams' database.
                    ContentValues values = new ContentValues();
                    String filePath = dataURIsList.get(i);
                    filePath = filePath.replace("'", "''");
                    String where = DBAccessHelper.SONG_FILE_PATH + "=" + "'" + filePath + "'";
                    values.put(DBAccessHelper.SONG_ALBUM_ART_PATH, "byte://" + dataURIsList.get(i));

                    mApp.getDBAccessHelper().getWritableDatabase().update(DBAccessHelper.MUSIC_LIBRARY_TABLE,
                            values, where, null);

                } else {
                    continue;
                }

            }

            //Refresh the memory/disk cache for the ImageLoader instance.
            try {
                mApp.getImageLoader().clearMemoryCache();
                mApp.getImageLoader().clearDiscCache();
            } catch (Exception e) {
                e.printStackTrace();
            }

            //Delete the temporary files once the artwork has been embedded.
            artworkFile.delete();
            file.delete();

        }

    }

    return 0;
}

From source file:com.jelly.music.player.AsyncTasks.AsyncGetAlbumArtTask.java

@Override
protected Integer doInBackground(String... params) {
    /************************************************************************************************
     * RETRIEVE THE HTTP SEARCH RESPONSE FROM ITUNES SERVERS.
     ************************************************************************************************/

    //First, we'll make a HTTP request to iTunes' servers with the album and artist name.
    if (params.length == 2) {
        artist = params[0];//  w  ww  .j  a  v a  2 s .  co m
        album = params[1];

        //Create duplicate strings that will be filtered out for the URL.
        urlArtist = artist;
        urlAlbum = album;

        //Remove any unacceptable characters.
        if (urlArtist.contains("#")) {
            urlArtist = urlArtist.replace("#", "");
        }

        if (urlArtist.contains("$")) {
            urlArtist = urlArtist.replace("$", "");
        }

        if (urlArtist.contains("@")) {
            urlArtist = urlArtist.replace("@", "");
        }

        if (urlAlbum.contains("#")) {
            urlAlbum = urlAlbum.replace("#", "");
        }

        if (urlAlbum.contains("$")) {
            urlAlbum = urlAlbum.replace("$", "");
        }

        if (urlAlbum.contains("@")) {
            urlAlbum = urlAlbum.replace("@", "");
        }

        //Replace any spaces in the artist and album fields with "%20".
        if (urlArtist.contains(" ")) {
            urlArtist = urlArtist.replace(" ", "%20");
        }

        if (urlAlbum.contains(" ")) {
            urlAlbum = urlAlbum.replace(" ", "%20");
        }

    }

    //Construct the url for the HTTP request.
    URL uri = null;
    try {
        uri = new URL("http://itunes.apple.com/search?term=" + urlArtist + "+" + urlAlbum + "&entity=album");
    } catch (MalformedURLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        return 1;
    }

    try {
        //Create a new HTTP connection.
        HttpURLConnection urlConnection = (HttpURLConnection) uri.openConnection();
        urlConnection.connect();

        //Set the destination directory for the xml file.
        File SDCardRoot = Environment.getExternalStorageDirectory();
        file = new File(SDCardRoot, "albumArt.xml");

        //Create the OuputStream that will be used to store the downloaded data into the file.
        FileOutputStream fileOutput = new FileOutputStream(file);

        //Create the InputStream that will read the data from the HTTP connection.
        InputStream inputStream = urlConnection.getInputStream();

        //Total size of target file.
        int totalSize = urlConnection.getContentLength();

        //Temp variable that stores the number of downloaded bytes.
        int downloadedSize = 0;

        //Create a buffer to store the downloaded bytes.
        byte[] buffer = new byte[1024];
        int bufferLength = 0;

        //Now read through the buffer and write the contents to the file.
        while ((bufferLength = inputStream.read(buffer)) > 0) {
            fileOutput.write(buffer, 0, bufferLength);
            downloadedSize += bufferLength;

        }

        //Close the File Output Stream.
        fileOutput.close();

    } catch (MalformedURLException e) {
        //TODO Auto-generated method stub
        e.printStackTrace();
        return 1;
    } catch (IOException e) {
        // TODO Auto-generated method stub
        e.printStackTrace();
        return 1;
    }

    //Create a File object that points to the downloaded file.
    File phpSource = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/albumArt.xml");
    String phpAsString = null;
    try {
        phpAsString = FileUtils.readFileToString(phpSource);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return 1;
    }

    //Extract the albumArt parameter from the PHP response.
    artworkURL = StringUtils.substringBetween(phpAsString, "\"artworkUrl100\":\"", "\",");
    if (artworkURL == null) {

        //Check and see if a lower resolution image available.
        artworkURL = StringUtils.substringBetween(phpAsString, "\"artworkUrl60\":\"", "\",");

        if (artworkURL == null) {
            URL_RETRIEVED = false;
            return 1;
        } else {
            //Replace "100x100" with "600x600" to retrieve larger album art images.
            artworkURL = artworkURL.replace("100x100", "600x600");
            URL_RETRIEVED = true;
        }

    } else {
        //Replace "100x100" with "600x600" to retrieve larger album art images.
        artworkURL = artworkURL.replace("100x100", "600x600");
        URL_RETRIEVED = true;
    }

    //Loop through the songs table and retrieve the data paths of all the songs (used to embed the artwork).

    //Replace any rogue apostrophes.
    if (album.contains("'")) {
        album = album.replace("'", "''");
    }

    if (artist.contains("'")) {
        artist = artist.replace("'", "''");
    }

    String selection = DBAccessHelper.SONG_ALBUM + "=" + "'" + album + "'" + " AND "
            + DBAccessHelper.SONG_ARTIST + "=" + "'" + artist + "'";

    String[] projection = { DBAccessHelper._ID, DBAccessHelper.SONG_FILE_PATH };

    Cursor cursor = mApp.getDBAccessHelper().getWritableDatabase().query(DBAccessHelper.MUSIC_LIBRARY_TABLE,
            projection, selection, null, null, null, null);

    if (cursor.getCount() != 0) {
        cursor.moveToFirst();
        dataURIsList.add(cursor.getString(1));

        while (cursor.moveToNext()) {
            dataURIsList.add(cursor.getString(1));
        }

    }

    cursor.close();

    if (URL_RETRIEVED == true) {
        artworkBitmap = mApp.getImageLoader().loadImageSync(artworkURL);

        File artworkFile = new File(Environment.getExternalStorageDirectory() + "/artwork.jpg");

        //Display the album art on the grid/listview so that the user knows that the download is complete.
        publishProgress();

        //Save the artwork.
        try {
            FileOutputStream out = new FileOutputStream(artworkFile);
            artworkBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            return 1;
        } finally {

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

                if (dataURIsList.get(i) != null) {

                    File audioFile = new File(dataURIsList.get(i));
                    AudioFile f = null;

                    try {
                        f = AudioFileIO.read(audioFile);
                    } catch (CannotReadException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (TagException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (ReadOnlyFileException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (InvalidAudioFrameException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    Tag tag = null;
                    try {
                        if (f != null) {
                            tag = f.getTag();
                        } else {
                            continue;
                        }

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

                    Artwork artwork = null;
                    try {
                        artwork = ArtworkFactory.createArtworkFromFile(artworkFile);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        setArtworkAsFile(artworkFile, dataURIsList.get(i));
                        continue;
                    } catch (Error e) {
                        e.printStackTrace();
                        setArtworkAsFile(artworkFile, dataURIsList.get(i));
                        continue;
                    }

                    if (artwork != null) {

                        try {
                            tag.setField(artwork);
                        } catch (FieldDataInvalidException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            setArtworkAsFile(artworkFile, dataURIsList.get(i));
                            continue;
                        } catch (Exception e) {
                            e.printStackTrace();
                            setArtworkAsFile(artworkFile, dataURIsList.get(i));
                            continue;
                        } catch (Error e) {
                            e.printStackTrace();
                            setArtworkAsFile(artworkFile, dataURIsList.get(i));
                            continue;
                        }

                    }

                    try {
                        f.commit();
                    } catch (CannotWriteException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        setArtworkAsFile(artworkFile, dataURIsList.get(i));
                        continue;
                    } catch (Error e) {
                        e.printStackTrace();
                        setArtworkAsFile(artworkFile, dataURIsList.get(i));
                        continue;
                    }

                    //Update the album art tag in jelly' database.
                    ContentValues values = new ContentValues();
                    String filePath = dataURIsList.get(i);
                    filePath = filePath.replace("'", "''");
                    String where = DBAccessHelper.SONG_FILE_PATH + "=" + "'" + filePath + "'";
                    values.put(DBAccessHelper.SONG_ALBUM_ART_PATH, "byte://" + dataURIsList.get(i));

                    mApp.getDBAccessHelper().getWritableDatabase().update(DBAccessHelper.MUSIC_LIBRARY_TABLE,
                            values, where, null);

                } else {
                    continue;
                }

            }

            //Refresh the memory/disk cache for the ImageLoader instance.
            try {
                mApp.getImageLoader().clearMemoryCache();
                mApp.getImageLoader().clearDiscCache();
            } catch (Exception e) {
                e.printStackTrace();
            }

            //Delete the temporary files once the artwork has been embedded.
            artworkFile.delete();
            file.delete();

        }

    }

    return 0;
}

From source file:com.logilite.vision.camera.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.
 *
 * @param type FILE_URI or DATA_URL//from ww  w .j  av a  2  s  .co  m
 */
private void checkForDuplicateImage(int type) {
    int diff = 1;
    Uri contentStore = whichContentStore();
    Cursor cursor = queryImgDB(contentStore);
    int currentNumOfImages = cursor.getCount();

    if (type == FILE_URI && this.saveToPhotoAlbum) {
        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)));
        if (diff == 2) {
            id--;
        }
        Uri uri = Uri.parse(contentStore + "/" + id);
        this.cordova.getActivity().getContentResolver().delete(uri, null, null);
        cursor.close();
    }
}

From source file:com.piusvelte.wapdroid.MapData.java

public void mapData() {
    mLoadingDialog = new ProgressDialog(this);
    mLoadingDialog.setTitle(R.string.loading);
    mLoadingDialog.setMessage((mPair == 0 ? Wapdroid.Ranges.NETWORK : Wapdroid.Ranges.CELL));
    mLoadingDialog.setCancelable(true);//from ww w.  ja  v  a2s .c o m
    mLoadingDialog.setOnCancelListener(this);
    mLoadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), this);
    mLoadingDialog.show();
    mThread = new Thread() {
        public void run() {
            String ssid = "", bssid = "", towers = "";
            int ctr = 0;
            List<Overlay> mapOverlays = mMView.getOverlays();
            GeoPoint point = new GeoPoint(0, 0);
            Cursor pairs = MapData.this.getContentResolver().query(Wapdroid.Ranges.CONTENT_URI,
                    new String[] { Wapdroid.Ranges._ID, Wapdroid.Ranges.SSID, Wapdroid.Ranges.BSSID,
                            Wapdroid.Ranges.CID, Wapdroid.Ranges.LAC, Wapdroid.Ranges.RSSI_MIN,
                            Wapdroid.Ranges.RSSI_MAX },
                    mPair == 0 ? Wapdroid.Ranges.NETWORK + "=" + mNetwork : Wapdroid.Ranges._ID + "=" + mPair,
                    null, null);
            int ct = pairs.getCount();
            if (pairs.moveToFirst()) {
                WapdroidItemizedOverlay pinOverlays = new WapdroidItemizedOverlay((MapData) mContext, ct);
                while (!interrupted() && !pairs.isAfterLast()) {
                    ctr++;
                    int cid = pairs.getInt(pairs.getColumnIndex(Wapdroid.Ranges.CID)),
                            lac = pairs.getInt(pairs.getColumnIndex(Wapdroid.Ranges.LAC)),
                            rssi_min = pairs.getInt(pairs.getColumnIndex(Wapdroid.Ranges.RSSI_MIN)),
                            rssi_max = pairs.getInt(pairs.getColumnIndex(Wapdroid.Ranges.RSSI_MAX)),
                            rssi_avg = Math.round((rssi_min + rssi_max) / 2),
                            rssi_range = Math.abs(rssi_min) - Math.abs(rssi_max);
                    mMsg = string_cellWarning + Wapdroid.Ranges.CELL + " " + Integer.toString(ctr) + " of "
                            + Integer.toString(ct);
                    mHandler.post(mUpdtDialog);
                    String tower = "{" + String.format(SAddInt, cell_id, cid) + ","
                            + String.format(SAddInt, location_area_code, lac) + ","
                            + String.format(SAddInt, mcc, mMCC) + "," + String.format(SAddInt, mnc, mMNC);
                    if (rssi_avg != Wapdroid.UNKNOWN_RSSI)
                        tower += "," + String.format(SAddInt, signal_strength, rssi_avg);
                    tower += "}";
                    if (ssid == "")
                        ssid = pairs.getString(pairs.getColumnIndex(Wapdroid.Ranges.SSID));
                    if (bssid == "")
                        bssid = pairs.getString(pairs.getColumnIndex(Wapdroid.Ranges.BSSID));
                    if (towers != "")
                        towers += ",";
                    towers += tower;
                    point = getGeoPoint(bldRequest(tower, bssid));
                    pinOverlays.addOverlay(new WapdroidOverlayItem(point, Wapdroid.Ranges.CELL,
                            string_cid + Integer.toString(cid) + string_linefeed + string_lac
                                    + Integer.toString(lac) + string_linefeed + string_range
                                    + Integer.toString(rssi_min) + string_colon + Integer.toString(rssi_max),
                            mNetwork, pairs.getInt(pairs.getColumnIndex(Wapdroid.Ranges._ID)), rssi_avg,
                            rssi_range));
                    pairs.moveToNext();
                }
                if (mPair == 0) {
                    mMsg = Wapdroid.Ranges.NETWORK + ": " + ssid;
                    mHandler.post(mUpdtDialog);
                    point = getGeoPoint(bldRequest(towers, bssid));
                    Location location = new Location("");
                    location.setLatitude(point.getLatitudeE6() / 1e6);
                    location.setLongitude(point.getLongitudeE6() / 1e6);
                    pinOverlays.addOverlay(
                            new WapdroidOverlayItem(point, Wapdroid.Ranges.NETWORK, ssid, mNetwork),
                            drawable_network);
                    pinOverlays.setDistances(location);
                }
                mapOverlays.add(pinOverlays);
                mMController.setCenter(point);
            }
            pairs.close();
            mLoadingDialog.dismiss();
            interrupt();
        }
    };
    mThread.start();
}

From source file:cd.education.data.collector.android.tasks.FormLoaderTask.java

/**
 * Initialize {@link FormEntryController} with {@link FormDef} from binary or
 * from XML. If given an instance, it will be used to fill the {@link FormDef}
 * ./*from   ww w . ja  v a  2s  . c  o m*/
 */
@Override
protected FECWrapper doInBackground(String... path) {
    FormEntryController fec = null;
    FormDef fd = null;
    FileInputStream fis = null;
    mErrorMsg = null;

    String formPath = path[0];

    File formXml = new File(formPath);
    String formHash = FileUtils.getMd5Hash(formXml);
    File formBin = new File(Collect.CACHE_PATH + File.separator + formHash + ".formdef");

    publishProgress(Collect.getInstance().getString(R.string.survey_loading_reading_form_message));

    if (formBin.exists()) {
        // if we have binary, deserialize binary
        Log.i(t, "Attempting to load " + formXml.getName() + " from cached file: " + formBin.getAbsolutePath());
        fd = deserializeFormDef(formBin);
        if (fd == null) {
            // some error occured with deserialization. Remove the file, and make a
            // new .formdef
            // from xml
            Log.w(t, "Deserialization FAILED!  Deleting cache file: " + formBin.getAbsolutePath());
            formBin.delete();
        }
    }
    if (fd == null) {
        // no binary, read from xml
        try {
            Log.i(t, "Attempting to load from: " + formXml.getAbsolutePath());
            fis = new FileInputStream(formXml);
            fd = XFormUtils.getFormFromInputStream(fis);
            if (fd == null) {
                mErrorMsg = "Error reading XForm file";
            } else {
                serializeFormDef(fd, formPath);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            mErrorMsg = e.getMessage();
        } catch (XFormParseException e) {
            mErrorMsg = e.getMessage();
            e.printStackTrace();
        } catch (Exception e) {
            mErrorMsg = e.getMessage();
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(fis);
        }
    }

    if (mErrorMsg != null || fd == null) {
        return null;
    }

    // set paths to /sdcard/odk/forms/formfilename-media/
    String formFileName = formXml.getName().substring(0, formXml.getName().lastIndexOf("."));
    File formMediaDir = new File(formXml.getParent(), formFileName + "-media");

    externalDataManager = new ExternalDataManagerImpl(formMediaDir);

    // new evaluation context for function handlers
    EvaluationContext ec = new EvaluationContext(null);
    ExternalDataHandler externalDataHandlerPull = new ExternalDataHandlerPull(externalDataManager);
    ec.addFunctionHandler(externalDataHandlerPull);

    fd.setEvaluationContext(ec);

    try {
        loadExternalData(formMediaDir);
    } catch (Exception e) {
        mErrorMsg = e.getMessage();
        e.printStackTrace();
        return null;
    }

    if (isCancelled()) {
        // that means that the user has cancelled, so no need to go further
        return null;
    }

    // create FormEntryController from formdef
    FormEntryModel fem = new FormEntryModel(fd);
    fec = new FormEntryController(fem);

    boolean usedSavepoint = false;

    try {
        // import existing data into formdef
        if (mInstancePath != null) {
            File instance = new File(mInstancePath);
            File shadowInstance = SaveToDiskTask.savepointFile(instance);
            if (shadowInstance.exists() && (shadowInstance.lastModified() > instance.lastModified())) {
                // the savepoint is newer than the saved value of the instance.
                // use it.
                usedSavepoint = true;
                instance = shadowInstance;
                Log.w(t, "Loading instance from shadow file: " + shadowInstance.getAbsolutePath());
            }
            if (instance.exists()) {
                // This order is important. Import data, then initialize.
                try {
                    importData(instance, fec);
                    fd.initialize(false, new InstanceInitializationFactory());
                } catch (RuntimeException e) {
                    Log.e(t, e.getMessage(), e);

                    // SCTO-633
                    if (usedSavepoint && !(e.getCause() instanceof XPathTypeMismatchException)) {
                        // this means that the .save file is corrupted or 0-sized, so
                        // don't use it.
                        usedSavepoint = false;
                        mInstancePath = null;
                        fd.initialize(true, new InstanceInitializationFactory());
                    } else {
                        // this means that the saved instance is corrupted.
                        throw e;
                    }
                }
            } else {
                fd.initialize(true, new InstanceInitializationFactory());
            }
        } else {
            fd.initialize(true, new InstanceInitializationFactory());
        }
    } catch (RuntimeException e) {
        Log.e(t, e.getMessage(), e);
        if (e.getCause() instanceof XPathTypeMismatchException) {
            // this is a case of
            // https://bitbucket.org/m.sundt/javarosa/commits/e5d344783e7968877402bcee11828fa55fac69de
            // the data are imported, the survey will be unusable
            // but we should give the option to the user to edit the form
            // otherwise the survey will be TOTALLY inaccessible.
            Log.w(t, "We have a syntactically correct instance, but the data threw an exception inside JR. We should allow editing.");
        } else {
            mErrorMsg = e.getMessage();
            return null;
        }
    }

    // Remove previous forms
    ReferenceManager._().clearSession();

    // for itemsets.csv, we only check to see if the itemset file has been
    // updated
    File csv = new File(formMediaDir.getAbsolutePath() + "/" + ITEMSETS_CSV);
    String csvmd5 = null;
    if (csv.exists()) {
        csvmd5 = FileUtils.getMd5Hash(csv);
        boolean readFile = false;
        ItemsetDbAdapter ida = new ItemsetDbAdapter();
        ida.open();
        // get the database entry (if exists) for this itemsets.csv, based
        // on the path
        Cursor c = ida.getItemsets(csv.getAbsolutePath());
        if (c != null) {
            if (c.getCount() == 1) {
                c.moveToFirst(); // should be only one, ever, if any
                String oldmd5 = c.getString(c.getColumnIndex("hash"));
                if (oldmd5.equals(csvmd5)) {
                    // they're equal, do nothing
                } else {
                    // the csv has been updated, delete the old entries
                    ida.dropTable(ItemsetDbAdapter.getMd5FromString(csv.getAbsolutePath()),
                            csv.getAbsolutePath());
                    // and read the new
                    readFile = true;
                }
            } else {
                // new csv, add it
                readFile = true;
            }
            c.close();
        }
        ida.close();
        if (readFile) {
            readCSV(csv, csvmd5, ItemsetDbAdapter.getMd5FromString(csv.getAbsolutePath()));
        }
    }

    // This should get moved to the Application Class
    if (ReferenceManager._().getFactories().length == 0) {
        // this is /sdcard/odk
        ReferenceManager._().addReferenceFactory(new FileReferenceFactory(Collect.ODK_ROOT));
    }

    // Set jr://... to point to /sdcard/odk/forms/filename-media/
    ReferenceManager._().addSessionRootTranslator(
            new RootTranslator("jr://images/", "jr://file/forms/" + formFileName + "-media/"));
    ReferenceManager._().addSessionRootTranslator(
            new RootTranslator("jr://image/", "jr://file/forms/" + formFileName + "-media/"));
    ReferenceManager._().addSessionRootTranslator(
            new RootTranslator("jr://audio/", "jr://file/forms/" + formFileName + "-media/"));
    ReferenceManager._().addSessionRootTranslator(
            new RootTranslator("jr://video/", "jr://file/forms/" + formFileName + "-media/"));

    // clean up vars
    fis = null;
    fd = null;
    formBin = null;
    formXml = null;
    formPath = null;

    FormController fc = new FormController(formMediaDir, fec,
            mInstancePath == null ? null : new File(mInstancePath));
    if (mXPath != null) {
        // we are resuming after having terminated -- set index to this
        // position...
        FormIndex idx = fc.getIndexFromXPath(mXPath);
        fc.jumpToIndex(idx);
    }
    if (mWaitingXPath != null) {
        FormIndex idx = fc.getIndexFromXPath(mWaitingXPath);
        fc.setIndexWaitingForData(idx);
    }
    data = new FECWrapper(fc, usedSavepoint);
    return data;

}

From source file:com.nookdevs.library.FictionwiseBooks.java

public boolean getUser() {
    if (m_User != null) {
        return true;
    }/*from  w w w. jav  a2  s  .  c  o m*/
    if (m_Db == null) {
        m_Db = getWritableDatabase();
    }
    try {
        String[] columns = { "login", "pass" };
        Cursor c = m_Db.query("USER", columns, null, null, null, null, null);
        if (c.getCount() >= 1) {
            c.moveToFirst();
            m_User = c.getString(0);
            m_Pass = c.getString(1);
            c.close();
            return true;
        } else {
            Log.e("FictionwiseBooks", "No User Info");
            c.close();
            return false;
        }
    } catch (Exception ex) {
        Log.e("FictionwiseBooks", "exception while adding user info", ex);
    }
    return false;
}

From source file:com.android.quicksearchbox.ShortcutRepositoryImplLog.java

@VisibleForTesting
ShortcutCursor getShortcutsForQuery(String query, Collection<Corpus> allowedCorpora,
        boolean allowWebSearchShortcuts, long now) {
    if (DBG)/*from  w  w w .j ava 2  s.  c o  m*/
        Log.d(TAG, "getShortcutsForQuery(" + query + "," + allowedCorpora + ")");
    String sql = query.length() == 0 ? mEmptyQueryShortcutQuery : mShortcutQuery;
    String[] params = buildShortcutQueryParams(query, now);

    SQLiteDatabase db = mOpenHelper.getReadableDatabase();
    Cursor cursor = db.rawQuery(sql, params);
    if (cursor.getCount() == 0) {
        cursor.close();
        return null;
    }

    if (DBG)
        Log.d(TAG, "Allowed sources: ");
    HashMap<String, Source> allowedSources = new HashMap<String, Source>();
    for (Corpus corpus : allowedCorpora) {
        for (Source source : corpus.getSources()) {
            if (DBG)
                Log.d(TAG, "\t" + source.getName());
            allowedSources.put(source.getName(), source);
        }
    }

    return new ShortcutCursor(new SuggestionCursorImpl(allowedSources, query, cursor), allowWebSearchShortcuts,
            mUiThread, mRefresher, this);
}

From source file:com.github.wakhub.monodict.activity.FlashcardActivity.java

@Background
void exportCardsTo(String path) {
    activityHelper.showProgressDialog(R.string.message_in_processing);
    JSONObject jsonObject = new JSONObject();
    JSONArray jsonArray = new JSONArray();
    try {/*  w  w w .  j a v  a2  s  .  co  m*/
        Cursor cursor = databaseHelper.findAllCards();
        for (int i = 0; i < cursor.getCount(); i++) {
            Card card = new Card(cursor);
            JSONObject cardData = new JSONObject();
            try {
                cardData.put(Card.Column.DISPLAY, card.getDisplay());
                cardData.put(Card.Column.TRANSLATE, card.getTranslate());
                cardData.put(Card.Column.BOX, card.getBox());
                cardData.put(Card.Column.DICTIONARY, card.getDictionary());
                jsonArray.put(cardData);
            } catch (JSONException e) {
                activityHelper.showError(e);
                activityHelper.hideProgressDialog();
                return;
            }
            cursor.moveToNext();
        }
    } catch (SQLException e) {
        activityHelper.showError(e);
        activityHelper.hideProgressDialog();
        return;
    }

    try {
        jsonObject.put(JSON_KEY_CARDS, jsonArray);
    } catch (JSONException e) {
        activityHelper.showError(e);
        activityHelper.hideProgressDialog();
        return;
    }

    try {
        FileOutputStream outputStream = new FileOutputStream(path);
        IOUtils.write(jsonObject.toString(), outputStream);
    } catch (FileNotFoundException e) {
        activityHelper.showError(e);
        activityHelper.hideProgressDialog();
        return;
    } catch (IOException e) {
        activityHelper.showError(e);
        activityHelper.hideProgressDialog();
        return;
    }
    activityHelper.hideProgressDialog();
    activityHelper.showToast(R.string.message_success);
}

From source file:com.ichi2.anki.tests.ContentProviderTest.java

/**
 * Test that query for the next card in the schedule returns a valid result without any deck selector
 *///  w  w w . j  av a 2 s  .c o  m
public void testQueryNextCard() {
    Collection col;
    col = CollectionHelper.getInstance().getCol(getContext());
    Sched sched = col.getSched();

    Cursor reviewInfoCursor = getContext().getContentResolver().query(FlashCardsContract.ReviewInfo.CONTENT_URI,
            null, null, null, null);
    assertNotNull(reviewInfoCursor);
    assertEquals("Check that we actually received one card", 1, reviewInfoCursor.getCount());

    reviewInfoCursor.moveToFirst();
    int cardOrd = reviewInfoCursor
            .getInt(reviewInfoCursor.getColumnIndex(FlashCardsContract.ReviewInfo.CARD_ORD));
    long noteID = reviewInfoCursor
            .getLong(reviewInfoCursor.getColumnIndex(FlashCardsContract.ReviewInfo.NOTE_ID));

    Card nextCard = null;
    for (int i = 0; i < 10; i++) {//minimizing fails, when sched.reset() randomly chooses between multiple cards
        sched.reset();
        nextCard = sched.getCard();
        if (nextCard.note().getId() == noteID && nextCard.getOrd() == cardOrd)
            break;
    }
    assertNotNull("Check that there actually is a next scheduled card", nextCard);
    assertEquals("Check that received card and actual card have same note id", nextCard.note().getId(), noteID);
    assertEquals("Check that received card and actual card have same card ord", nextCard.getOrd(), cardOrd);

}

From source file:edu.stanford.mobisocial.dungbeetle.DBIdentityProvider.java

public DBIdentityProvider(DBHelper helper) {
    mHelper = helper;//  w w w  . ja va2s  .  co  m
    helper.addRef();
    mUnclosedException = new Exception("Finalized without close being called. Created at...");
    Cursor c = mHelper.getReadableDatabase().rawQuery("SELECT * FROM " + MyInfo.TABLE, new String[] {});
    try {
        if (!c.moveToFirst()) {
            throw new IllegalStateException("Missing my_info entry!");
        }

        mPubKeyString = c.getString(c.getColumnIndexOrThrow(MyInfo.PUBLIC_KEY));
        mPubKey = RSACrypto.publicKeyFromString(mPubKeyString);
        mPrivKey = RSACrypto.privateKeyFromString(c.getString(c.getColumnIndexOrThrow(MyInfo.PRIVATE_KEY)));
        mName = c.getString(c.getColumnIndexOrThrow(MyInfo.NAME));
        mEmail = c.getString(c.getColumnIndexOrThrow(MyInfo.EMAIL));
        mPubKeyTag = personIdForPublicKey(mPubKey);

        Log.d(TAG, c.getCount() + " public keys");
    } finally {
        c.close();
    }
}