Search code examples
androidtwitterbitmapuriinternal-storage

internal storage for app and uri


So I'm using the twitter api and I want to tweet with an image I use:

    TweetUri = Uri.fromFile(saveIT);
    TweetComposer.Builder builder = new TweetComposer.Builder(this)
            .text("")
            .image(TweetUri);
    builder.show();

The original image is a bitmap, so what I did (not sure if this is the optimal way) was save in the internal storage:

    private File saveToInternalStorage(Bitmap bitmapImage){
    ContextWrapper cw = new ContextWrapper(getApplicationContext());
    // path to /data/data/yourapp/app_data/imageDir
    File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
    // Create imageDir
    String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date());
    String mImageName="MI_"+ timeStamp +".jpg";
    File mypath=new File(directory,mImageName);

    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(mypath);
        // Use the compress method on the BitMap object to write image to the OutputStream
        bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try
        {
            fos.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
    return mypath;
}

The file it returns will be the "saveIT" in the TweetUri when it does the fromfile method. Of course this will overload the storage so what I plan to do is wipe the internal storage for the app when it is stopped (no other data is saved in the internal storage other than the temp images I save for the tweet):

@Override
protected void onStop() {
    super.onStop();
    File MSD = this.getApplicationContext().getFilesDir();
    File [] lisFiles = MSD.listFiles();
    for(int i=0;i<lisFiles.length;i++)
    {
        boolean deleted = lisFiles[i].delete();
    }
}

None of this works... I can't seem to find any of the images when I save them to verify if the deleting is happening. Also, when the user clicks tweet no image is added to the tweet as well. No idea what I'm doing wrong here... In reality I don't want to save the image in the internal storage but I do because the tweet api uses a URI to tweet and not a bitmap.


Solution

  • I switched it to write to external storage and it worked fine. Also I switched it to delete at onDestroy. This is better because, when I invoke the Twitter API it switches activities so the onstop is invoked which would delete the temp picture too early. It's too early becuase if the user clicks cancel at the twitter api, comes back to my api and then invokes the twitter api again the uri will point to nothing since the picture was already deleted. THATS ALL FOLKS :)