Mapping listView items with photos from the cloud - android

I have some places in a listView. These are picked from a Google Map, for which I would like to take a picture. One for each. These photos should be available online, so I have searched for some proper solutions. I've choosed imgur's API.
Is it possible to link pictures with places? I would like to make mapping between uploaded pictures and listView items.
Photo picker and uploader class:
public class OAuthTestActivity extends Activity {
public static final int REQUEST_CODE_PICK_IMAGE = 1001;
private static final String AUTHORIZATION_URL = "https://api.imgur.com/oauth2/authorize";
private static final String CLIENT_ID = "CLIENT_ID";
private LinearLayout rootView;
private String accessToken;
private String refreshToken;
private String picturePath = "";
private Button send;
private String uploadedImageUrl = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rootView = new LinearLayout(this);
rootView.setOrientation(LinearLayout.VERTICAL);
TextView tv = new TextView(this);
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(llp);
rootView.addView(tv);
setContentView(rootView);
String action = getIntent().getAction();
if (action == null || !action.equals(Intent.ACTION_VIEW)) { // We need access token to use Imgur's api
tv.setText("Start OAuth Authorization");
Uri uri = Uri.parse(AUTHORIZATION_URL).buildUpon()
.appendQueryParameter("client_id", CLIENT_ID)
.appendQueryParameter("response_type", "token")
.appendQueryParameter("state", "init")
.build();
Intent intent = new Intent();
intent.setData(uri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
} else { // Now we have the token, can do the upload
tv.setText("Got Access Token");
Uri uri = getIntent().getData();
Log.d("Got imgur's access token", uri.toString());
String uriString = uri.toString();
String paramsString = "http://callback?" + uriString.substring(uriString.indexOf("#") + 1);
Log.d("tag", paramsString);
List<NameValuePair> params = URLEncodedUtils.parse(URI.create(paramsString), "utf-8");
Log.d("tag", Arrays.toString(params.toArray(new NameValuePair[0])));
for (NameValuePair pair : params) {
if (pair.getName().equals("access_token")) {
accessToken = pair.getValue();
} else if (pair.getName().equals("refresh_token")) {
refreshToken = pair.getValue();
}
}
Log.d("tag", "access_token = " + accessToken);
Log.d("tag", "refresh_token = " + refreshToken);
Button chooseImage = new Button(this);
rootView.addView(chooseImage);
chooseImage.setText("Choose an image");
chooseImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
}
});
send = new Button(this);
rootView.addView(send);
send.setText("send to imgur");
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (picturePath != null && picturePath.length() > 0 &&
accessToken != null && accessToken.length() > 0) {
(new UploadToImgurTask()).execute(picturePath);
}
}
});
}
}
#Override
protected void onResume() {
super.onResume();
if (send == null) return;
if (picturePath == null || picturePath.length() == 0) {
send.setVisibility(View.GONE);
} else {
send.setVisibility(View.VISIBLE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d("tag", "request code : " + requestCode + ", result code : " + resultCode);
if (data == null) {
Log.d("tag" , "data is null");
}
if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_PICK_IMAGE && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
Log.d("tag", "image path : " + picturePath);
cursor.close();
}
super.onActivityResult(requestCode, resultCode, data);
}
// Here is the upload task
class UploadToImgurTask extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
final String upload_to = "https://api.imgur.com/3/upload";
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(upload_to);
try {
HttpEntity entity = MultipartEntityBuilder.create()
.addPart("image", new FileBody(new File(params[0])))
.build();
httpPost.setHeader("Authorization", "Bearer " + accessToken);
httpPost.setEntity(entity);
final HttpResponse response = httpClient.execute(httpPost,
localContext);
final String response_string = EntityUtils.toString(response
.getEntity());
final JSONObject json = new JSONObject(response_string);
Log.d("tag", json.toString());
JSONObject data = json.optJSONObject("data");
uploadedImageUrl = data.optString("link");
Log.d("tag", "uploaded image url : " + uploadedImageUrl);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
if (aBoolean.booleanValue()) { // after sucessful uploading, show the image in web browser
Button openBrowser = new Button(OAuthTestActivity.this);
rootView.addView(openBrowser);
openBrowser.setText("Open Browser");
openBrowser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setData(Uri.parse(uploadedImageUrl));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
}
}
}

Related

My app crashes when linking to another page

