Get Parsefile to ImageView - java

I want to get file from parse to ImageView. I'm try to get by "getDataInBackgound" But when I call to this method' UI is stuck and I get the last image.
ParseFile image = tableParseObjects.getParseFile(PARSE_IMAGES);
image.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] data, ParseException e) {
Bitmap bitpic = BitmapFactory.decodeByteArray(data, 0, data.length);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitpic.compress(Bitmap.CompressFormat.PNG, 100, stream);
vectorSample.setPic(bitpic);
}
});

I think you have to load the image using Picasso or the ImageLoader class. I had the same doubt and I used a ParseImageView too. This is my code:
Retrieve from parse.com the ParseFile (the image) with an asynctask:
public class BackgroundQuery extends AsyncTask<Object, Void, Object> {
private String id;
public BackgroundQuery(String id) {
this.id = id;
}
#Override
protected Object doInBackground(Object... params) {
Object o = null;
try {
ParseQuery<ParseObject> query = ParseQuery.getQuery(params[0]
.getClass().getSimpleName());
query.whereEqualTo("objectId", id);
List<ParseObject> result = query.find();
if (result != null) {
for (ParseObject obj : result) {
o = obj.getParseFile("photo"); // Photo is the ParseFile
}
}
} catch (ParseException e) {
Log.e(TAG, e.getMessage());
}
return o;
}
}
In your layout use this like an ImageView:
<com.parse.ParseImageView
android:id="#id/imgv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true />
Use this line for load the picture in the ParseImageView:
Picasso.with(this).load(parsefile.getUrl()).into(parseimageview);
An alternative to load bigger pics quickly it´s using an ImageLoader. Please check this.
Hope this help :)

Related

How to wait for non null return before continuing

