Parse file saveing error,""Unable to encode an unsaved parsefile" - java

I am getting error while uploading image on Parse.Please Help me about this. I tried some Stack overflow question but its nothing, So please help me,Thank in advance.
When i press Submit button then i am getting following error.
error is
java.lag.illegalStateException: Unable to encode an unsaved parsefile
and my code is
bitmapLogo=BitmapFactory.decodeFile(picturePath);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmapLogo.compress(Bitmap.CompressFormat.PNG,0, stream);
byte[] image = stream.toByteArray();
String filename=etUser.getText().toString()+".png";
ParseFile file = new ParseFile(filename, image);
System.out.println("PARSE FILE NAME : "+picturePath);
file.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if(e!=null){
btSignup.setText(e.getMessage());
}
}
},new ProgressCallback() {
#Override
public void done(Integer integer) {
btSignup.setText(""+integer);
}
});
String spin= String.valueOf(spinBCat.getSelectedItem());
ParseUser user = new ParseUser();
user.setUsername(etUser.getText().toString());
user.setPassword(etPass.getText().toString());
user.setEmail(etEmail.getText().toString());
user.put("logoname",etUser.getText().toString());
user.put("blogo",file);
user.signUpInBackground(new SignUpCallback() {
public void done(ParseException e) {
if (e == null) {
Toast.makeText(AddBusinessActivity.this,"You are Successfully Signed Up",Toast.LENGTH_LONG).show();
signUpSucess();
} else {
Toast.makeText(AddBusinessActivity.this,""+e.getMessage(),Toast.LENGTH_LONG).show();
// Sign up didn't succeed. Look at the ParseException
// to figure out what went wrong
}
}
});

Finally I solve this answer. Just add code in ProgressCallback method
Code is
bitmapLogo=BitmapFactory.decodeFile(picturePath);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmapLogo.compress(Bitmap.CompressFormat.PNG,0, stream);
byte[] image = stream.toByteArray();
String filename=etUser.getText().toString()+".png";
ParseFile file = new ParseFile(filename, image);
System.out.println("PARSE FILE NAME : "+picturePath);
file.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if(e!=null){
btSignup.setText(e.getMessage());
}
}
},new ProgressCallback() {
#Override
public void done(Integer integer) {
String spin= String.valueOf(spinBCat.getSelectedItem());
ParseUser user = new ParseUser();
user.setUsername(etUser.getText().toString());
user.setPassword(etPass.getText().toString());
user.setEmail(etEmail.getText().toString());
user.put("logoname",etUser.getText().toString());
user.put("blogo",file);
user.signUpInBackground(new SignUpCallback() {
public void done(ParseException e) {
if (e == null) {
Toast.makeText(AddBusinessActivity.this,"You are Successfully Signed Up",Toast.LENGTH_LONG).show();
signUpSucess();
} else {
Toast.makeText(AddBusinessActivity.this,""+e.getMessage(),Toast.LENGTH_LONG).show();
// Sign up didn't succeed. Look at the ParseException
// to figure out what went wrong
}
}
});
}
});

Related

finish() method not finishing the activity

I am trying to come back to the Main Activity after taking a picture.
However, the finish() method is not taking me back to the Main Activity. Here is my code.
protected void takePicture() {
ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener() {
#Override
public void onImageAvailable(ImageReader reader) {
Image image = null;
try {
image = reader.acquireLatestImage();
ByteBuffer buffer = image.getPlanes()[0].getBuffer();
byte[] bytes = new byte[buffer.capacity()];
buffer.get(bytes);
picture = bytes;
save(bytes);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (image != null) {
image.close();
}
}
}
private void save(byte[] bytes) throws IOException {
OutputStream output = null;
try {
output = new FileOutputStream(file);
output.write(bytes);
} finally {
if (null != output) {
output.close();
}
}
}
};
} catch (CameraAccessException e) {
e.printStackTrace();
}
while(picture == null);
sendImage(picture);
finish();
}
private void sendImage(byte[] bytes) {
Intent i = new Intent();
i.putExtra("picture", bytes);
setResult(1, i);
}
If I run this code, the result picture is not null, but the Activity does not finish. If I comment out the line with
while(picture == null);
the resulting picture is null but the activity finishes at the end of the method. I want to have both the picture not be null and the Activity to finish. Any help would be greatly appreciated;