Android app crashes when linking to another page
Every time I clicked on the button I created to go to the next Activity, the app crashes.
Here is the code I used:
public void openPictureCaptures(View view) {
Intent intent = new Intent(this, EventActivity.class);
this.startActivity ( intent );
}
The Activity I am linking to(EventActivity.class):
public class EventActivity extends Activity {
//public static final String KEY_MENU_TYPE = "menutype";
Button CaptureImageFromCamera,UploadImageToServer;
ImageView ImageViewHolder;
EditText imageName;
EditText detailText;
ProgressDialog progressDialog ;
Intent intent ;
public static final int RequestPermissionCode = 1 ;
Bitmap bitmap;
boolean check = true;
String GetImageNameFromEditText;
String GetImageDescFromEditText;
String ImageNameFieldOnServer = "event" ;
String ImageDescOnServer = "description";
String ImagePathFieldOnServer = "image" ;
//String menutype = "";
String ImageUploadPathOnSever ="http://getme.com/osunelection/capture_img_upload_to_server.php" ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event);
CaptureImageFromCamera = (Button)findViewById(R.id.button);
ImageViewHolder = (ImageView)findViewById(R.id.imageView);
UploadImageToServer = (Button) findViewById(R.id.button2);
imageName = (EditText)findViewById(R.id.editText);
detailText = (EditText) findViewById(R.id.detailText);
EnableRuntimePermissionToAccessCamera();
CaptureImageFromCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 7);
}
});
UploadImageToServer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
GetImageNameFromEditText = imageName.getText().toString();
GetImageDescFromEditText = detailText.getText().toString();
ImageUploadToServerFunction();
}
});
/* this.menutype = intent.getStringExtra(KEY_MENU_TYPE);
if (this.menutype == null) {
this.menutype = "";
}*/
}
// Star activity for result method to Set captured image on image view after click.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 7 && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
try {
// Adding captured image in bitmap.
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
// adding captured image in imageview.
ImageViewHolder.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Requesting runtime permission to access camera.
public void EnableRuntimePermissionToAccessCamera(){
if (ActivityCompat.shouldShowRequestPermissionRationale(EventActivity.this,
Manifest.permission.CAMERA))
{
// Printing toast message after enabling runtime permission.
Toast.makeText(EventActivity.this,"CAMERA permission allows us to Access CAMERA app", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(EventActivity.this,new String[]{Manifest.permission.CAMERA}, RequestPermissionCode);
}
}
// Upload captured image online on server function.
public void ImageUploadToServerFunction(){
ByteArrayOutputStream byteArrayOutputStreamObject ;
byteArrayOutputStreamObject = new ByteArrayOutputStream();
// Converting bitmap image to jpeg format, so by default image will upload in jpeg format.
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStreamObject);
byte[] byteArrayVar = byteArrayOutputStreamObject.toByteArray();
final String ConvertImage = Base64.encodeToString(byteArrayVar, Base64.DEFAULT);
class AsyncTaskUploadClass extends AsyncTask<Void,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog at image upload time.
progressDialog = ProgressDialog.show(EventActivity.this,"Image is Uploading","Please Wait",
false,false);
}
#Override
protected void onPostExecute(String string1) {
super.onPostExecute(string1);
// Dismiss the progress dialog after done uploading.
progressDialog.dismiss();
// Printing uploading success message coming from server on android app.
Toast.makeText(EventActivity.this,string1,Toast.LENGTH_LONG).show();
// Setting image as transparent after done uploading.
ImageViewHolder.setImageResource(android.R.color.transparent);
}
#Override
protected String doInBackground(Void... params) {
ImageProcessClass imageProcessClass = new ImageProcessClass();
HashMap<String,String> HashMapParams = new HashMap<String,String>();
HashMapParams.put(ImageNameFieldOnServer, GetImageNameFromEditText);
HashMapParams.put(ImageDescOnServer, GetImageDescFromEditText);
HashMapParams.put(ImagePathFieldOnServer, ConvertImage);
String FinalData = imageProcessClass.ImageHttpRequest(ImageUploadPathOnSever, HashMapParams);
return FinalData;
}
}
AsyncTaskUploadClass AsyncTaskUploadClassOBJ = new AsyncTaskUploadClass();
AsyncTaskUploadClassOBJ.execute();
}
public void goBack(View view) {
Intent intent = new Intent(this, IncidentMenuActivity.class);
startActivity(intent);
}
public class ImageProcessClass{
public String ImageHttpRequest(String requestURL,HashMap<String, String> PData) {
StringBuilder stringBuilder = new StringBuilder();
try {
URL url;
HttpURLConnection httpURLConnectionObject ;
OutputStream OutPutStream;
BufferedWriter bufferedWriterObject ;
BufferedReader bufferedReaderObject ;
int RC ;
url = new URL(requestURL);
httpURLConnectionObject = (HttpURLConnection) url.openConnection();
httpURLConnectionObject.setReadTimeout(19000);
httpURLConnectionObject.setConnectTimeout(19000);
httpURLConnectionObject.setRequestMethod("POST");
httpURLConnectionObject.setDoInput(true);
httpURLConnectionObject.setDoOutput(true);
OutPutStream = httpURLConnectionObject.getOutputStream();
bufferedWriterObject = new BufferedWriter(
new OutputStreamWriter(OutPutStream, "UTF-8"));
bufferedWriterObject.write(bufferedWriterDataFN(PData));
bufferedWriterObject.flush();
bufferedWriterObject.close();
OutPutStream.close();
RC = httpURLConnectionObject.getResponseCode();
if (RC == HttpsURLConnection.HTTP_OK) {
bufferedReaderObject = new BufferedReader(new InputStreamReader(httpURLConnectionObject.getInputStream()));
stringBuilder = new StringBuilder();
String RC2;
while ((RC2 = bufferedReaderObject.readLine()) != null){
stringBuilder.append(RC2);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
private String bufferedWriterDataFN(HashMap<String, String> HashMapParams) throws UnsupportedEncodingException {
StringBuilder stringBuilderObject;
stringBuilderObject = new StringBuilder();
for (Map.Entry<String, String> KEY : HashMapParams.entrySet()) {
if (check)
check = false;
else
stringBuilderObject.append("&");
stringBuilderObject.append(URLEncoder.encode(KEY.getKey(), "UTF-8"));
stringBuilderObject.append("=");
stringBuilderObject.append(URLEncoder.encode(KEY.getValue(), "UTF-8"));
}
return stringBuilderObject.toString();
}
}
#Override
public void onRequestPermissionsResult(int RC, String per[], int[] PResult) {
switch (RC) {
case RequestPermissionCode:
if (PResult.length > 0 && PResult[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(EventActivity.this,"Permission Granted, Now your application can access CAMERA.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(EventActivity.this,"Permission Canceled, Now your application cannot access CAMERA.", Toast.LENGTH_LONG).show();
}
break;
}
}
}
Is there something I am doing wrong that might of caused it? I have made some research online and this is the same method most of them used.

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);
}
}

Android payapal integration

this is my first question on stackoverflow.hope i can find my solutuon .i am integrating paypal in android.my device is showing "payment of this marchent are not allowed(invalid client id).here is my code
private static final String CONFIG_ENVIRONMENT = PayPalConfiguration.ENVIRONMENT_PRODUCTION;
// note that these credentials will differ between live & sandbox
// environments.
private static final String CONFIG_CLIENT_ID ="my client id";
private static final int REQUEST_CODE_PAYMENT = 1;
private static final int REQUEST_CODE_FUTURE_PAYMENT = 2;
private static PayPalConfiguration config = new PayPalConfiguration()
.environment(CONFIG_ENVIRONMENT)
.clientId(CONFIG_CLIENT_ID)
// The following are only used in PayPalFuturePaymentActivity.
.merchantName("Rajeev Lochan Sharma")
.merchantPrivacyPolicyUri(
Uri.parse("https://www.example.com/privacy"))
.merchantUserAgreementUri(
Uri.parse("https://www.example.com/legal"));
PayPalPayment thingToBuy;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_afcl);
final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
Intent intent = new Intent(this, PayPalService.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startService(intent);
ButterKnife.inject(this);
_request3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// signup();
new Test().execute(_names.getText().toString(), _placeofbirth.getText().toString(), _timeofbirth.getText().toString()
);
thingToBuy = new PayPalPayment(new BigDecimal("10"), "USD",
"quote", PayPalPayment.PAYMENT_INTENT_SALE);
Intent intent = new Intent(AfcRequest1Activity.this,
PaymentActivity.class);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivityForResult(intent, REQUEST_CODE_PAYMENT);
}
});
}
public void onBackPressed() {
new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Exit")
.setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
}).setNegativeButton("No", null).show();
}
private class Test extends AsyncTask {
protected void onPreExecute() {
super.onPreExecute();
//here you can some progress dialog or some view
}
#Override
protected String doInBackground(String... Params) {
String res = "";
try {
byte[] result = null;
String str = "";
HttpClient client;
HttpPost post;
ArrayList<NameValuePair> nameValuePair;
HashMap<String, String> mData;
Iterator<String> it;
HttpResponse response;
StatusLine statusLine;
//here is url api call url
post = new HttpPost("http://astro360horoscope.com/backend/api/form_amc_afc.php");
nameValuePair = new ArrayList<NameValuePair>();
mData = new HashMap<String, String>();
mData.put("username", Params[0]);
mData.put("placeofbirth", Params[1]);
mData.put("timeofbirth", Params[2]);
//for now nothing is there
it = mData.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
nameValuePair.add(new BasicNameValuePair(key, mData.get(key)));
}
post.setEntity(new UrlEncodedFormEntity(nameValuePair, "utf-8"));
client = new DefaultHttpClient();
response = client.execute(post);
statusLine = response.getStatusLine();
result = EntityUtils.toByteArray(response.getEntity());
str = new String(result, "utf-8");
if (statusLine.getStatusCode() == HttpURLConnection.HTTP_OK) {
//here we get the response if all is correct
res = str;
} else {
res = str;
return res;
}
} catch (Exception e1) {
res = "error:" + e1.getMessage().toString();
e1.printStackTrace();
}
return res;
}
protected void onPostExecute(String response) {
super.onPostExecute(response);
}
}
public void onFuturePaymentPressed(View pressed) {
Intent intent = new Intent(AfcRequest1Activity.this,
PayPalFuturePaymentActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivityForResult(intent, REQUEST_CODE_FUTURE_PAYMENT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_PAYMENT) {
if (resultCode == Activity.RESULT_OK) {
PaymentConfirmation confirm = data
.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirm != null) {
try {
System.out.println(confirm.toJSONObject().toString(4));
System.out.println(confirm.getPayment().toJSONObject()
.toString(4));
Toast.makeText(getApplicationContext(), "Order placed",
Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
System.out.println("The user canceled.");
} else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
System.out
.println("An invalid Payment or PayPalConfiguration was submitted. Please see the docs.");
}
} else if (requestCode == REQUEST_CODE_FUTURE_PAYMENT) {
if (resultCode == Activity.RESULT_OK) {
PayPalAuthorization auth = data
.getParcelableExtra(PayPalFuturePaymentActivity.EXTRA_RESULT_AUTHORIZATION);
if (auth != null) {
try {
Log.i("FuturePaymentExample", auth.toJSONObject()
.toString(4));
String authorization_code = auth.getAuthorizationCode();
Log.i("FuturePaymentExample", authorization_code);
sendAuthorizationToServer(auth);
Toast.makeText(getApplicationContext(),
"Future Payment code received from PayPal",
Toast.LENGTH_LONG).show();
} catch (JSONException e) {
Log.e("FuturePaymentExample",
"an extremely unlikely failure occurred: ", e);
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.i("FuturePaymentExample", "The user canceled.");
} else if (resultCode == PayPalFuturePaymentActivity.RESULT_EXTRAS_INVALID) {
Log.i("FuturePaymentExample",
"Probably the attempt to previously start the PayPalService had an invalid PayPalConfiguration. Please see the docs.");
}
}
}
private void sendAuthorizationToServer(PayPalAuthorization authorization) {
}
public void onFuturePaymentPurchasePressed(View pressed) {
// Get the Application Correlation ID from the SDK
String correlationId = PayPalConfiguration
.getApplicationCorrelationId(this);
Log.i("FuturePaymentExample", "Application Correlation ID: "
+ correlationId);
// TODO: Send correlationId and transaction details to your server for
// processing with
// PayPal...
Toast.makeText(getApplicationContext(),
"App Correlation ID received from SDK", Toast.LENGTH_LONG)
.show();
}
#Override
public void onDestroy() {
// Stop service when done
stopService(new Intent(this, PayPalService.class));
super.onDestroy();
}

Android Fabric Twitter share listener

I use Fabric SDK to send tweets from my application.
I build a share dialog and send tweet from activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TwitterAuthConfig authConfig = new TwitterAuthConfig(CONSUMER_KEY, CONSUMER_SECRET);
Fabric.with(this, new TwitterCore(authConfig), new TweetComposer());
Bundle bundle = getIntent().getExtras().getBundle(SHARE_DATA);
String description = bundle.getString(SHARE_DESCRIPTION);
String title = bundle.getString(SHARE_TITLE);
String picture = bundle.getString(SHARE_PICTURE_LINK);
String link = bundle.getString(SHARE_LINK);
TweetComposer.Builder builder = null;
try {
InputStream in = new java.net.URL(picture).openStream();
Bitmap bitmap = BitmapFactory.decodeStream(in);
Uri yourUri = getImageUri(this,bitmap);
builder = new TweetComposer.Builder(this)
.text(title + "\n" + description)
.url(new URL(link))
.image(yourUri);
//??? IS THERE ANY LISTENER ???
builder.show();
} catch (IOException e1) {
e1.printStackTrace();
}
}
I want to know status of sharing, like an success or not, but i can't find any listener for this action. I missed something?
Instead of use builder.show(), you should use builder.createIntent() :
Intent intent = new TweetComposer.Builder(getActivity())
.text("TEXT")
.url("URL")
.createIntent();
startActivityForResult(intent, TWEET_COMPOSER_REQUEST_CODE);
To get the result feedback in onActivityResult() :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == TWEET_COMPOSER_REQUEST_CODE) {
if(resultCode == Activity.RESULT_OK) {
onTwitterSuccess();
} else if(resultCode == Activity.RESULT_CANCELED) {
onTwitterCancel();
}
}
}
use below method to twitt via rest service and pass media id as null.i m successfully posting tweets from my app
public void postToTwitter(ArrayList<String>mediaIds) {
String message;
if(Validator.isNotNull(preferences.getFbShareMessage())){
message=preferences.getFbShareMessage()+" "+com.aimdek.healthwel.network.Request.HOST_URL + "/user-history/" + userHistory.getUserId() + "/" + userHistory.getId();
}
else {
message = getString(R.string.google_status, HWUtil.getFullName(preferences.getUserInfo().getFirstName(), preferences.getUserInfo().getLastName()), userHistory.getSportName(), HWUtil.secondToTime(userHistory.getDuration()))+" "+com.aimdek.healthwel.network.Request.HOST_URL + "/user-history/" + userHistory.getUserId() + "/" + userHistory.getId();
}
String mediaId;
if (Validator.isNotNull(mediaIds) && mediaIds.size() > 0) {
mediaId="";
for (int i = 0; i < mediaIds.size(); i++) {
if (i == 0) {
mediaId = mediaIds.get(i);
} else {
mediaId += "," + mediaIds.get(i);
}
}
}
else {
mediaId=null;
}
StatusesService statusesService = twitterApiClient.getStatusesService();
statusesService.update(message, null, null, null, null, null, null, null, mediaId, new Callback<Tweet>() {
#Override
public void success(Result<Tweet> result) {
dismissProgressDialog();
if(Validator.isNotNull(preferences.getImagePath()) && !preferences.getImagePath().isEmpty()) {
preferences.getImagePath().clear();
}
com.aimdek.healthwel.network.Request.getRequest().sendRequest(com.aimdek.healthwel.network.Request.SHARE_USER_HISTORY, TwitterIntegration.this, TwitterIntegration.this, RequestParameterBuilder.buildMapForShareUserHistory(userHistory.getId(), TwitterIntegration.this));
}
#Override
public void failure(TwitterException exception) {
if(Validator.isNotNull(preferences.getImagePath()) && !preferences.getImagePath().isEmpty()) {
preferences.getImagePath().clear();
}
dismissProgressDialog();
finish();
HWUtil.showToast(TwitterIntegration.this,exception.getMessage());
}
});
}

How to set an image on imageView from the gallery and image taken by camera in Android?

In my app I want to set an image on a ImageView from gallery and I want to set an image which is taken by the camera. I have tried this code, when I load image from the gallery, it is working. But when I try to take a picture to set on ImageView, that activity is loaded but the image is not showing in the ImageView. Any solution for this? Here is my code:
First Activity
public class MainActivity extends ActionBarActivity {
private static int RESULT_LOAD_IMAGE = 1;
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
Bitmap photo;
String picturePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
// this.imageView = (ImageView)this.findViewById(R.id.imgView);
Button photoButton = (Button) this.findViewById(R.id.button2);
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
int flagval = 1;
/* ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));*/
sendImage(flagval);
}
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
/* photo = (Bitmap) data.getExtras().get("data");
//imageView.setImageBitmap(photo);
int flagvalt=2;
try {
sendImage(flagvalt);
}
catch (Exception e){
Toast.makeText(MainActivity.this, "Method error", Toast.LENGTH_SHORT).show();
}*/
try {
loadCamPic();
Toast.makeText(MainActivity.this, "Method invoked", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(MainActivity.this, "Method error", Toast.LENGTH_SHORT).show();
}
}
}
public void sendImage(int flag) {
if (flag == 1) {
Toast.makeText(MainActivity.this, "Loc:" + picturePath, Toast.LENGTH_SHORT).show();
Intent myIntent1 = new Intent(MainActivity.this, ImageUploadActivity.class);
myIntent1.putExtra("key", picturePath);
MainActivity.this.startActivity(myIntent1);
}
/*else if(flag==2) {
Intent intent = new Intent(MainActivity.this, ImageUploadActivity.class);
intent.putExtra("BitmapImage", photo);
}*/
}
void loadCamPic() {
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String pathName = baseDir + "/DCIM/CAMERA";
File parentDir = new File(pathName);
File[] files = parentDir.listFiles();
Date lastDate = null;
String lastFileName;
boolean isFirstFile = true;
for (File file : files) {
if (isFirstFile) {
lastDate = new Date(file.lastModified());
isFirstFile = false;
}
if (file.getName().endsWith(".jpg") || file.getName().endsWith(".jpeg")) {
Date lastModDate = new Date(file.lastModified());
if (lastModDate.after(lastDate)) {
lastDate = lastModDate;
lastFileName = file.getName();
String pathName2 = pathName + lastFileName;
// Log.e(TAG, "Method invoked");
Intent intent = new Intent(MainActivity.this, ImageUploadActivity.class);
Bundle extras = new Bundle();
extras.putString("FILE_PATH", pathName2);
extras.putString("FILE_NAME", lastFileName);
intent.putExtras(extras);
MainActivity.this.startActivity(intent);
}
}
}
}
}
Second Activity
public class ImageUploadActivity extends ActionBarActivity {
private Button upload;
private Bitmap bitmap;
private ProgressDialog dialog;
String picturePath;
String filename;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_upload);
//Image from sdcard
Intent intent1 = getIntent();
picturePath = intent1.getExtras().getString("key");
imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
bitmap = (BitmapFactory.decodeFile(picturePath));
//Camera Image
/* Intent intent = getIntent();
bitmap = (Bitmap) intent.getParcelableExtra("BitmapImage");
imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(bitmap);*/
if (picturePath == null) {
Intent intent = getIntent();
Bundle extras = intent.getExtras();
filename = extras.getString("FILE_NAME");
String filepath = extras.getString("FILE_PATH");
Toast.makeText(ImageUploadActivity.this, "Success:" + filepath, Toast.LENGTH_SHORT).show();
imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(filepath));
bitmap = (BitmapFactory.decodeFile(filepath));
}
upload = (Button) findViewById(R.id.upload);
upload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (bitmap == null) {
Toast.makeText(getApplicationContext(),
"Please select image", Toast.LENGTH_SHORT).show();
} else {
dialog = ProgressDialog.show(ImageUploadActivity.this, "Uploading",
"Please wait...", true);
new ImageUploadTask().execute();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_image_upload, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
class ImageUploadTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... unsued) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost("http://10.10.10.15/test/upload.php");
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
/* entity.addPart("uploaded_file", new ByteArrayBody(data,
"myImage.jpg"));*/
// String newFilename= filename.concat("file");
// newFilename=filename+newFilename;
entity.addPart("uploaded_file", new ByteArrayBody(data,
filename));
// Log.e(TAG, "Method invoked");
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost,
localContext);
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
String aux = "";
while ((aux = reader.readLine()) != null) {
builder.append(aux);
}
String sResponse = builder.toString();
return sResponse;
} catch (Exception e) {
if (dialog.isShowing())
dialog.dismiss();
Toast.makeText(getApplicationContext(), "Exception Message 1", Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
return null;
}
// (null);
}
#Override
protected void onProgressUpdate(Void... unsued) {
}
#Override
protected void onPostExecute(String sResponse) {
try {
if (dialog.isShowing())
dialog.dismiss();
if (sResponse != null) {
Toast.makeText(getApplicationContext(),
"Photo uploaded successfully",
Toast.LENGTH_SHORT).show();
Log.e("Response", sResponse);
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"Exception Message",
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
}
}
Take a look at the selected as best answer here Take photo w/ camera intent and display in imageView or textView? and you could find out how to take a picture and set it as a background of an imageView programmatically

Categories

Resources