I want to retrieve a bitmap from a separate class. The separate class has a method that downloads a bitmap from an online server with a data callback. By default the method returns null until the bitmap is downloaded. When I call the method from my main class I get null. How can I wait for this retrieval to be non null (i.e the bitmap has been downloaded) before continuing any main class operations?
Main Class
profileBitmap = myParse.getImageBitmap(getContext(), tagId);
Separate Class
public Bitmap getImageBitmap (final Context context, String tagId) {
// give us the user's photo
ParseQuery<ParseObject> parseQuery = new ParseQuery<>("Photo");
parseQuery.whereEqualTo("username", tagId);
parseQuery.getFirstInBackground(new GetCallback<ParseObject>() {
#Override
public void done(ParseObject object, ParseException e) {
if (object != null && e == null) {
ParseFile profilePic = (ParseFile) object.get("profilePicture");
//download process
profilePic.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] data, ParseException e) {
if (data != null && e == null) {
// converts file to image
selectedImageBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
} else {
// returns error user bitmap
selectedImageBitmap = BitmapFactory.decodeResource(context.getResources(), android.R.drawable.ic_dialog_alert);
FancyToast.makeText(context, "Error: " + e.getMessage(), FancyToast.LENGTH_SHORT, FancyToast.ERROR, false).show();
}
}
});
} else {
// returns empty user bitmap
selectedImageBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.empty_user);
FancyToast.makeText(context, "Error: " + e.getMessage(), FancyToast.LENGTH_SHORT, FancyToast.ERROR, false).show();
}
}
});
return selectedImageBitmap;
}
I would use a listener:
Create an interface in a new file:
public interface onBitmapDownloadedListener{
void onDownloadFinished(Bitmap bitmap);
}
In your main class implement the interface, and pass the reference of your main class to the MyParse class
class MainClass implements onBitmapDownloadedListener{
//now when you create an instance of myParse, pass the listener
......
myParse = new MyParse(this);
#Override
public void onDownloadFinished(Bitmap bitmap){
//here you get the bitmap
profileBitmap = bitmap
}
Make a constructor in MyParse class that accepts the interface:
class MyParse {
private onBitmapDownloadedListener listener;
//constrcutor
public MyParse(onBitmapDownloadedListener listener){
this.listener = listener
}
//your method
public Bitmap getImageBitmap (final Context context, String tagId) {
........
........
........
#Override
public void done(byte[] data, ParseException e) {
if (data != null && e == null) {
// converts file to image
selectedImageBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
//notify here
listener.onDownloadFinished(selectedImageBitmap);
}
....
....
....
}
}

How to get data from sqlite, and show it using stackwidget?

I want to retrieve url image from sqlite, then convert it to bitmap and show it into stackwidget. When insert url image manually, one by one, it works well. But when i use url image from sqlite, application is force close and my stackwidget doesn't show image.
public class StackRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory {
...
StackRemoteViewsFactory(Context context) {
mContext = context;
}
#Override
public void onCreate() {
FilmHelper filmHelper = FilmHelper.getInstance(mContext);
filmHelper.open();
}
#Override
public void onDataSetChanged() {
DatabaseHelper databaseHelper;
databaseHelper = new DatabaseHelper(mContext);
SQLiteDatabase databases = databaseHelper.getReadableDatabase();
long count = DatabaseUtils.queryNumEntries(databases, "note");
ArrayList<Film> ini = new ArrayList<>();
Cursor c =FilmHelper.database.rawQuery("SELECT * FROM note" , null );
c.moveToFirst();
Film note;
int i;
if (c.getCount() > 0) {
for (i=0; i < count; i++ ) {
do {
note = new Film();
note.setId(c.getInt(c.getColumnIndexOrThrow(_ID)));
note.setPosterPath(c.getString(c.getColumnIndexOrThrow(IMAGE)));
ini.add(note);
try {
URL url = new URL("https://image.tmdb.org/t/p/w600_and_h900_bestv2/" +
ini.get(i).getPosterPath());
Bitmap image = BitmapFactory.decodeStream(url.openStream());
mWidgetItems.add(image);
} catch (IOException e) {
System.out.println(e);
}
c.moveToNext();
} while (!c.isAfterLast());
}
}
c.close();
databases.close();
...
}
you are doing network consuming task like converting url to bitmap inside forloop in main thread.
you can use Asynctask that will download bitmap from url to you in onPostExecute and from that you can add bitmap to mWidgetItems.
class ConvertUrltoBitmap extends AsyncTask<String, Void, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
public Bitmap doInBackground(String... urls) {
Bitmap map = null;
try {
URL url = new URL(urls[0]);
HttpURLConnection connection =(HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
map= BitmapFactory.decodeStream(input);
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
protected void onPostExecute(Bitmap bitmap){
try {
mWidgetItems.add(bitmap);
}catch (Exception exception){
exception.printStackTrace();
}
}}

Generating thumbnail for videos in ImageView at a given position

The below code is working good, its generating image thumbnail for the video from the given url, but i want to know, is it possible to generate video thumbnail at suppose 100 milliseconds because by default its generating thumbnail at the beginning position so if in beginning the video screen is black then the thumbnail is also showing black so its looking quite odd. So is there any possibility to get the thumbnail by skipping some milliseconds.
public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
String path;
public DownloadImage(ImageView bmImage, String path) {
this.bmImage = (ImageView ) bmImage;
this.path=path;
}
protected Bitmap doInBackground(String... urls) {
Bitmap myBitmap = null;
MediaMetadataRetriever mMRetriever = null;
try {
mMRetriever = new MediaMetadataRetriever();
if (Build.VERSION.SDK_INT >= 14)
mMRetriever.setDataSource(path, new HashMap<String, String>());
else
mMRetriever.setDataSource(path);
myBitmap = mMRetriever.getFrameAtTime();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (mMRetriever != null) {
mMRetriever.release();
}
}
return myBitmap;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
You can use other overloaded methods of MediaMetadataRetriever to get frame of a particular time.
public Bitmap getFrameAtTime(long timeUs, int option) {
throw new RuntimeException("Stub!");
}
public Bitmap getFrameAtTime(long timeUs) {
throw new RuntimeException("Stub!");
}
public Bitmap getFrameAtTime() {
throw new RuntimeException("Stub!");
}

Loading images with Parse in GridView

I'm trying to make an application which grabs all the ParseFiles in a ParseObject and display them in a GridView, successively.
I've done so with one activity, which represents a news feed, and everything works fine.
But when I'm trying to implement the same method in my other activity, it doesn't work.
I'm using an AsyncTask to load the images in the background.
This is my code:
ThumbnailItems.java (POJO class)
public class ThumbnailItems {
Bitmap thumb;
// Empty constructor.
public ThumbnailItems(){
}
// Constructor.
public ThumbnailItems(Bitmap thumb){
super();
this.thumb = thumb;
}
// Getter.
public Bitmap getImage(){
return thumb;
}
// Setter.
public void setImage(Bitmap thumb){
this.thumb = thumb;
}
}
My AsyncTask:
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
thumbItemsList = new ArrayList<ThumbnailItems>();
try {
ParseQuery<ParseObject> postQuery = new ParseQuery<ParseObject>("Posts");
postQuery.orderByDescending("createdAt");
objectList = postQuery.find();
for (ParseObject posts : objectList){
final ThumbnailItems thumbItems = new ThumbnailItems();
// Locate user profile picture.
ParseFile thumbFile = (ParseFile) posts.get("author_img");
thumbFile.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] bytes, ParseException e) {
if (e == null) {
Bitmap userImage = Bitmap.createScaledBitmap(
BitmapFactory.decodeByteArray(bytes, 0, bytes.length)
, 150, 150, false);
thumbItems.setImage(userImage);
} else {
Log.d("ParseException", "Error: " + e.getMessage());
e.printStackTrace();
}
}
});
thumbItemsList.add(thumbItems);
}
} catch (ParseException e){
Log.e("ParseException", "Error: " + e.getMessage() + " with code: " + e.getCode());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
LayoutInflater layoutInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View activityView = layoutInflater.inflate(R.layout.activity_profile, null, false);
gridView = (GridView) activityView.findViewById(R.id.gridView);
gridViewAdapter = new GridViewAdapter(getApplicationContext()
, R.layout.profile_viewpager_tab1_children
, thumbItemsList);
gridView.setAdapter(gridViewAdapter);
}
}
(I've already seen this tutorial, but I really want to be consistent with my code)
i think batter to use Like.
and don't use AsyncTask to load the images in the background.
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(
"ClassName");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
// TODO Auto-generated method stub
if (e == null) {
// hear u will get responce.
for (ParseObject parseObject : list) {
ParseFile image = (ParseFile) parseObject.get(""); // hear
// set
// column
// name
// same
// as
// parse
// table
if (image != null) {
// hear store image into your custom array.
// Like...
Log.e("get Image ",
" IMAGE URL IS " + image.getUrl());
}
}
// and hear u can set your adapter
// and yr grid view
// in adapter to use Picasso libary for image shower.
// how to use picasso lib.
Picasso.with(getApplicationContext()).load("image url")
.fit().into(imageview);
} else {
// hear is yr fail responce
// e.getMessage()
}
}
});

