Cannot Retrieve Query from Current User - Parse (Android) - java

I'm trying to retrieve an image from the current user to display as a profile picture.
I can quite easily get it to work by inserting a specific object ID after query.getInBackground() What I want to do is to pull the "profilePicture" of the user currently logged in, hence current User, and not just one specific user. How can I fix this?
progressDialog = ProgressDialog.show(GalleryActivity.this, "",
"Downloading Image...", true);
// Locate the class table named "ImageUpload" in Parse.com
ParseQuery<ParseUser> query = ParseUser.getQuery();
// Locate the objectId from the class
ParseUser currentUser = ParseUser.getCurrentUser();
query.getInBackground(String.valueOf(ParseUser.getCurrentUser()),
new GetCallback<ParseUser>() {
public void done(ParseUser object,
ParseException e) {
// TODO Auto-generated method stub
// Locate the column named "ImageName" and set
// the string
ParseFile fileObject = (ParseFile) object
.get("profilePicture");
fileObject
.getDataInBackground(new GetDataCallback() {
public void done(byte[] data,
ParseException e) {
if (e == null) {
Log.d("test",
"We've got data in data.");
// Decode the Byte[] into
// Bitmap
Bitmap bmp = BitmapFactory
.decodeByteArray(
data, 0,
data.length);
// Get the ImageView from
// main.xml
ImageView image = (ImageView) findViewById(R.id.galleryProfilePic);
// Set the Bitmap into the
// ImageView
Bitmap resized = Bitmap.createScaledBitmap(bmp, 300, 300, true);
Bitmap conv_bm = getRoundedRectBitmap(resized, 300);
image.setImageBitmap(conv_bm);
// Close progress dialog
progressDialog.dismiss();
} else {
Log.d("test",
"There was a problem downloading the data.");
ImageView image = (ImageView) findViewById(R.id.galleryProfilePic);
image.setImageResource(R.drawable.ic_default_profile_picture);
}
}
});
}
});

