Post media tweets with Twitter Fabric SDK - android

I have included Twitter Fabric SDK in my android application and can post tweets from it. I would like to post images as well though but that doesn't seem possible through the StatusesService that is used to post text-only tweets.
Is it not possible to do this through the SDK? Do I have to do an explicit http post for this?

According to the Fabric SDK, yes you can embed media in your Tweet through TweetUI.
Sample Code
Initialize with Fabric
Fabric.with(this, new TweetComposer());
Tweet Code
TweetComposer.Builder builder = new TweetComposer.Builder(this)
.text("just setting up my Fabric.")
.image(myImageUri);
builder.show();
File myImageFile = new File("/path/to/image");
Uri myImageUri = Uri.fromFile(myImageFile);
Remember
In the event that the Twitter app is not installed, TweetComposer will
create an intent to interact with the Twitter.com in a browser. The
browser ignores a specified image.

package ...
public class StatusFragment extends Fragment {
Button btn_select, btn_post_image;
EditText edt_status;
String status;
ImageView img_status;
private static final int RESULT_LOAD_IMAGE = 1;
SharedPreferences mSharedPreferences;
String selectedImagePath;
Uri selectedImage;
TypedFile typedFile;
private static final String IMAGE_DIRECTORY_NAME = "Hello Twitter";
String mCurrentPhotoPath;
File mFile;
ProgressDialog pDialog;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_status, container, false);
btn_post_image = (Button) rootView.findViewById(R.id.btn_post_image);
btn_select = (Button) rootView.findViewById(R.id.btn_select);
edt_status = (EditText) rootView.findViewById(R.id.edt_status);
img_status = (ImageView) rootView.findViewById(R.id.img_status);
btn_post_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (StatusFragment.CheckNetwork.isInternetAvailable(getActivity())) //if connection available
{
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Uploading......");
pDialog.show();
final TwitterSession session = Twitter.getSessionManager().getActiveSession();
mFile = new File(getRealPathFromURI(selectedImage));
TypedFile typedFile = new TypedFile("application/octet-stream", mFile);
TwitterApiClient twitterApiClient = TwitterCore.getInstance().getApiClient(session);
MediaService ms = twitterApiClient.getMediaService();
ms.upload(typedFile, null, null, new Callback<Media>() {
#Override
public void success(Result<Media> mediaResult) {
// show on User Timeline
// StatusesService statusesService = TwitterCore.getInstance().getApiClient(session).getStatusesService();
// statusesService.update(edt_status.getText().toString(), null, false, null, null, null, true, false, mediaResult.data.mediaIdString, new Callback<Tweet>() {
// #Override
// public void success(Result<Tweet> tweetResult) {
// //...
// Toast.makeText(getActivity(), "Upload Complete", Toast.LENGTH_SHORT).show();
// pDialog.dismiss();
// }
//
// #Override
// public void failure(TwitterException e) {
// //...
// Toast.makeText(getActivity(), "Upload Error" + e.getMessage(), Toast.LENGTH_SHORT).show();
// pDialog.dismiss();
// }
//
// });
// Show on Home Timeline
StatusesService statusesService = TwitterCore.getInstance().getApiClient(session).getStatusesService();
statusesService.update( " content: " + edt_status.getText().toString(), null, false, null, null, null, true, false, mediaResult.data.mediaIdString, new Callback<Tweet>() {
#Override
public void success(Result<Tweet> tweetResult) {
pDialog.dismiss();
Toast.makeText(getActivity(), "Upload Completed", Toast.LENGTH_SHORT).show();
}
#Override
public void failure(TwitterException e) {
//...
pDialog.dismiss();
Toast.makeText(getActivity(), "Upload Error"+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void failure(TwitterException e) {
//...
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else{
Toast.makeText(getActivity(), "Network error", Toast.LENGTH_SHORT).show();
}
}
});
btn_select.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
return rootView;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == Activity.RESULT_OK) {
selectedImage = data.getData();
img_status.setImageURI(selectedImage);
}
}
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);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri contentUri) {
try {
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} catch (Exception e) {
return contentUri.getPath();
}
}
public static class CheckNetwork {
static String TAG = CheckNetwork.class.getSimpleName();
public static boolean isInternetAvailable(Context context) {
NetworkInfo info = (NetworkInfo) ((ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (info == null) {
Log.d(TAG, "no internet connection");
return false;
} else {
if (info.isConnected()) {
Log.d(TAG, " internet connection available...");
return true;
} else {
Log.d(TAG, " internet connection");
return true;
}
}
}
}
public class MyTwitterApiClient extends TwitterApiClient {
public MyTwitterApiClient(TwitterSession session) {
super(session);
}
public UploadMediaService getUploadMediaService() {
return getService(UploadMediaService.class);
}
}
interface UploadMediaService {
#Multipart
#POST("1.1/media/upload.json")
void upload(#Part("media") TypedFile file, #Part("additional_owners") String owners, Callback<MediaEntity> cb);
}
public void openPath(Uri uri) {
InputStream is = null;
try {
is = getActivity().getContentResolver().openInputStream(uri);
//Convert your stream to data here
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Try it!

Related

i want to send image and some data using volley in android

I want to send image as well as data using volley help me i need simplest way to send it please help me i have tried in postman where i selected the file rather than text and send all went well i need like that.
Map<String, String> params = new HashMap<String, String>();
params.put("number", strUserName.trim());
params.put("image", image);
JSONObject json = new JSONObject(params);
String url = "";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url
, json, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject object = new JSONObject(String.valueOf(response));
String status = object.getString("Status");
if (status.equals("200")) {
Intent intent = new Intent(MainActivity.this, OtpVerification.class);
intent.putExtra("mobile1",strUserName);
startActivity(intent);
finish();
} else if(status.equals("404")) {
Toast.makeText(MainActivity.this, "Please Enter Valid No.", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Log.e("Ashish", " " + e);
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(jsonObjectRequest);
}
I have tried this now but its shopwing me the error my value on addstring are not passing they are sending empty as i am directly putting the value too.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
btnChoose = findViewById(R.id.button_choose);
btnUpload = findViewById(R.id.button_upload);
btnChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
imageBrowse();
}
});
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (filePath != null) {
imageUpload(filePath);
} else {
Toast.makeText(getApplicationContext(), "Image not selected!", Toast.LENGTH_LONG).show();
}
}
});
}
private void imageBrowse() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == PICK_IMAGE_REQUEST) {
Uri picUri = data.getData();
filePath = getPath(picUri);
Log.d("picUri", picUri.toString());
Log.d("filePath", filePath);
imageView.setImageURI(picUri);
}
}
}
private void imageUpload(final String imagePath) {
SimpleMultiPartRequest smr1= new SimpleMultiPartRequest(Request.Method.POST, BASE_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response", response);
try {
JSONObject jObj = new JSONObject(response);
String message = jObj.getString("status");
if (message.equals("201")) {
Toast.makeText(getApplicationContext(), message + "Done", Toast.LENGTH_LONG).show();
} else if (message.equals("200")) {
Toast.makeText(getApplicationContext(), message + "Done", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
smr1.addStringParam("a_k_s_no", "1112");
smr1.addStringParam("year", "2020");
smr1.addStringParam("month", "01");
smr1.addStringParam("token", "5c041062bf7ab2a409f910ab34fe6e1e");
smr1.addFile("fileToUpload", imagePath);
MyApplication.getInstance().addToRequestQueue(smr1);
}
private String getPath(Uri contentUri) {
String[] proj = {MediaStore.Images.Media.DATA};
CursorLoader loader = new CursorLoader(getApplicationContext(), contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
Sample Code :
Volley Image Upload Layout
For creating the above layout you can use the following xml code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Upload Image using Volley"
android:id="#+id/textView"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="10dp"/>
<Button
android:id="#+id/button_choose"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorAccent"
android:text="Browse Image"
android:textColor="#fff"
android:layout_gravity="center_horizontal"
android:layout_margin="20dp"
android:padding="10dp"/>
<ImageView
android:id="#+id/imageView"
android:layout_width="200dp"
android:layout_height="200dp"
android:background="#drawable/border"
android:layout_gravity="center_horizontal"
android:padding="5dp"
android:layout_margin="20dp"/>
<Button
android:id="#+id/button_upload"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorAccent"
android:text="upload"
android:textColor="#fff"
android:layout_gravity="center_horizontal"
android:layout_margin="20dp"/>
</LinearLayout>
Now lets come to MainActivity.java
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
private Button btnChoose, btnUpload;
public static String BASE_URL = "http://192.168.1.100/AndroidUploadImage/upload.php";
static final int PICK_IMAGE_REQUEST = 1;
String filePath;
Now implement OnClickListener interface to our buttons.
btnChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
imageBrowse();
}
});
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (filePath != null) {
imageUpload(filePath);
} else {
Toast.makeText(getApplicationContext(), "Image not selected!", Toast.LENGTH_LONG).show();
}
}
});
Now we will create a method to choose image from gallery. Create the following method.
private void imageBrowse() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST);
}
To complete the image choosing process we need to override the following method.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if(requestCode == PICK_IMAGE_REQUEST){
Uri picUri = data.getData();
filePath = getPath(picUri);
imageView.setImageURI(picUri);
}
}
}
// Get Path of selected image
private String getPath(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(getApplicationContext(), contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
More information about Android Images, read chapter Amazing Facts of Android ImageView.
Now run your application and if you can choose image from gallery then you can move ahead. In below snapshot you can see mine app is working.Image Upload Using Volley
Now we need to create one more method that will upload the image to our server. Create the following method in MainActivity class.
private void imageUpload(final String imagePath) {
SimpleMultiPartRequest smr = new SimpleMultiPartRequest(Request.Method.POST, BASE_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response", response);
try {
JSONObject jObj = new JSONObject(response);
String message = jObj.getString("message");
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
smr.addFile("image", imagePath);
MyApplication.getInstance().addToRequestQueue(smr);
}
So the final complete code for our MainActivity.java file would be like
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
private Button btnChoose, btnUpload;
public static String BASE_URL = "http://192.168.1.100/AndroidUploadImage/upload.php";
static final int PICK_IMAGE_REQUEST = 1;
String filePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
btnChoose = (Button) findViewById(R.id.button_choose);
btnUpload = (Button) findViewById(R.id.button_upload);
btnChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
imageBrowse();
}
});
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (filePath != null) {
imageUpload(filePath);
} else {
Toast.makeText(getApplicationContext(), "Image not selected!", Toast.LENGTH_LONG).show();
}
}
});
}
private void imageBrowse() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if(requestCode == PICK_IMAGE_REQUEST){
Uri picUri = data.getData();
Log.d("picUri", picUri.toString());
Log.d("filePath", filePath);
imageView.setImageURI(picUri);
}
}
}
private void imageUpload(final String imagePath) {
SimpleMultiPartRequest smr = new SimpleMultiPartRequest(Request.Method.POST, BASE_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response", response);
try {
JSONObject jObj = new JSONObject(response);
String message = jObj.getString("message");
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
smr.addFile("image", imagePath);
MyApplication.getInstance().addToRequestQueue(smr);
}
// Get Path of selected image
private String getPath(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(getApplicationContext(), contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
}
Now at last add below permission to your application.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
MyApplication.java
public class MyApplication extends Application {
public static final String TAG = MyApplication.class.getSimpleName();
private RequestQueue mRequestQueue;
private static MyApplication mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized MyApplication getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
Hope this will work!

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=-1, data=null} to activity

I want to show my image in imageview after click but i don't know why this error occur and i searched a lot on this but i could no find solution of this problem and i tried to implement code after see solution but it doesn't work,so i m confused what's going wrong.This is my code:
package kmsg.com.onetouch.activity;
public class UploadDocumentActivity extends AppCompatActivity {
JSONParser parser;
Bitmap photo;
ImageView mImgDocument;
Button mBtnBill,mBtnPres,mBtnGetFile,mBtnUpload;
EditText mEtBillDate,mEtbillValue,mEtStoreRefID,mEtDoctorID;
LinearLayout mBillLinear,mPresLinear;
String mBillDate,mBillValue,mStoreRefID,mDoctorID;
boolean flag= true;
private static final int CAMERA_REQUEST = 1888;
private static final int MY_CAMERA_PERMISSION_CODE = 100;
File imageFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_document);
parser = new JSONParser(this);
init();
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
}
private void init() {
mImgDocument=(ImageView)findViewById(R.id.imgDocument);
mBtnBill=(Button)findViewById(R.id.btnBill);
mBtnPres=(Button)findViewById(R.id.btnPres);
mBtnGetFile=(Button)findViewById(R.id.btnGetFile);
mBtnUpload=(Button)findViewById(R.id.btnUpload);
mEtBillDate=(EditText)findViewById(R.id.et_billDate);
mEtbillValue=(EditText)findViewById(R.id.et_billValue);
mEtStoreRefID=(EditText)findViewById(R.id.et_refID);
mEtDoctorID=(EditText)findViewById(R.id.et_doctorID);
mBillLinear=(LinearLayout)findViewById(R.id.bill_linear);
mPresLinear=(LinearLayout)findViewById(R.id.prescription_linear);
}
public void getBill(View view) {
flag= true;
mPresLinear.setVisibility(View.GONE);
mBillLinear.setVisibility(View.VISIBLE);
}
public void getPrescription(View view) {
flag=false;
mBillLinear.setVisibility(View.GONE);
mPresLinear.setVisibility(View.VISIBLE);
}
public void getFile(View view) {
if (ContextCompat.checkSelfPermission(UploadDocumentActivity.this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(UploadDocumentActivity.this,new String[]{Manifest.permission.CAMERA},
MY_CAMERA_PERMISSION_CODE);
} else {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String pictureNm = getPictureName();
imageFile = new File(pictureDirectory , pictureNm);
Uri pictureUri = Uri.fromFile(imageFile);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,pictureUri);
cameraIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY,1);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
}
/* public void getFile(View view) {
if (ContextCompat.checkSelfPermission(UploadDocumentActivity.this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(UploadDocumentActivity.this,new String[]{Manifest.permission.CAMERA},
MY_CAMERA_PERMISSION_CODE);
} else {
Intent i=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File dir=
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
String pictureNm = getPictureName();
File output=new File(dir, pictureNm);
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(output));
startActivityForResult(i, CAMERA_REQUEST);
}
}
*/
private String getPictureName(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String timestamp = sdf.format(new Date());
return "paymentProof" + timestamp + ".jpg";
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_CAMERA_PERMISSION_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
Intent cameraIntent = new
Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
} else {
Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//super.onActivityResult(requestCode, resultCode, data);
if(resultCode != RESULT_CANCELED){
if (requestCode == CAMERA_REQUEST) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
mImgDocument.setImageBitmap(photo);
}
}
}
private boolean validateFormForBill() {
mBillDate = mEtBillDate.getText().toString().trim();
mBillValue = mEtbillValue.getText().toString().trim();
mStoreRefID = mEtStoreRefID.getText().toString().trim();
mEtBillDate.setError(null);
mEtbillValue.setError(null);
mEtStoreRefID.setError(null);
if (TextUtils.isEmpty(mBillDate.trim())) {
mEtBillDate.setError("Bill Date cannot be blank");
return false;
}
if (TextUtils.isEmpty(mBillValue.trim())) {
mEtbillValue.setError("Bill Value cannot be blank");
return false;
}
if (TextUtils.isEmpty(mStoreRefID.trim())) {
mEtStoreRefID.setError("Ref ID cannot be blank");
return false;
}
return true;
}
private boolean validateFormForPres() {
mDoctorID = mEtDoctorID.getText().toString().trim();
mEtDoctorID.setError(null);
if (TextUtils.isEmpty(mDoctorID.trim())) {
mEtDoctorID.setError("Doctor ID cannot be blank");
return false;
}
return true;
}
public void uploadDocument(View view) {
if (UtilityServices.checkInternetConnection(UploadDocumentActivity.this)) {
if (flag) {
if (UploadDocumentActivity.this.validateFormForBill()) {
new UploadBill().execute();
}
} else {
if (UploadDocumentActivity.this.validateFormForPres()) {
// new UploadPres().execute();
}
}
}else {
Toast.makeText(this, R.string.no_internet, Toast.LENGTH_SHORT).show();
}
}
private class UploadBill extends AsyncTask<String,String,String> {
String status= null;
String msg = null;
JSONObject responseObject;
#Override
protected String doInBackground(String... strings) {
List<Part> partList = new ArrayList<>();
partList.add(new StringPart("billAmt", mBillValue));
partList.add(new StringPart("billDate", mBillDate));
partList.add(new StringPart("storeId", mStoreRefID));
System.out.println("Data"+mBillDate+mBillValue+mStoreRefID);
partList.add(new StringPart("userMobile", SharedPrefManager.getString("mobile")));
/* try {
partList.add(new FilePart("file", imageFile));
} catch (FileNotFoundException e) {
e.printStackTrace();
}*/
String url = Constants.UPLOAD_BILL;
System.out.println("partList:"+partList);
responseObject = parser.makeHttpRequestWithMultipart(url, partList);
try {
// Simulate network access.
if (responseObject != null) {
System.out.println("responseObject: " + responseObject.toString());
try {
status = responseObject.getString(Constants.SVC_STATUS);
return status;
} catch (JSONException e) {
e.printStackTrace();
}
}
if (responseObject.has(Constants.SVC_MSG)) {
try {
msg = responseObject.getString(Constants.SVC_MSG);
} catch (JSONException e) {
e.printStackTrace();
}
return status;
}
return "";
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final String success) {
super.onPostExecute(success);
if (success != null) {
System.out.println(Constants.STATUS_SUCCESS);
if (Constants.STATUS_SUCCESS.equals(success)) {
System.out.println("Successful Svc Call:"+ "post object task details called");
Toast.makeText(UploadDocumentActivity.this, "Successful Svc Call:"+ "post object task details called", Toast.LENGTH_LONG).show();
} else {
System.out.println(success);
try {
AlertDialog alertDialog = new AlertDialog.Builder(UploadDocumentActivity.this).create();
alertDialog.setTitle("Info");
alertDialog.setMessage(responseObject.getString(Constants.SVC_MSG));
alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
catch(Exception e)
{
UtilityServices.appendLog("Show Dialog: "+e.getMessage());
}
}
} else {
System.out.println("svcstatus is null");
}
}
}
private class UploadPres extends AsyncTask<String,String,String> {
String status= null;
String msg = null;
JSONObject responseObject;
#Override
protected String doInBackground(String... strings) {
List<Part> partList = new ArrayList<>();
partList.add(new StringPart("storeId", mDoctorID));
partList.add(new StringPart("userMobile", SharedPrefManager.getString("mobile")+""));
try {
partList.add(new FilePart("file", imageFile));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String url = Constants.UPLOAD_PRESCRIPTION;
System.out.println("partList:"+partList);
responseObject = parser.makeHttpRequestWithMultipart(url, partList);
try {
// Simulate network access.
if (responseObject != null) {
System.out.println("responseObject: " + responseObject.toString());
try {
status = responseObject.getString(Constants.SVC_STATUS);
return status;
} catch (JSONException e) {
e.printStackTrace();
}
}
if (responseObject.has(Constants.SVC_MSG)) {
try {
msg = responseObject.getString(Constants.SVC_MSG);
} catch (JSONException e) {
e.printStackTrace();
}
return status;
}
return "";
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final String success) {
super.onPostExecute(success);
if (success != null) {
System.out.println(Constants.STATUS_SUCCESS);
if (Constants.STATUS_SUCCESS.equals(success)) {
System.out.println("Successful Svc Call:"+ "post object task details called");
Toast.makeText(UploadDocumentActivity.this, "Successful Svc Call:"+ "post object task details called", Toast.LENGTH_LONG).show();
} else {
System.out.println(success);
try {
AlertDialog alertDialog = new AlertDialog.Builder(UploadDocumentActivity.this).create();
alertDialog.setTitle("Info");
alertDialog.setMessage(responseObject.getString(Constants.SVC_MSG));
alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
catch(Exception e)
{
UtilityServices.appendLog("Show Dialog: "+e.getMessage());
}
}
} else {
System.out.println("svcstatus is null");
}
}
}
}
This is my class and i am trying to capture an image on click a button and then save into directory after that show into imageview and then want to send to server,i hope you will help me as a best programmer.
this question may be a duplicate of this.
Basically, when you pass an OutPut file to the intent, you cannot read data from extra, you have to make sure that CameraApplication has access to your files. You are getting this exception, because CameraApplication cannot save the file on your directory, you need to add a file provider...
Please make your code is same as the base android documentation.
Try This
public void getFile(View view) {
if (ContextCompat.checkSelfPermission(UploadDocumentActivity.this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(UploadDocumentActivity.this,new String[]{Manifest.permission.CAMERA},
MY_CAMERA_PERMISSION_CODE);
} else {
Intent i=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File dir=
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
String pictureNm = getPictureName();
File output=new File(dir, pictureNm);
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(output));
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
}

How to limit the item of listview in arrayadapter and use LoadPrevious header for loading more items

My Activity
public class UserComments extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_comments);
lv= (ListView) findViewById(R.id.Listview_common);
realm=Realm.getDefaultInstance();
Button btnLoadMore = new Button(this);
btnLoadMore.setText("Load Previous");
lv.addHeaderView(btnLoadMore);
btnLoadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
realm = Realm.getDefaultInstance();
int position;
position = lv.getCheckedItemPosition();
position = position - 1;
lv.getItemAtPosition(position);
int last = lv.getLastVisiblePosition();
if (position == 1) {
System.out.println("previous is Impossilble");
setAdapter();
}
}
});
displayInputDialog();
imgattach=(ImageView) findViewById(R.id.imgattach);
imgattach.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectImage();
}
});
}
public void setAdapter()
{
lv= (ListView) findViewById(R.id.Listview_common);
final UserCommentRealmHelper helper=new UserCommentRealmHelper(realm);
helper.retrieveFromDB();
UserCommentArrayAdapter adapter=new UserCommentArrayAdapter(UserComments.this,helper.justRefresh());
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
realmChangeListener=new RealmChangeListener() {
#Override
public void onChange() {
UserCommentArrayAdapter adapter=new UserCommentArrayAdapter(UserComments.this,helper.justRefresh());
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
};
realm.addChangeListener(realmChangeListener);
}
public void displayInputDialog()
{
descEditTxt= (EditText) findViewById(R.id.editwrite);
ImageView fab = (ImageView) findViewById(R.id.send);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String desc = descEditTxt.getText().toString();
UserComment s = new UserComment();
s.setDescription(desc);
UserCommentRealmHelper helper = new UserCommentRealmHelper(realm);
if (helper.save(s)) {
descEditTxt.setText("");
setAdapter();
}
else {
Toast.makeText(UserComments.this, "Invalid Data", Toast.LENGTH_SHORT).show();
}
}
});
}
public void cameraIntent() {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
intent.putExtra("camera",REQUEST_CAMERA);
}
public void galleryIntent() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
}
public void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library","Camera Video","Gallery Video",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(UserComments.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result=Utility.checkPermission(UserComments.this);
if (items[item].equals("Take Photo")) {
userChoosenTask="Take Photo";
if(result)
cameraIntent();
} else if (items[item].equals("Choose from Library")) {
userChoosenTask="Choose from Library";
if(result)
galleryIntent();
}
else if (items[item].equals("Camera Video")) {
userChoosenTask="Camera Video";
if(result)
startRecording();
}
else if (items[item].equals("Gallery Video")) {
userChoosenTask="Gallery Video";
if(result)
CaptureVideoFromGallery();
}
else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
public void CaptureVideoFromGallery()
{
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Video"), SELECT_FILES);
}
public void startRecording()
{
java.util.Date date= new java.util.Date();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(date.getTime());
File mediaFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +"/"+timeStamp+".mp4");
/// File mediaFile = new File(Environment.getExternalStorageDirectory(),System.currentTimeMillis() + ".mp4");
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = Uri.fromFile(mediaFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, VIDEO_CAPTURE);
}
/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
// Check that the SDCard is mounted
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraVideo");
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraVideo", "Failed to create directory MyCameraVideo.");
return null;
}
}
// Create a media file name
// For unique file name appending current timeStamp with file name
java.util.Date date= new java.util.Date();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(date.getTime());
File mediaFile;
if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if(userChoosenTask.equals("Take Photo"))
cameraIntent();
else if(userChoosenTask.equals("Choose from Library"))
galleryIntent();
else if(userChoosenTask.equals("Video"))
startRecording();
} else {
}
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_FILE) {
onSelectFromGalleryResult(data);
}
else if (requestCode == REQUEST_CAMERA) {
onCaptureImageResult(data);
}
else if (requestCode == SELECT_FILES) {
onSelectFromGalleryVideoResults(data);
}
else if (requestCode == VIDEO_CAPTURE) {
Toast.makeText(this, "Video has been saved to:\n" + data.getData(), Toast.LENGTH_LONG).show();
SaveVideoData(String.valueOf(data.getData()));
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Video recording cancelled.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Failed to record video", Toast.LENGTH_LONG).show();
}
}
}
public void SaveVideoData(String data) {
try {
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
UserComment s = realm.createObject(UserComment.class);
s.setVideoUrl(data);
realm.commitTransaction();
realm.close();
UserCommentRealmHelper helper = new UserCommentRealmHelper(realm);
if (helper.save(s)) {
setAdapter();
}
else
{
Toast.makeText(UserComments.this, "Invalid Data", Toast.LENGTH_SHORT).show();
}
Log.d("path", data);
Log.d("working realm", "yes....");
Toast.makeText(getApplicationContext(),"Set Image URL"+data,Toast.LENGTH_LONG).show();
}
catch (Exception ex){
Toast.makeText(getApplicationContext(),"Nope its not done",Toast.LENGTH_LONG).show();
}
}
public String getRealPathFromURI(Uri contentUri) {
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
#SuppressWarnings("deprecation")
public void onSelectFromGalleryResult(Intent data) {
// Toast.makeText(UserComments.this,"My bm"+data,Toast.LENGTH_LONG).show();
SaveImageVideoData(String.valueOf(data.getData()),true);
}
#SuppressWarnings("deprecation")
public void onSelectFromGalleryVideoResults(Intent data) {
Toast.makeText(UserComments.this,"My bm"+data,Toast.LENGTH_LONG).show();
SaveVideoData(String.valueOf(data));
}
public void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.PNG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".png");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
//Toast.makeText(UserComments.this,"No Error",Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
//Toast.makeText(UserComments.this,"Error Arrived",Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
//Toast.makeText(UserComments.this,"Error Arrived again",Toast.LENGTH_LONG).show();
}
SaveImageVideoData(String.valueOf(destination),false);
//Toast.makeText(UserComments.this,"its done",Toast.LENGTH_LONG).show();
}
public void SaveImageVideoData(String data,boolean flag) {
try {
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
UserComment s = realm.createObject(UserComment.class);
s.setImageUrl(data);
s.setFlag(flag);
realm.commitTransaction();
realm.close();
UserCommentRealmHelper helper = new UserCommentRealmHelper(realm);
if (helper.save(s)) {
setAdapter();
}
else
{
Toast.makeText(UserComments.this, "Invalid Data", Toast.LENGTH_SHORT).show();
}
Log.d("path", data);
Log.d("working realm", "yes....");
Toast.makeText(getApplicationContext(),"Set Image URL"+data,Toast.LENGTH_LONG).show();
}
catch (Exception ex){
Toast.makeText(getApplicationContext(),"Nope its not done",Toast.LENGTH_LONG).show();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
realm.removeChangeListener(realmChangeListener);
realm.close();}
}
My Adapter Class
public class UserCommentArrayAdapter extends ArrayAdapter<UserComment> {
public UserCommentArrayAdapter(Context context, List<UserComment> objects){
super(context,0,objects);
this.context = context;
this.mInflater = LayoutInflater.from(context);
contactList = objects;
}
#Override
public UserComment getItem(int position) {
return contactList.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final UserCommentArrayAdapter.ViewHolder vh;
if (convertView == null) {
View view = mInflater.inflate(R.layout.item_commonchat, parent, false);
vh = UserCommentArrayAdapter.ViewHolder.create((LinearLayout) view);
view.setTag(vh);
} else {
vh = (UserCommentArrayAdapter.ViewHolder) convertView.getTag();
}
UserComment s = getItem(position);
if(s.getVideoUrl()!=null && s.getVideoUrl().length()>0)
{
Log.d("start error testing", "videooooooo");
vh.videoView.setVideoPath(s.getVideoUrl());
vh.videoView.setMediaController(new MediaController(context));
vh.videoView.start();
}
if(vh.txtbeencnt!=null) {
vh.txtbeencnt.setVisibility(View.VISIBLE);
vh.imageView.setVisibility(View.GONE);
vh.videoView.setVisibility(View.GONE);
vh.txtbeencnt.setText(s.getDescription());
}
if(s.getImageUrl() != null && s.getImageUrl().length()>0) {
boolean flag= s.isFlag();
if (flag == true) {
vh.imageView.setVisibility(View.VISIBLE);
vh.txtbeencnt.setVisibility(View.GONE);
vh.videoView.setVisibility(View.GONE);
Picasso.with(context).load(s.getImageUrl()).placeholder(R.mipmap.ic_launcher).into(vh.imageView);
Toast.makeText(context, "Got Gallery Image URL" + s.getImageUrl(), Toast.LENGTH_LONG).show();
} else if (flag == false) {
vh.imageView.setVisibility(View.VISIBLE);
vh.txtbeencnt.setVisibility(View.GONE);
vh.videoView.setVisibility(View.GONE);
Bitmap bitmap = BitmapFactory.decodeFile(s.getImageUrl());
vh.imageView.setImageBitmap(bitmap);
Toast.makeText(context, "Got Camera Image URL" + s.getImageUrl(), Toast.LENGTH_LONG).show();
}
}
return vh.rootView;
}
private static class ViewHolder {
public final LinearLayout rootView;
public final ImageView imageView;
public final TextView txtbeencnt;
public final VideoView videoView;
private ViewHolder(LinearLayout rootView,TextView txtbeencnt,ImageView imageView,VideoView videoView) {
this.rootView = rootView;
this.imageView = imageView;
this.txtbeencnt = txtbeencnt;
this.videoView=videoView;
}
public static UserCommentArrayAdapter.ViewHolder create(LinearLayout rootView) {
ImageView imageView = (ImageView) rootView.findViewById(R.id.img);
VideoView videoView = (VideoView) rootView.findViewById(R.id.videoView1);
TextView txtbeencnt = (TextView) rootView.findViewById(R.id.textdesc);
return new UserCommentArrayAdapter.ViewHolder(rootView,txtbeencnt,imageView,videoView);
}
}
}
Want the output like this
I searched a lot but everywhere found to use getcount() method which returns some specific integer value of item, but here I am not using custom adapter so what to do in this case?