Android Picasso: Method call should happen from the main thread

I am trying to get info from a server, including photos. I have created a class called ServerManager, which allows me to download the desired information. However, I cannot download images with Picasso because I get a java.lang.IllegalStateException: Method call should happen from the main thread..
This is what I am doing in ServerManager:
// Check if the photo is already downloaded
if (!checkInternalPhoto(member)) {
final String outputURL = context.getFilesDir().getAbsolutePath() + "/" + member.photoPath;
String photoURL = rootURL + "photos/" + member.photoPath;
Picasso.with(context)
.load(photoURL)
.into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
File file = new File(outputURL);
try {
file.createNewFile();
FileOutputStream outputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG,100,outputStream);
outputStream.flush();
outputStream.close();
} catch (IOException e) {
Log.e("IOException",e.getLocalizedMessage());
}
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
}
What can I do?
Edit: I tried to use the code in my MainActivity and I am getting the same error message...
public void downloadPhotos(List<Member> memberList){
String rootInURL = serverManager.getRootURL();
String rootOutURL = serverManager.getOutputURL();
for(int i = 0; i < memberList.size(); i++){
if(!serverManager.checkInternalPhoto(memberList.get(i))){
final String outputURL = rootOutURL + memberList.get(i).photoPath;
String photoURL = rootInURL + "photos/" + memberList.get(i).photoPath;
Picasso.with(this)
.load(photoURL)
.into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
File file = new File(outputURL);
try{
file.createNewFile();
FileOutputStream outputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG,100,outputStream);
outputStream.flush();
outputStream.close();
Toast.makeText(context, "YEpa: " ,Toast.LENGTH_LONG).show();
} catch (IOException e){
Toast.makeText(context, "Error: " + e.toString(),Toast.LENGTH_LONG).show();
}
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
}
}
}
Try this and your error should disappear. This problem always happens when you use it in Unit Android test
kotlin code
Handler(Looper.getMainLooper()).post {
}
java code
new Handler(Looper.getMainLooper()).post(() -> {
});
You can't update an ui element from a different thread than the one which created that ui element. On Android that almost always means the main thread.
What you need to do is send back the photoUrl String to your activity or fragment on the main thread. The traditional way of doing it is by using a Handler. You can read about this more here: https://developer.android.com/training/multiple-threads/communicate-ui.html

Picasso fail to load image locally

i am try to download a image and save it locally. Everything runs trough i didnt get any exceptions, but the file dont appear in my location
i searched for an solution but didnt find any.
Heres my code:
private void saveImages() {
try{
final File thumbsPath = new File(getExternalFilesDir(null), "thumbs");
if (!thumbsPath.exists())
thumbsPath.mkdirs();
Target target = new Target(){
#Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
new Thread(new Runnable() {
#Override
public void run() {
File file = new File(thumbsPath.getAbsolutePath() + "/file.jpeg"); //folder exists
try {
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, ostream);
ostream.flush();
ostream.close();
} catch (Exception e) {
Log.e("ERROR", e.getMessage());
}
}
}).start();
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
Log.e("ERROR", "");
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
Log.e("ERROR", "");
}
};
Picasso.with(getApplicationContext())
.load(myurltodownloadfrom)
.into(target);
}
catch (Exception e){
Log.e("ERROR",e.getMessage());
}
}
Never store Files that way.
It is all covered here: https://developer.android.com/training/basics/data-storage/files.html

Zxing Embedded Barcode Reader using (BarcodeView)