I actually got this working by passing the object ID of the current user as a string into the query to replace the static object ID:
String currentUser = ParseUser.getCurrentUser().getObjectId();
query.getInBackground(currentUser,
new GetCallback<ParseUser>() {

Related

How can I generate multiple values QR code in android studio

I would like to enter multiple text fields for example
name
email
password
address
And then I would like to generate a QR code from this input. How can I do that in android studio?
Setting up the library and manifest
Open App level gradle file and import the library.
implementation 'androidmads.library.qrgenearator:QRGenearator:1.0.3'
The, click “Sync Now”.
Then, open your Manifest file and add the following permissions. It is used to save QR Code to file storage.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
We need to handle runtime permissions from Android Version 6.0.
Generating QR Code
QRGEncoder qrgEncoder = new QRGEncoder(inputValue, null, QRGContents.Type.TEXT, smallerDimension);
Here, inputValue is an input to be converted to QR Code.
Input Type also can be specified while initializing the library.
We can specify the dimensions also.
Then, add the following lines to create QR Code and encode that into Bitmap Format.
try {
// Getting QR-Code as Bitmap
bitmap = qrgEncoder.encodeAsBitmap();
// Setting Bitmap to ImageView
qrImage.setImageBitmap(bitmap);
} catch (WriterException e) {
Log.v(TAG, e.toString());
}
qrImage is an ImageView used to preview the generated QR code bitmap.
Saving QR Code
QR Generator has an option to save the generated QR Code Bitmap to storage using the following lines.
// Save with location, value, bitmap returned and type of Image(JPG/PNG).
QRGSaver.save(savePath, edtValue.getText().toString().trim(), bitmap, QRGContents.ImageType.IMAGE_JPEG);
We can save QR Code in PNG & JPG format also. We have to handle runtime permissions from Android version 6.0.
Your particular case:
Combine the information you want to encode in the QR code, and add it as the inputValue for the QRGEncoder. Here is an example code for clarity:
public class MainActivity extends AppCompatActivity {
String TAG = "GenerateQRCode";
EditText edtValue;
ImageView qrImage;
Button start, save;
String inputValue;
String savePath = Environment.getExternalStorageDirectory().getPath() + "/QRCode/";
Bitmap bitmap;
QRGEncoder qrgEncoder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
qrImage = (ImageView) findViewById(R.id.QR_Image);
edtValue = (EditText) findViewById(R.id.edt_value);
start = (Button) findViewById(R.id.start);
save = (Button) findViewById(R.id.save);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
inputValue = edtValue.getText().toString().trim();
if (inputValue.length() > 0) {
WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
Point point = new Point();
display.getSize(point);
int width = point.x;
int height = point.y;
int smallerDimension = width < height ? width : height;
smallerDimension = smallerDimension * 3 / 4;
qrgEncoder = new QRGEncoder(
inputValue, null,
QRGContents.Type.TEXT,
smallerDimension);
try {
bitmap = qrgEncoder.encodeAsBitmap();
qrImage.setImageBitmap(bitmap);
} catch (WriterException e) {
Log.v(TAG, e.toString());
}
} else {
edtValue.setError("Required");
}
}
});
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean save;
String result;
try {
save = QRGSaver.save(savePath, edtValue.getText().toString().trim(), bitmap, QRGContents.ImageType.IMAGE_JPEG);
result = save ? "Image Saved" : "Image Not Saved";
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
Article: https://www.c-sharpcorner.com/article/how-to-generate-qr-code-in-android/
Concatenate all the information in a string and do a hash on said string. Next use a library such as (https://github.com/zxing/zxing) to generate the QR code.
Use this for generating qr code online. Then use picasso to load the image. ( Use your data in the url parameter )
https://chart.googleapis.com/chart?chs=500x500&cht=qr&chl=data
I found it as the best way.

Issues with Microsoft API

So Im having trouble using Microsoft's Emotion API for Android. I have no issues with regards to running the Face API; Im able to get the face rectangles but I am not able to get it working on the emotion api. I am taking images using the builtin Android camera itself. Here is the code I am using:
private void detectAndFrame(final Bitmap imageBitmap)
{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
ByteArrayInputStream inputStream =
new ByteArrayInputStream(outputStream.toByteArray());
AsyncTask<InputStream, String, List<RecognizeResult>> detectTask =
new AsyncTask<InputStream, String, List<RecognizeResult>>() {
#Override
protected List<RecognizeResult> doInBackground(InputStream... params) {
try {
Log.e("i","Detecting...");
faces = faceServiceClient.detect(
params[0],
true, // returnFaceId
false, // returnFaceLandmarks
null // returnFaceAttributes: a string like "age, gender"
);
if (faces == null)
{
Log.e("i","Detection Finished. Nothing detected");
return null;
}
Log.e("i",
String.format("Detection Finished. %d face(s) detected",
faces.length));
ImageView imageView = (ImageView)findViewById(R.id.imageView);
InputStream stream = params[0];
com.microsoft.projectoxford.emotion.contract.FaceRectangle[] rects = new com.microsoft.projectoxford.emotion.contract.FaceRectangle[faces.length];
for (int i = 0; i < faces.length; i++) {
com.microsoft.projectoxford.face.contract.FaceRectangle rect = faces[i].faceRectangle;
rects[i] = new com.microsoft.projectoxford.emotion.contract.FaceRectangle(rect.left, rect.top, rect.width, rect.height);
}
List<RecognizeResult> result;
result = client.recognizeImage(stream, rects);
return result;
} catch (Exception e) {
Log.e("e", e.getMessage());
Log.e("e", "Detection failed");
return null;
}
}
#Override
protected void onPreExecute() {
//TODO: show progress dialog
}
#Override
protected void onProgressUpdate(String... progress) {
//TODO: update progress
}
#Override
protected void onPostExecute(List<RecognizeResult> result) {
ImageView imageView = (ImageView)findViewById(R.id.imageView);
imageView.setImageBitmap(drawFaceRectanglesOnBitmap(imageBitmap, faces));
MediaStore.Images.Media.insertImage(getContentResolver(), imageBitmap, "AnImage" ,"Another image");
if (result == null) return;
for (RecognizeResult res: result) {
Scores scores = res.scores;
Log.e("Anger: ", ((Double)scores.anger).toString());
Log.e("Neutral: ", ((Double)scores.neutral).toString());
Log.e("Happy: ", ((Double)scores.happiness).toString());
}
}
};
detectTask.execute(inputStream);
}
I keep getting the error Post Request 400, indicating some sort of issue with the JSON or the face rectangles. But I'm not sure where to start debugging this issue.
You're using the stream twice, so the second time around you're already at the end of the stream. So either you can reset the stream, or, simply call the emotion API without rectangles (ie skip the call to the face API.) The emotion API will determine the face rectangles for you.

AsyncTask - Download image - decode stream Error

I'd like to create app which allows to download a picture using URL address and next, shows it on my screen.
Unfortunately, in LogCat is showed this error:
BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: sdcard/photoalbum/download_image.jpg: open failed: ENOENT (No such file or directory)
Download's progress, which is showing on screen, works really fast. Image has 12 KB.
But I see that this picture is not downloading on my phone (sdcard).
This is caused that I couldn't decode this stream?
I would be grateful if somebody know how to resolve/fix this problem?
Here is a code:
ImageView imageView;
String image_url = "http://montco.happeningmag.com/wp-content/uploads/2015/04/run-150x150.jpg";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
imageView = (ImageView) findViewById(R.id.image_view);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(image_url);
}
});
}
// how to create an assign task do download this image
class DownloadTask extends AsyncTask<String,Integer,String> // second type is Integer because this is from 'int progress', third is String because this is the return ("Download Complete...")
{
// progress bar to display this download
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setTitle("Download in Progress...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMax(100);
progressDialog.setProgress(0);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
// how is the maximum size of this file, we need some variable:
int file_length = 0;
String path = params[0]; // we get this URL , 0(zero) index of this argument
// how image_url on this variable call "path"
try {
URL url = new URL(path);
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
file_length = urlConnection.getContentLength();
// we need a folder to storage this download image
File new_folder = new File("sdcard/photoalbum");
if(!new_folder.exists())
{
new_folder.mkdir(); // we create new folder if 'photoalbum' doesnt exist in sdcard
}
// how to put some file inside this folder
File input_file = new File(new_folder,"downloaded_image.jpg");
// how to create input STREAM to read information data from url
InputStream inputStream = new BufferedInputStream(url.openStream(),8192); // we need input stream with some buffer. 8192(8 KB) (input stream
// now I want to read informations in one kb so I need byte variable
byte[] data = new byte[1024]; // it will read info to 1 KB
// before read information we need some variable
int total = 0;
int count = 0;
// we need output stream object to write a data
OutputStream outputStream = new FileOutputStream(input_file); // because outputStream is available in input_file
// we need write information to outputStream
while((count = inputStream.read())!=-1) //loop executes until the value became (-1)
{
// how to update value from a variable total
total += count;
outputStream.write(data,0,count); // data is available on the Byte variable data; offset; count
// how to display a progress bar: we need to call publish progress method and specify special value for this progress
int progress = (int) total*100/file_length;
publishProgress(progress);
}
// how to close Stream
inputStream.close();
outputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// after finished our job we need to return some result
return "Download Complete...";
}
#Override
protected void onProgressUpdate(Integer... values) {
progressDialog.setProgress(values[0]); // this will update the progress bar
}
#Override
protected void onPostExecute(String result) {
// after finishing job, we need to hide a progress bar
progressDialog.hide();
// how to display some result
Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();
// how to put image into imageView
String path = "sdcard/photoalbum/download_image.jpg";
// how to set this image in imageView
imageView.setImageDrawable(Drawable.createFromPath(path));
}
}
File new_folder = new File("sdcard/photoalbum");
if(!new_folder.exists()){
new_folder.mkdir(); // we create new folder if 'photoalbum' doesnt exist in sdcard
}
Try to modify the upper code as follow:
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
|| !Environment.isExternalStorageRemovable()) {
File new_folder = new File(Environment.getExternalStorageDirectory().toString() + File.separator + "photoalbum");
if(!new_folder.exists()){
new_folder.mkdirs(); // we create new folder if 'photoalbum' doesnt exist in sdcard
}
}