Value of variable does not change instantly in activity

I am making a edit profile page , in which i display profile picture of the user the user can edit the profile picture . before clicking submit the i want to save the final updated url of profile picture . The problem is that if i change the profile picture and and instantly click on submit the value of variable storing the url doen not change but if i wait for few seconds it changes is there a way to get the value updated instantly.
**My edit profile class**
public class DocEditProfileInfo extends DocBaseActivity {
private static final String TAG =
private String profilePicUrl;
public String profilepicUrlComplete;
ArrayList<String> mImagesString = new ArrayList<>();
private ProgressBar imageProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ButterKnife.bind(this);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
imageProgressBar = (ProgressBar) findViewById(R.id.progress);
setUpRestAdapter();
setSalutation();
setDocPersonalDetails();
ImageView iv = (ImageView) findViewById(R.id.camera_new);
iv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setDialogForImage();
}
});
docSubmitInfo.setOnClickListener(this);
}
private void setDialogForImage() {
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.dialog_select_from_source);
Button btnCamera = (Button) dialog.findViewById(R.id.btnCamera);
Button btnDocs = (Button) dialog.findViewById(R.id.btnDoc);
btnDocs.setVisibility(View.INVISIBLE);
Button btnGallery = (Button) dialog.findViewById(R.id.btnGallery);
dialog.show();
btnCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
dialog.cancel();
}
});
btnGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, PICK_FROM_GALLERY);
dialog.cancel();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri mImageCaptureUri;
if (resultCode != RESULT_OK) {
return;
}
if (requestCode == 0 && resultCode == RESULT_OK) {
Bitmap bp = (Bitmap) data.getExtras().get("data");
// Uri selectedImageUri = data.getData();
// Glide.with(this).load(selectedImageUri).fitCenter().into(personImage);
personImage.setImageBitmap(getRoundedShape(bp));
// personImage.setImageBitmap(bp);
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
Uri tempUri = getImageUri(getApplicationContext(), bp);
// CALL THIS METHOD TO GET THE ACTUAL PATH
File filePath = new File(getRealPathFromURI(tempUri));
sendImagesToServerFromCamera(filePath.getPath());
} else if (requestCode == PICK_FROM_GALLERY && resultCode == RESULT_OK) {
/* Uri selectedImageUri = data.getData();
Log.e(TAG, "onActivityResult: URI " + selectedImageUri);
Glide.with(this).load(selectedImageUri).into(personImage);*/
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String imgDecodableString = cursor.getString(columnIndex);
cursor.close();
// Set the Image in ImageView after decoding the String
personImage.setImageBitmap(getRoundedShape(BitmapFactory
.decodeFile(imgDecodableString)));
sendImagesToServerFromCamera(imgDecodableString);
}
}
public Bitmap getRoundedShape(Bitmap scaleBitmapImage) {
*******
}
private String getRealPathFromURI(Uri tempUri) {
********
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
*********
}
private void sendImagesToServerFromCamera(String path) {
File imgPath = new File(path);
Log.e(TAG, "PATH " + path);
RequestBody requestFile =
RequestBody.create(MediaType.parse("image/jpg"), imgPath);
//For sending all types of images , presently only jpg allowed
// RequestBody fbody = RequestBody.create(MediaType.parse("image/*"), imgPath);
MultipartBody.Part body =
MultipartBody.Part.createFormData("file", imgPath.getName(), requestFile);
/* MultipartBody.Part body =
MultipartBody.Part.createFormData("file", imgPath.getName(), fbody);*/
Call<ProfilePicture> call = ProfilePicAdapter.sendProfilePic(body);
call.enqueue(new Callback<ProfilePicture>() {
#Override
public void onResponse(Call<ProfilePicture> call, Response<ProfilePicture> response) {
if (response.isSuccessful()) {
profilePicUrl = response.body().getUrl();
// profilepicUrlComplete = BASE_URL_FOR_IMAGE + profilePicUrl;
// String profilePicUrl = BASE_URL_FOR_IMAGE + profilePicUrl;
if (response.body().getUrl() != null) {
profilePicUrl = response.body().getUrl();
String profilePictureUrlComplete = BASE_URL_FOR_IMAGE + profilePicUrl;
setProfilePicURL(profilePictureUrlComplete);
}
} else {
Log.e(TAG, "UNSUCCESSFUL RESPONSE " + response.errorBody() + "*" + response.code());
}
}
#Override
public void onFailure(Call<ProfilePicture> call, Throwable t) {
Log.e(TAG, "onFailure: " + t.toString());
}
});
}
private void setProfilePicURL(String profilePictureUrlComplete) {
profilepicUrlComplete = profilePictureUrlComplete;
Log.e(TAG, "setProfilePicURL: " + profilePictureUrlComplete);
}
private void setDocPersonalDetails() {
*********
}
#Override
public void onClick(View v) {
if (isEditProfileValid()) {
Log.e(TAG, "onClick: PROFILE URL " + profilepicUrlComplete);
***docPersonalDetailsUpdate.setProfilePic(profilepicUrlComplete);***
Call<DoctorProfile> call = docPersonalDetailsUpdateAdapter.docEditPersonalDetails(docPersonalDetailsUpdate);
if (NetworkUtils.isNetworkConnected(this)) {
call.enqueue(new Callback<DoctorProfile>() {
#Override
public void onResponse(Call<DoctorProfile> call, Response<DoctorProfile> response) {
if (response.isSuccessful()) {
finish();
}
}
#Override
public void onFailure(Call<DoctorProfile> call, Throwable t) {
Log.e(TAG, "onFailure: ");
}
});
} else {
SnakBarUtils.networkConnected(this);
}
}

Getting user date from Facebook session ? - Android

I'm trying get name and email from a facebook session opened. I want to get these informations an add in a EditText. When I try get these informations the Facebook is opened to type my login and password to access after this doesn't return the informations.
How can I do it ?
I'm trying this.
public class CadUsuarioFrag extends Fragment implements View.OnClickListener, RadioGroup.OnCheckedChangeListener{
private EditText etNome, etEmail, etSenha;
private ImageButton ibImage;
private Button btnSingUp;
private String pathImage;
private static final int RESULT_LOAD_IMAGE = 1;
private ProgressDialog progress;
private final String TAG = getClass().getSimpleName() + "->";
//radiogroup
private RadioGroup rgTipoCad;
//
private String nome = "";
private String email = "";
private String senha = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((CustomDrawerLayout)getActivity()).getSupportActionBar().hide();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == getActivity().RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
pathImage = cursor.getString(columnIndex);
cursor.close();
}
Session.getActiveSession().onActivityResult(getActivity(), requestCode, resultCode, data);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.form_cadusuario, container, false);
etNome = (EditText)view.findViewById(R.id.etNome);
etEmail = (EditText)view.findViewById(R.id.etEmail);
etSenha = (EditText)view.findViewById(R.id.etSenha);
ibImage = (ImageButton)view.findViewById(R.id.ibImage);
btnSingUp = (Button)view.findViewById(R.id.btnSingUp);
rgTipoCad = (RadioGroup)view.findViewById(R.id.rgTipoCad);
//listeners
rgTipoCad.setOnCheckedChangeListener(this);
ibImage.setOnClickListener(this);
btnSingUp.setOnClickListener(this);
etNome.requestFocus();
return view;
}
#Override
public void onClick(View v) {
if(v == ibImage){
Intent i = new Intent(
Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}else if(v == btnSingUp){
if(checkFields()){
addUsuario();
}
}
}
/** verifica se todos os campos foram informados para o insert */
private boolean checkFields(){
nome = etNome.getText().toString().trim();
email = etEmail.getText().toString().trim();
senha = etSenha.getText().toString().trim();
int selected = rgTipoCad.getCheckedRadioButtonId();
if(nome.length() == 0 || email.length() == 0 || senha.length() == 0){
Toast.makeText(getView().getContext(), "Informe todos os campos", Toast.LENGTH_SHORT).show();
etNome.requestFocus();
etNome.selectAll();
return false;
}else{
return true;
}
}
private void addUsuario(){
progress = new CustomProgressDialog().getCustomProgress(null, getView().getContext());
progress.show();
Usuario u = new Usuario(nome, email, senha, "1");
JsonObjectRequest app = new UsuarioDAO().addUsuario(u, new UsuarioAdapter(){
#Override
public void onUsuarioCadastrado(Boolean value) {
if(!value){
Toast.makeText(getView().getContext(), "Usuário não cadastrado", Toast.LENGTH_SHORT).show();
}else{
sucesso();
}
progress.dismiss();
}
});
CustomVolleySingleton.getInstance(getView().getContext()).addToRequestQueue(app);
}
private void sucesso(){
AlertDialog.Builder alert = new AlertDialog.Builder(getView().getContext());
alert.setTitle("Guia Store");
alert.setMessage("Obrigado por se cadastrar\nEfetue agora seu login para acesso");
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
FragmentTransaction ft;
Fragment frag;
frag = new LoginFrag();
ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fl, frag, "InicioFrag");
ft.commit();
removeFrag();
}
});
AlertDialog dialog = alert.create();
dialog.show();
}
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(checkedId == R.id.rbGuiaStore){
//Log.i(TAG, "rbGuiaStore selecionado");
etNome.setHint("Nome");
etEmail.setHint("Email");
etSenha.setHint("Senha");
etNome.requestFocus();
}else{
//Log.i(TAG, "rbFacebook selecionado");
etNome.setHint("Nome");
etEmail.setHint("Email facebook");
etSenha.setHint("Senha facebook");
etNome.requestFocus();
checkFacebookSession();
}
}
private void checkFacebookSession(){
// start Facebook Login
Session.openActiveSession(getActivity(), true, new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
// make request to the /me API
Request.newMeRequest(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
Toast.makeText(getView().getContext(), user.getName(), Toast.LENGTH_SHORT).show();
etNome.setText(user.getName());
Log.i("usuario", user.getName());
}
}
}).executeAsync();
}
}
});
}
/** remove o fragment da fila */
private void removeFrag(){
getActivity().getSupportFragmentManager().popBackStack();
//getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onStop() {
super.onStop();
CustomVolleySingleton.getInstance(getView().getContext()).cancelPendingRequests(CustomVolleySingleton.TAG);
}
}
You can do something like below.
Request.newMeRequest(session, new Request.GraphUserCallback()
{
#Override
public void onCompleted(GraphUser user, Response response)
{
if (response != null)
{
try
{
String name = user.getName();
String email = (String) user.getProperty("email");
Log.e(LOG_TAG, "Name: " + name + " Email: " + email);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}).executeAsync();
P.S. Session should be opened before running this request. You can check sessionState through isOpened() method

Categories

Resources