Not sure if this is know behavior or what, but here's the logical flow:
User opens app
Pulls nav drawer out, clicks profile pic to change it
Gallery intent pops up, user picks image, everything works fine
Subsequent attempt to open gallery works fine, upon choosing picture, application hangs
onResume() is not called, neither is onActivityResult(). I even commented out all the code in onActivityResult and it still happens. Any ideas what would cause this?
Here is code from onCreate() in the main activity
ImageButton profilePictureButton = (ImageButton) findViewById(R.id.change_profile_picture);
profilePictureButton.requestFocus();
profilePictureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 1);
}
});
And here's the handler:
#Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
if(resultCode == RESULT_OK) {
if(requestCode == 1) {
ImageView view = ((ImageView) findViewById(R.id.nav_profile_picture));
if(data != null) {
/*Picasso.with(this).load(data.getData()).into(view);
UsersCache.getInstance().GetUser("", new Response.Listener<UserItem>() {
#Override
public void onResponse(UserItem response) {
String pictureName = response.username + UUID.randomUUID().toString();
String url = "<redacted>";
JSONObject requestBody = new JSONObject();
try {
requestBody.put("profilePicture", "<redacted>/media/profile_pictures/" + pictureName);
} catch(JSONException e) {
e.printStackTrace();
return;
}
FlareJsonObjectRequest request = new FlareJsonObjectRequest(Method.POST, url, requestBody, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
String tet = null;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
String tet = null;
}
});
new AmazonS3Uploader(data.getData(), "profile_pictures/" + pictureName);
VolleyQueue.getInstance().getQueue().add(request);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
String tet = null;
}
});*/
}
}
I think you are missing the read access permission in Manifest -
android:name="android.permission.READ_EXTERNAL_STORAGE" />
Related
Seems simple, but I can't get it to work. I have a public class string variable that should change within a if or switch statement. I haven't declared the variable inside the statement so it should change given the scope, no? But it only reads "FROM" and when I do go to change it in the if statement that applies, it does change to "TO" but only in that instance and reverts back to "FROM". I would pass it along the methods, but the full code is more cluttered and I don't think it's possible to do so.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
String typeOfText = "FROM";
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantRequest) {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.faboptions_favorite) {
Toast.makeText(MainActivity.this, "FROM", Toast.LENGTH_SHORT).show();
typeOfText = "FROM";
cameraSource.takePicture(null, new CameraSource.PictureCallback() {
#Override
public void onPictureTaken(byte[] bytes) {
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
cropPicFile(bmp);
}
});
} else if (view.getId() == R.id.faboptions_textsms) {
Toast.makeText(MainActivity.this, "TO", Toast.LENGTH_SHORT).show();
typeOfText = "TO";
Log.d("VARIABLE","" + typeOfText);
cameraSource.takePicture(null, new CameraSource.PictureCallback() {
#Override
public void onPictureTaken(byte[] bytes) {
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
cropPicFile(bmp);
}
});
} else {
typeOfText = "FROM";
Toast.makeText(MainActivity.this, "Share", Toast.LENGTH_SHORT).show();
createDialogSaveInfo();
}
}
private void createDialogSaveInfo() {
final Dialog dialog = new Dialog(MainActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setContentView(R.layout.dialog_confirm_address_scan);
//Establish Dialog Views
Button submit = (Button) dialog.findViewById(R.id.button_dialog_scanner_submit);
Button cancel = (Button) dialog.findViewById(R.id.button_dialog_scanner_cancel);
final EditText fromEditText = (EditText) dialog.findViewById(R.id.editText_dialog_scanner_from);
final EditText toEditText = (EditText) dialog.findViewById(R.id.editText_dialog_scanner_to);
//Set text from captured strings in surface view
fromEditText.setText(fromAddress);
toEditText.setText(toAddress);
//Setup listeners
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//TODO save info to realm
saveLabelInfoIntoRealm(fromEditText.getText().toString(), toEditText.getText().toString());
dialog.dismiss();
}
});
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
private void saveLabelInfoIntoRealm(final String from, final String to) {
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
Package userPackage = realm.createObject(Package.class, 0);
userPackage.setFromAddress(from);
userPackage.setToAddress(to);
}
});
}
private int getPrimaryKey() {
try {
return realm.where(Package.class).max("primaryKey").intValue() + 1;
} catch (ArrayIndexOutOfBoundsException e) {
return 0;
}
}
private void configureListeners() {
fabOptions.setOnClickListener(this);
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
if (path == null) {
Log.d("TAG", "" + path.toString());
}
return Uri.parse(path);
}
private void cropPicFile(Bitmap file) {
Uri imageToCrop = getImageUri(this, file);
CropImage.activity(imageToCrop)
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri photo = result.getUri();
readImage(photo);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
private void readImage(Uri photo) {
StringBuilder stringBuilder = new StringBuilder();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), photo);
Frame imageFrame = new Frame.Builder()
.setBitmap(bitmap)
.build();
final SparseArray<TextBlock> items = textRecognizer.detect(imageFrame);
for (int i = 0; i < items.size(); i++) {
TextBlock item = items.valueAt(i);
stringBuilder.append(item.getValue());
stringBuilder.append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
Log.d("VARIABLE","" + typeOfText);
if (typeOfText.equals("FROM")) {
fromAddress = stringBuilder.toString();
} else if (typeOfText.equals("TO")){
toAddress = stringBuilder.toString();
}
}
}
The reason the code keeps reverting is because the call to readImage() is in onActivityResult() which recreates the activity when called. So basically, you are getting a fresh object, and the onTypeText() is reinitialized. onActivityResult() is basically a callback from your previous activity.
Your onClick() is not being called due you don't assign clicklistener to R.id.faboptions_favorite and the other View
in onCreate add :
findViewById(R.id.faboptions_favorite).setOnClickListener(this);
and same for the other view.
I am working on quickblox message attachment functionality in android.
What all I am trying to do is : OnViewClicked one CreateChooser(type:images/*) would be open.
After selecting an image it will come to onActivityResult method where it stores Uri.
Post that sendAttachment function is being called.
Here is my coding portion :
private Uri uri;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case FILE_SELECT_CODE:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
uri = data.getData();
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
public void sendAttachment() {
File filePhoto = new File(uri.getPath());
Boolean fileIsPublic = false;
QBContent.uploadFileTask(filePhoto, fileIsPublic, null, new QBProgressCallback() {
#Override
public void onProgressUpdate(int i) {
// i - progress in percentages
Log.e(TAG, "onProgressUpdate: " + i);
}
}).performAsync(new QBEntityCallback<QBFile>() {
#Override
public void onSuccess(QBFile qbFile, Bundle bundle) {
Integer id = qbFile.getId();
// create a message
QBChatMessage chatMessage = new QBChatMessage();
chatMessage.setProperty("save_to_history", "1"); // Save a message to history
// attach a photo
QBAttachment attachment = new QBAttachment("photo");
attachment.setId(qbFile.getId().toString());
chatMessage.setBody("");
chatMessage.addAttachment(attachment);
// send a message
try {
mQBChatDialog.sendMessage(chatMessage);
mtvEmpty.setVisibility(View.INVISIBLE);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
#Override
public void onError(QBResponseException errors) {
Log.e("DATA", TextUtils.join(",", errors.getErrors()));
}
});
}
LOGCAT ERROR :
E/ERROR: File upload onError,File does not exist,Passed object is not file,Incorrect content type
I found out a solution on this.
This type of error displays whenever you try to add file that does not exist on your device physically.
To resolve the problem I simply downloaded new file & my code worked with a charm.
Try below Code.It works for me to upload image,video and audio
public void uploadAttachment(final File file, final int fileType) {
String tags = CollectionsUtils.getMimeType(Uri.fromFile(file));
ChatHelper.getInstance().loadFileAsAttachment(file, tags, new QBEntityCallback<QBAttachment>() {
#Override
public void onSuccess(QBAttachment result, Bundle params) {
fileUploadProgressMap.remove(item);
result.setType(String.valueOf(fileType));
fileQBAttachmentMap.put(item, result);
notifyDataSetChanged();
}
#Override
public void onError(QBResponseException e) {
onAttachmentUploadErrorListener.onAttachmentUploadError(e);
remove(item);
}
}, new QBProgressCallback() {
#Override
public void onProgressUpdate(final int progress) {
fileUploadProgressMap.put(item, progress);
mainThreadHandler.post(new Runnable() {
#Override
public void run() {
notifyDataSetChanged();
}
});
}
});
}
public void loadFileAsAttachment(File file, String tags, QBEntityCallback<QBAttachment> callback,
QBProgressCallback progressCallback) {
QBContent.uploadFileTask(file, true, tags, progressCallback)
.performAsync(new QbEntityCallbackTwoTypeWrapper<QBFile, QBAttachment>(callback) {
#Override
public void onSuccess(QBFile qbFile, Bundle bundle) {
QBAttachment attachment = new QBAttachment(QBAttachment.PHOTO_TYPE);
attachment.setId(qbFile.getId().toString());
attachment.setUrl(qbFile.getPublicUrl());
callback.onSuccess(attachment, bundle);
}
});
}
Rather using uri.getPath() for getting the file please use uri.getLastPathSegment().
I am trying to open camera intent in my app.But I just need to make sure that the image doesn't get saved in either the SD Card or in the Internal Storage.Also the image should get displayed in the app when the picture is clicked.
public class FBCheckInActivity extends Activity{
private CallbackManager callbackManager;
private LoginManager loginManager;
private File mFileTemp;
public static final int REQUEST_CODE_TAKE_PICTURE = 2;
public String path;
Bitmap sharingPhoto;
String caption="";
ImageView chooseImage;
EditText captionText;
Button postFacebook;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.facebook_sharing);
printHashKey();
sharingPhoto= BitmapFactory.decodeResource(this.getResources(), R.drawable.no_image);
FacebookSdk.sdkInitialize(getApplicationContext());
fbSharing(sharingPhoto);
}
private void fbSharing(Bitmap sharingPhoto) {
chooseImage=(ImageView) findViewById(R.id.share_image);
chooseImage.setImageBitmap(sharingPhoto);
captionText=(EditText) findViewById(R.id.caption_text);
postFacebook=(Button) findViewById(R.id.buttonPost);
postFacebook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginFaceBook();
}
});
chooseImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openCamera();
}
});
captionText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
caption = captionText.getText().toString();
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
#Override
protected void onResume() {
super.onResume();
}
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
if(requestCode==REQUEST_CODE_TAKE_PICTURE){
Log.d("zambo","after selecting pic");
path = mFileTemp.getPath();
Log.d("zambo", path);
sharingPhoto = BitmapFactory.decodeFile(path);
chooseImage.setImageBitmap(sharingPhoto);
fbSharing(sharingPhoto);
}
else {
Log.d("zambo","callback manager for facebook sharing");
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}
public void printHashKey(){
try {
PackageInfo info = getPackageManager().getPackageInfo(
"com.urbanwand",
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
}
public void loginFaceBook(){
callbackManager = CallbackManager.Factory.create();
List<String> permissionNeeds = Arrays.asList("publish_actions");
loginManager = LoginManager.getInstance();
loginManager.logInWithPublishPermissions(FBCheckInActivity.this, permissionNeeds);
loginManager.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
graphApi(accessToken);
}
#Override
public void onCancel() {
Toast.makeText(FBCheckInActivity.this, "cancel", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(FacebookException error) {
Toast.makeText(FBCheckInActivity.this, "error", Toast.LENGTH_SHORT).show();
}
});
}
public void openCamera(){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
Uri mImageCaptureUri = null;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
mFileTemp = new File(Environment
.getExternalStorageDirectory(), "IMG_"
+ ".jpg");
mImageCaptureUri = Uri.fromFile(mFileTemp);
} else {
/*
* The solution is taken from here:
* http://stackoverflow.com/questions
* /10042695/how-to-get-camera-result-as-a-uri-in-data-folder
*/
mFileTemp = new File(getFilesDir(), "IMG_"
+ ".jpg");
mImageCaptureUri = InternalStorageContentProvider.CONTENT_URI;
}
intent.putExtra(MediaStore.EXTRA_OUTPUT,
mImageCaptureUri);
intent.putExtra("return-data", true);
startActivityForResult(intent, REQUEST_CODE_TAKE_PICTURE);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
//Log.d("User_Photo", "cannot take picture", e);
}
}
public void graphApi(AccessToken accessToken){
GraphRequest request = GraphRequest.newUploadPhotoRequest(accessToken, "me/photos", sharingPhoto, caption, null, new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
Log.d("zambo","On Completed Callback");
AlertDialog.Builder completeDialog = new AlertDialog.Builder(FBCheckInActivity.this);
completeDialog.setMessage("Thank you for sharing your happiness!!");
completeDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(FBCheckInActivity.this, DinerHotSellers.class));
overridePendingTransition(0, 0);
}
});
completeDialog.create();
completeDialog.show();
}
});
request.executeAsync();
}
This is what i have implemnted till now. But it doesn't give me the image back in the activity if it is stored in SD Card. Also the image is getting saved. Is is possible not to save the image in the storage media?
Thanks
A simple demo:
maim.xml
<button android:id="#+id/button1" android:layout_height="wrap_content" android:layout_width="match_parent" android:text="TakePhoto" button="">
<imageview android:id="#+id/imageView1" android:layout_gravity="center_horizontal" android:layout_height="wrap_content" android:layout_width="wrap_content"></imageview></button>
MainActivity.java(not all)
public static final int TAKE_PHOTO = 1;
public static final int CROP_PHOTO = 2;
private Button takePhotoBn;
private ImageView showImage;
private Uri imageUri;
private String filename;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
takePhotoBn = (Button) findViewById(R.id.button1);
showImage = (ImageView) findViewById(R.id.imageView1);
takePhotoBn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SimpleDateFormat format = new SimpleDateFormat(yyyyMMddHHmmss);
Date date = new Date(System.currentTimeMillis());
filename = format.format(date);
//File outputImage = new File(Environment.getExternalStorageDirectory(),test.jpg);
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
File outputImage = new File(path,filename+.jpg);
try {
if(outputImage.exists()) {
outputImage.delete();
}
outputImage.createNewFile();
} catch(IOException e) {
e.printStackTrace();
}
imageUri = Uri.fromFile(outputImage);
Intent intent = new Intent(android.media.action.IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent,TAKE_PHOTO);
}
});
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK) {
Toast.makeText(MainActivity.this, ActivityResult resultCode error, Toast.LENGTH_SHORT).show();
return;
}
switch(requestCode) {
case TAKE_PHOTO:
Intent intent = new Intent(com.android.camera.action.CROP); //cut
intent.setDataAndType(imageUri, image/*);
intent.putExtra(scale, true);
intent.putExtra(aspectX, 1);
intent.putExtra(aspectY, 1);
intent.putExtra(outputX, 340);
intent.putExtra(outputY, 340);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
Toast.makeText(MainActivity.this, " ", Toast.LENGTH_SHORT).show();
//flush
Intent intentBc = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intentBc.setData(imageUri);
this.sendBroadcast(intentBc);
startActivityForResult(intent, CROP_PHOTO);
break;
case CROP_PHOTO:
try {
Bitmap bitmap = BitmapFactory.decodeStream(
getContentResolver().openInputStream(imageUri));
Toast.makeText(MainActivity.this, imageUri.toString(), Toast.LENGTH_SHORT).show();
showImage.setImageBitmap(bitmap); //show image
} catch(FileNotFoundException e) {
e.printStackTrace();
}
break;
default:
break;
}
}
you need add permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">
<uses-permission android:name="android.permission.CAMERA"> </uses-permission></uses-permission>
I want to pick a video file from gallery (first part of my code) and upload it to a server using Retrofit-neglect it for this question please. So, I want to pass a File from the first part to the second one but it gives me the error mentioned in the title.
MainActivity:
public class MainActivity extends Activity
{
private static int RESULT_LOAD_VIDEO = 1;
String decodableString;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button btn_load = (Button) findViewById(R.id.buttonLoadVideo);
btn_load.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
loadVideoFromGallery(btn_load);
}
});
}
/*
* PICK THE VIDEO AND EXTRACT ITS ADDRESS
*/
public void loadVideoFromGallery(View view)
{
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_VIDEO);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
try {
// When a video is picked
if (requestCode == RESULT_LOAD_VIDEO && resultCode == RESULT_OK
&& null != data)
{
// Get the video from data
Uri selectedVideo = data.getData();
String[] filePathColumn = { MediaStore.Video.Media.DATA };
Cursor cursor = getContentResolver().query(selectedVideo,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
decodableString = cursor.getString(columnIndex);
Log.i("mok","ds: " + decodableString);//ds: /storage/extSdCard/DCIM/Camera/20151112_142950.mp4
Log.i("mok","svp: " + selectedVideo.getPath());//svp: /external/video/media/253
Log.i("mok","fpc0: " + filePathColumn[0]);//fpc0: _data
cursor.close();
File file = new File(selectedVideo.getPath());
upload(file);
} else
{
Toast.makeText(this, "You haven't picked any video",
Toast.LENGTH_LONG).show();
}
} catch (Exception e)
{
e.printStackTrace();
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
/*
* UPLOAD THE SELECTED VIDEO TO THE SRVER
*/
public void upload(File file)
{
final String BASE_URL = "http://192.168.1.7/";
Retrofit retrofit = new Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
UploadApiService service = retrofit.create(UploadApiService.class);
MediaType MEDIA_TYPE = MediaType.parse("video/mp4");
RequestBody requestBody = RequestBody.create(MEDIA_TYPE, file);
Call<ResponseBody> call = service.uploadVideo("desc", requestBody);
call.enqueue(new Callback<ResponseBody>(){
#Override
public void onResponse(Response<ResponseBody> response, Retrofit retrofit)
{
// TODO Auto-generated method stub
if (response.isSuccess())
{
Log.i("mok","S");
ResponseBody rb = response.body();
}
else
{
Log.i("mok","F");
com.squareup.okhttp.ResponseBody rb = response.errorBody();
}
}
#Override
public void onFailure(Throwable t)
{
t.printStackTrace();
Log.i("mok",t.getCause()+"");
Log.i("mok","T");
finish();
}
});
}
}
Just I had to use File file = new File(decodableString). The error is gone (the question answered) so I posted this answer, but the solution for uploading the file is not working properly (that's another issue).
I have integrated Facebook into my app. However, instead of bringing it up in a dialog, it opens full screen. I was wondering if anyone would know of a way to change this to dialog.
FaceBook Handler Class:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/*
* Get existing access_token if any
*/
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if(access_token != null)
facebook.setAccessToken(access_token);
if(expires != 0)
facebook.setAccessExpires(expires);
if (facebook.isSessionValid())
postFacebookMessage();
else {
facebook.authorize(this, new String[] {"publish_stream"}, new Facebook.DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
Toast.makeText(FacebookConnector.this, "Facebook error: " + e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
#Override
public void onError(DialogError e) {
Toast.makeText(FacebookConnector.this, "Facebook dialog error: " + e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
#Override
public void onComplete(Bundle values) {
postFacebookMessage();
Toast.makeText(FacebookConnector.this, "Thank You For Sharing!", Toast.LENGTH_SHORT).show(); }
#Override
public void onCancel() {Toast.makeText(FacebookConnector.this, "Facebook authorization cancelled.", Toast.LENGTH_LONG).show();
}
});
}
}
private void postFacebookMessage() {
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
Bundle params = new Bundle();
params.putString("message", MSG);
params.putString("picture", "http://meanwhileinwv.com/meanwhile.png");
mAsyncRunner.request("me/feed", params, "POST", new FacebookPostListener(), null); }
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
}
The code above produces the following result:
I would like it to be a dialog that the facebook window opens into. I have achieved this with my Twitter code:
Call authorization with additional parameter Facebook.FORCE_DIALOG_AUTH, like this:
facebook.authorize(this, new String[] {"publish_stream"}, Facebook.FORCE_DIALOG_AUTH, new Facebook.DialogListener() { ... });