Android: Bitmap doesn't get added to ArrayList<Bitmap>

I create a Bitmap using Android Query like this:
ArrayList<Bitmap> bitmapArray = new ArrayList<Bitmap>();
aq = new AQuery(HomeCategoryActivity.this);
aq.ajax(currentUrl,Bitmap.class,0,new AjaxCallback<Bitmap>(){
#Override
public void callback(String url, Bitmap object, AjaxStatus status) {
if(object != null)
{
bitmapArray.add(object);
}
}
});
But when I Log.d the size of the arraylist, it returns 0. The Bitmap is NOT NULL, I checked by setting it as an image resource. It simply doesn't get added to the arraylist. What do you think is wrong?

How to use AsyncTask to update a global variable

What I want to do: I am putting rows into a ListView using a custom "Location" adapter. I am trying to add a Bitmap into a row of the ListView. This Bitmap is coming from a URL. So, I have a global variable public static Bitmap bitmap and want to update this variable using an AsyncTask. Here is my code:
try {
String s = "";
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
final JSONObject json = jArray.getJSONObject(i);
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
//here I am calling my new task and giving it the ID to find the image
BitmapWorkerTask myTask = new BitmapWorkerTask(json.getInt("ID"));
myTask.execute();
adapter.add(new Location(bitmap, json
.getString("PlaceTitle"), json
.getString("PlaceDetails"), json
.getString("PlaceDistance"), json
.getString("PlaceUpdatedTime")));
bitmap = null;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error Parsing Data " + e.toString());
}
and here is my AsyncTask
class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
private int photoID = 0;
public BitmapWorkerTask(int photoID) {
// Use a WeakReference to ensure the ImageView can be garbage collected
this.photoID = photoID;
}
// Decode image in background.
#Override
protected Bitmap doInBackground(Integer... params) {
String initialURL = "http://afs.spotcontent.com/img/Places/Icons/";
final String updatedURL = initialURL + photoID + ".jpg";
Bitmap bitmap2 = null;
try {
bitmap2 = BitmapFactory.decodeStream((InputStream) new URL(
updatedURL).getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap2;
}
// Once complete, see if ImageView is still around and set bitmap.
#Override
protected void onPostExecute(Bitmap bitmap2) {
bitmap = bitmap2;
}
}
So, for each iteration, I am feeding the AsyncTask an ID which it uses to find the image, and then (I was hoping) should update the global Bitmap which is passed into the adapter. When I run my app, the every listing's picture is empty. Any ideas on what I'm doing wrong?
Consider the following possible order your commands get executed (remembering that tasks run in the background, so the order is non-deterministic):
myTask.execute()
BitmapWorkerTask.doInBackground()
adapter.Add(new Location(bitmap, .......
BitmapWorkerTask.onPostExecute()
When you create the Location() object in step 3, the 'bitmap' object being passed is the global object pointer. Its value is NOT valid yet, because onPostExecute() wasn't called yet. So the Location object is created with a non-bitmap object. On step 4, when the bitmap is finally retrieved, the value of the global object pointer is changed (correctly), but that doesn't affect the (empty) bitmap object already passed to Location on step 2... Which is why you don't see the bitmap on your view.
What you could do is pass an additional parameter to the BitmapWorkerTask constructor: You could pass the Location object (or the underlying bitmap). From onPostExecute() you could then update that Location/bitmap object with the retrieved bitmap. You don't need a global variable here.

Categories