Call AsyncTask class with additional parameters in order to check where to show image

I am using an AsyncTask class to download images for my quiz application. This is the class:
public class DownloadImagesTask extends AsyncTask<ImageView, Void, Bitmap>{
ImageView imageView = null;
#Override
protected Bitmap doInBackground(ImageView... imageViews) {
this.imageView = imageViews[0];
return download_Image((String)imageView.getTag());
}
#Override
protected void onPostExecute(Bitmap result) {
// imageView.setImageBitmap(result);
downloaded_image = new BitmapDrawable(result);
//setting question image
question_view.setCompoundDrawablesWithIntrinsicBounds(null, null, null, downloaded_image);
}
private Bitmap download_Image(String url) {
//---------------------------------------------------
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e("Hub","Error getting the image from server : " + e.getMessage().toString());
}
return bm;
//--------------------------------------------------
}
}
The image is getting downloaded and I am putting the image inside my Question TextView like this:
downloaded_image = new BitmapDrawable(result);
//setting question image
question_view.setCompoundDrawablesWithIntrinsicBounds(null, null, null, downloaded_image);
I am giving a call to this class from my activity like this:
//image download
String imageURL = "http://cache.daylife.com/imageserve/074efG3gPV4oK/50x50.jpg";
image_downloadView.setTag(imageURL);
new DownloadImagesTask().execute(image_downloadView);
I want to pass some extra parameters in order to identify whether I am downloading the image for the question or answer TextViews.
How do I achieve this?
Thanks in advance!
P.S.: I have one question and four options in the application for every set of question.
You can pass parameters to your AsyncTask Constructor.
DownLoadImagesTask dt= new DownLoadImagesTask("hello",1); //passing string and integer value
dt.execute(image_downloadView);
In asynctask
String s;
int value;
public DownLoadImagesTask(String string, int i) {
// TODO Auto-generated constructor stub
s=string;
value=1;
}
You can change the type of your first param to an Object (Or create a custom parameter class/hash - the best option) and pass multiple items to it.
ImageView imgView = (ImageView) findViewById(R.id.imageView1);
String param = "parameter";
MyAsyncTask task = new MyAsyncTask();
task.execute(param, imgView);
private class MyAsyncTask extends AsyncTask<Object, Void, Void> {
private String parameter;
private ImageView imgView;
#Override
protected Void doInBackground(Object... params) {
//Looping option
for (Object object : params) {
if (object instanceof String) {
this.parameter = (String) object;
//do_something
} else if (object instanceof ImageView) {
//do_something_else
}
}
//Direct access option
this.parameter = (String) params[0];
this.imgView = (ImageView) params[1];
return null;
}
}
In your case, you can pass a View
new DownloadImagesTask().execute(image_downloadView, question_resultView);
private class DownloadImagesTask extends AsyncTask<View, Void, Bitmap> {
TextView questionView = null;
ImageView imageView = null;
#Override
protected Bitmap doInBackground(View... views) {
for (View view : views) {
if (view instanceof ImageView) {
this.imageView = (ImageView) view;
} else if (view instanceof TextView) {
this.questionView = (TextView) view;
}
}
return download_Image((String)imageView.getTag());
}
#Override
protected void onPostExecute(Bitmap result) {
// imageView.setImageBitmap(result);
downloaded_image = new BitmapDrawable(result);
//setting question image
questionView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, downloaded_image);
}
}

Categories