My question is when scanning a pdf417 barcode format sometimes it returns a UPC_E format base on the scan result?
here is a snippet of my code
private BarcodeView barcodeView;
private BarcodeCallback callback = new BarcodeCallback() {
#Override
public void barcodeResult(BarcodeResult result) {
if (result.getText() != null) {
Toast.makeText(getActivity(), result.getText(), Toast.LENGTH_LONG).show();
}
}
#Override
public void possibleResultPoints(List<ResultPoint> resultPoints) {
}
};
here is the library
compile 'com.journeyapps:zxing-android-embedded:3.3.0'
This solved the problem. long time ago :)
private BarcodeCallback callback = new BarcodeCallback() {
#Override
public void barcodeResult(BarcodeResult result) {
if (result.getText() != null) {
String barcodeResult = result.getText();
String barcodeFormat = result.getBarcodeFormat().toString();
if (barcodeFormat.equals("PDF_417")) {
try {
String barcodeEncodedResult = new ConvertUtil().encodeIntoBase64(barcodeResult);
processEncodedResult(barcodeEncodedResult);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getActivity(), "Unable to read as PDF_417 barcode format", Toast.LENGTH_LONG).show();
}
}
}
you can pass the format to scan with intent integrator. Something like :
IntentIntegrator integrator = new IntentIntegrator(this);
integrator.setDesiredBarcodeFormats(IntentIntegrator.PDF_147);
intent = integrator.createScanIntent();
barcodeView.initializeFromIntent(intent);

Android post picture to Facebook wall

I am trying to post a picture to my wall on Facebook. I have managed logging in and posting text to the wall. However, when I try posting the picture, nothing happens.
I am using the Android Facebook SDK.
Here is what I have so far:
Bundle params = new Bundle();
params.putString("method", "photos.upload");
Toast.makeText(FacebookPoster.this, "" + getIntent().getExtras().getByteArray("data").length, Toast.LENGTH_SHORT).show();
params.putByteArray("picture", getIntent().getExtras().getByteArray("data"));
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request(null, params, "POST", new SampleUploadListener(), null);
The Toast shows 8733, which means the byte array isn't empty
NB. Logcat output some warnings (not errors):
03-02 14:19:29.554: WARN/Bundle(1891): Attempt to cast generated internal exception:
03-02 14:19:29.554: WARN/Bundle(1891): java.lang.ClassCastException: java.lang.String
03-02 14:19:29.554: WARN/Bundle(1891): at android.os.Bundle.getByteArray(Bundle.java:1305)
03-02 14:19:29.554: WARN/Bundle(1891): at com.facebook.android.Util.openUrl(Util.java:155)
03-02 14:19:29.554: WARN/Bundle(1891): at com.facebook.android.Facebook.request(Facebook.java:559)
03-02 14:19:29.554: WARN/Bundle(1891): at com.facebook.android.AsyncFacebookRunner$2.run(AsyncFacebookRunner.java:253)
03-02 14:19:29.584: WARN/Bundle(1891): Key method expected byte[] but value was a java.lang.String. The default value <null> was returned.
(Shows several times underneath each other.)
What am I doing wrong?
SOLVED.
This is what I did to make it work:
facebook.authorize(this, new String[] { "publish_stream" },
new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
}
#Override
public void onError(DialogError dialogError) {
// TODO Auto-generated method stub
}
#Override
public void onComplete(Bundle values) {
postToWall(values.getString(Facebook.TOKEN));
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
}
});
And the helper method:
private void postToWall(String accessToken) {
Bundle params = new Bundle();
params.putString(Facebook.TOKEN, accessToken);
// The byte array is the data of a picture.
params.putByteArray("picture", getIntent().getExtras().getByteArray("data"));
try {
facebook.request("me/photos", params, "POST");
} catch (FileNotFoundException fileNotFoundException) {
makeToast(fileNotFoundException.getMessage());
} catch (MalformedURLException malformedURLException) {
makeToast(malformedURLException.getMessage());
} catch (IOException ioException) {
makeToast(ioException.getMessage());
}
}
first thing is that you are not using graph api to upload the pictures... u r using the old rest api... try to use graph api, its simple...
Use following code:
Bundle param = new Bundle();
param.putString("message", "picture caption");
param.putByteArray("picture", ImageBytes);
mAsyncRunner.request("me/photos", param, "POST", new SampleUploadListener());
According to error message, it looks like its giving errors in getting bytes from intent's bundle...
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
facebook.authorize(FbdemoActivity.this, new String[]{ "user_photos,publish_checkins,publish_actions,publish_stream"},new DialogListener() {
#Override
public void onComplete(Bundle values) {
}
#Override
public void onFacebookError(FacebookError error) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onCancel() {
}
});
}
});
public void postImageonWall() {
byte[] data = null;
Bitmap bi = BitmapFactory.decodeFile("/sdcard/viewitems.png");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
Bundle params = new Bundle();
params.putString(Facebook.TOKEN, facebook.getAccessToken());
params.putString("method", "photos.upload");
params.putByteArray("picture", data);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request(null, params, "POST", new SampleUploadListener(), null);
}
public class SampleUploadListener extends BaseRequestListener {
public void onComplete(final String response, final Object state) {
try {
// process the response here: (executed in background thread)
Log.d("Facebook-Example", "Response: " + response.toString());
JSONObject json = Util.parseJson(response);
final String src = json.getString("src");
// then post the processed result back to the UI thread
// if we do not do this, an runtime exception will be generated
// e.g. "CalledFromWrongThreadException: Only the original
// thread that created a view hierarchy can touch its views."
} catch (JSONException e) {
Log.w("Facebook-Example", "JSON Error in response");
} catch (FacebookError e) {
Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
}
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
}
try this code it will work i had used the same code and uploads the image on Facebook.
Here is the working code sample. Pass image path and message.
public static void postImageonWall(String FilePath,String msg ) {
try {
Bitmap bi = BitmapFactory.decodeFile(FilePath);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bi.compress(Bitmap.CompressFormat.PNG, 100, stream); // where bm is bitmap from Sdcard
byte[] byteArray = stream.toByteArray();
Bundle param = new Bundle();
param = new Bundle();
param.putString("message", msg);
param.putString("filename", "Dessert Dash");
param.putByteArray("image", byteArray);
param.putString("caption", "Dessert Dash in Android Market Now");
mAsyncRunner.request("me/photos", param, "POST", fbrq, null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String postwall(String uid)
{
String response = "";
try
{
String DIRECTORY_PATH = "/sdcard/159.jpg";
Bundle params = new Bundle();
Bitmap bitmap = BitmapFactory.decodeFile(DIRECTORY_PATH);
byte[] data = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
params.putString("app_id", uid);
params.putString("message", "picture caption");
params.putByteArray("picture", data);
mFacebook.authorize(this, PERMISSIONS, new LoginDialogListener());
mAsyncRunner.request("me/photos", params, "POST", new WallPostRequestListener());
mAsyncRunner.request(response, new WallPostRequestListener());
Log.e("post result", response);
}
catch (Exception e)
{
e.printStackTrace();
}
return response;
}
public class WallPostRequestListener extends BaseRequestListener
{
public void onComplete(final String response)
{
Log.d("Facebook-Example", "Got response: " + response);
String message = "<empty>";
try
{
JSONObject json = Util.parseJson(response);
message = json.getString("message");
}
catch (JSONException e)
{
Log.w("Facebook-Example", "JSON Error in response");
}
catch (FacebookError e)
{
Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
}
final String text = "Your Wall Post: " + message;
}
}
I'm sure Facebook will fix this eventually, but for the time being these examples (posted by other users) are very misleading because they do NOT in fact post to the user's wall (in the regular sense). Instead they are added to the user's photo gallery, and then happen to end up on the wall, but not in the same way in which normal posts work... there is no title and no caption and if you add another photo it ends up side by side with the first (rather than as a separate entry). So, when you use the api command me/feed it just fails in a spectacular way where it actually adds a post to the wall but it's an empty post from the application (it even disregards the title and caption).
Hopefully Facebook will fix this sometime in the near term.
Posting the image and Text to Facebook wall from code, Once you logged in using facebook credentials.
note : This is applicable only after logging in to your app using facebook credentials
sharePhotoToFacebook(); //function called from any UI event
private void sharePhotoToFacebook(){
Bitmap bitmap=null;
String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/Download/";
try {
File file = new File(path, "image9.jpg");
bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
}
catch (Exception e){
Log.e("Error" , " Error in loading file");
}
SharePhoto photo = new SharePhoto.Builder()
.setBitmap(bitmap)
.setCaption("A post from Android code")
.build();
SharePhotoContent content = new SharePhotoContent.Builder()
.addPhoto(photo)
.build();
ShareApi.share(content, null);
Toast.makeText(LoginSuccessActivity.this, "Image posted successfully", Toast.LENGTH_LONG).show();
}

Categories