ma_gr ma_gr - 6 months ago 34
Android Question

Create a temporary image from URL not working


  • List item



I'm loading some images from a URL by using JSON and opening them in full size in a new Activity.

In that Activity I want to share them by using a
ShareActionProvider
.

Some questions on Stack Overflow suggest downloading them first as a temporary file, but it's not working with my code:

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_full_screen);

Intent i = getIntent();
path = i.getStringExtra(TAG_FILEIMG);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.full_screen, menu);

MenuItem item = menu.findItem(R.id.menu_item_share);
mShareActionProvider = (ShareActionProvider) item.getActionProvider();
mShareActionProvider.setShareIntent(createShareIntent());

return true;
}

public File getTempFile(Context context, String url) {

url = path;
try {
String fileName = Uri.parse(url).getLastPathSegment();
file = File.createTempFile(fileName, null, context.getCacheDir());
}catch (IOException e) {
e.printStackTrace();
}
return file;

}

private Intent createShareIntent() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, file);
shareIntent.setType("image/*");


return shareIntent;

}


full_screen.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.habitodigital.FullScreenActivity" >

<item
android:id="@+id/menu_item_share"
android:showAsAction="ifRoom"
android:title="@string/share"
android:actionProviderClass="android.widget.ShareActionProvider"/>

</menu>


path is the JSON image path I use to load images by using an
ImageLoader
.

Is this temporary file creation code correct?

Answer

You're creating an empty file here.

public File getTempFile(Context context, String url) {

url = path;
try {
    String fileName = Uri.parse(url).getLastPathSegment();
    file = File.createTempFile(fileName, null, context.getCacheDir());
}catch (IOException e) {
    e.printStackTrace();
}
return file;

}

What you should do is download the image from the website and write it into that file.

You can use FileOutputStream to write on the file.

Comments