i want to send image and some data using volley in android - 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!

Related

Select Multiple Images and Display in Multiple ImageView

I want to select 4 images from phone gallery and display them in 4 imageviews, so far below code is working fine by selecting 4 buttons individually.
Now i want to implement to select 4 images with 1 button and get them displayed in 4 imageview simulatenously, i am stuck here and have done many google search and found a solution by using getClipData below but after many trial and error still not working, can someone enlighthen me and appreicate your help.
if(data.getClipData() != null) {
int count = data.getClipData().getItemCount(); //evaluate the count before the for loop --- otherwise, the count is evaluated every loop.
for(int i = 0; i < count; i++) {
// Uri filepath = data.getClipData().getItemAt(i).getUri();
}
//do something with the image (save it to some directory or whatever you need to do with it here)
}
} else if(data.getData() != null) {
String imagePath = data.getData().getPath();
//do something with the image (save it to some directory or whatever you need to do with it here)
MainActivity.java code:
public class MainActivity extends AppCompatActivity
{
EditText t1,t2;
// TextView tv_upload1;
Button browse,browse_two,browse_three,browse_four,upload;
ImageView img, img_two,img_three,img_four;
Bitmap bitmap,bitmap_two,bitmap_three,bitmap_four;
String encodeImageString,encodeImageString_two,encodeImageString_three,encodeImageString_four;
private static final String url="http://example.com/fileupload.php";
ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button openActivityBtn = findViewById(R.id.openActivityBtn);
img = (ImageView) findViewById(R.id.img);
img_two = (ImageView) findViewById(R.id.img_two);
img_three = (ImageView) findViewById(R.id.img_three);
img_four = (ImageView) findViewById(R.id.img_four);
upload = (Button) findViewById(R.id.upload);
browse = (Button) findViewById(R.id.browse);
browse_two = (Button) findViewById(R.id.browse_two);
browse_three = (Button) findViewById(R.id.browse_three);
browse_four = (Button) findViewById(R.id.browse_four);
browse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Dexter.withActivity(MainActivity.this)
.withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
Intent intent = new Intent(Intent.ACTION_PICK);
// intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Browse Image"), 1);
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) {
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
token.continuePermissionRequest();
}
}).check();
}
});
//-----brose2
browse_two.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Dexter.withActivity(MainActivity.this)
.withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
Intent intent = new Intent(Intent.ACTION_PICK);
// intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Browse Image"), 2);
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) {
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
token.continuePermissionRequest();
}
}).check();
}
});
//-----browse3
browse_three.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Dexter.withActivity(MainActivity.this)
.withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
Intent intent = new Intent(Intent.ACTION_PICK);
// intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Browse Image"), 3);
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) {
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
token.continuePermissionRequest();
}
}).check();
}
});
//-----browse4
browse_four.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Dexter.withActivity(MainActivity.this)
.withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
Intent intent = new Intent(Intent.ACTION_PICK);
// intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Browse Image"), 4);
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) {
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
token.continuePermissionRequest();
}
}).check();
}
});
upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText firstName = (EditText) findViewById(R.id.t1);
// if (firstName.getText().toString().length() != 0);
// firstName.setError("Dealer name is required!");
EditText fivecode = (EditText) findViewById(R.id.t2);
// if (fivecode.getText().toString().length() != 12)
// fivecode.setError("12 digit 5+5 dealer code is required!");
//--------progressbar start
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
// mProgressDialog.setMessage(getString(R.string.progress_detail));
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.setProgress(0);
mProgressDialog.setTitle("UPLOAD STATUS");
mProgressDialog.setMessage("Your photos are being uploaded...");
mProgressDialog.setProgressNumberFormat(null);
mProgressDialog.setProgressPercentFormat(null);
mProgressDialog.show();
//---------progressbar end
uploaddatatodb();
return;
}
});
//-----------------view button
openActivityBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(MainActivity.this,ItemsActivity.class);
startActivity(intent);
// mProgressDialog.show();
}
});
//-----------------view button
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data)
{
if (requestCode == 1 && resultCode == RESULT_OK) {
if(data.getClipData() != null) {
int count = data.getClipData().getItemCount(); //evaluate the count before the for loop --- otherwise, the count is evaluated every loop.
for(int i = 0; i < count; i++) {
// Uri filepath = data.getClipData().getItemAt(i).getUri();
}
//do something with the image (save it to some directory or whatever you need to do with it here)
}
} else if(data.getData() != null) {
String imagePath = data.getData().getPath();
//do something with the image (save it to some directory or whatever you need to do with it here)
// Uri filepath = data.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(imagePath);
bitmap = BitmapFactory.decodeStream(inputStream);
img.setImageBitmap(bitmap);
encodeBitmapImage(bitmap);
} catch (Exception ex) {
}
}
//start
if (requestCode == 2 && resultCode == RESULT_OK) {
Uri filepath = data.getData();
try {
InputStream inputStream_two = getContentResolver().openInputStream(filepath);//two
bitmap_two = BitmapFactory.decodeStream(inputStream_two); //two
img_two.setImageBitmap(bitmap_two);
encodeBitmapImage_two(bitmap_two);
} catch (Exception ex) {
}
}//end
//start 3
if (requestCode == 3 && resultCode == RESULT_OK) {
Uri filepath = data.getData();
try {
InputStream inputStream_three = getContentResolver().openInputStream(filepath);//two
bitmap_three = BitmapFactory.decodeStream(inputStream_three); //two
img_three.setImageBitmap(bitmap_three);
encodeBitmapImage_three(bitmap_three);
} catch (Exception ex) {
}
}//end 3
//start 4
if (requestCode == 4 && resultCode == RESULT_OK) {
Uri filepath = data.getData();
try {
InputStream inputStream_four = getContentResolver().openInputStream(filepath);//two
bitmap_four = BitmapFactory.decodeStream(inputStream_four); //two
img_four.setImageBitmap(bitmap_four);
encodeBitmapImage_four(bitmap_four);
} catch (Exception ex) {
}
}//end 4
super.onActivityResult(requestCode, resultCode, data);
}
private void encodeBitmapImage(Bitmap bitmap)
{
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,30,byteArrayOutputStream);
byte[] bytesofimage=byteArrayOutputStream.toByteArray();
encodeImageString=android.util.Base64.encodeToString(bytesofimage, Base64.DEFAULT);
// encodeImageString_two=android.util.Base64.encodeToString(bytesofimage, Base64.DEFAULT);
}
private void encodeBitmapImage_two(Bitmap bitmap)
{
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,30,byteArrayOutputStream);
byte[] bytesofimage=byteArrayOutputStream.toByteArray();
// encodeImageString=android.util.Base64.encodeToString(bytesofimage, Base64.DEFAULT);
encodeImageString_two=android.util.Base64.encodeToString(bytesofimage, Base64.DEFAULT);
}
private void encodeBitmapImage_three(Bitmap bitmap)
{
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,30,byteArrayOutputStream);
byte[] bytesofimage=byteArrayOutputStream.toByteArray();
// encodeImageString=android.util.Base64.encodeToString(bytesofimage, Base64.DEFAULT);
encodeImageString_three=android.util.Base64.encodeToString(bytesofimage, Base64.DEFAULT);
}
private void encodeBitmapImage_four(Bitmap bitmap)
{
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,30,byteArrayOutputStream);
byte[] bytesofimage=byteArrayOutputStream.toByteArray();
// encodeImageString=android.util.Base64.encodeToString(bytesofimage, Base64.DEFAULT);
encodeImageString_four=android.util.Base64.encodeToString(bytesofimage, Base64.DEFAULT);
}
//-------------------refresh page after uploaded--------------
public void checkStartOtherActivity(){
// Intent i=new Intent(this, MainActivity.class);
// i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// startActivity(i);
Intent i = new Intent(this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
}
private void uploaddatatodb() {
t1 = (EditText) findViewById(R.id.t1);
t2 = (EditText) findViewById(R.id.t2);
final String name = t1.getText().toString().trim();
final String dsg = t2.getText().toString().trim();
// tv_upload1 = (TextView) findViewById(R.id.tv_upload1);
//-----------------------------check imageview got inserted photos?----------
if (img.getDrawable().getConstantState() == getResources().getDrawable(R.drawable.uploadimg).getConstantState()
| img_two.getDrawable().getConstantState() == getResources().getDrawable(R.drawable.uploadimg_two).getConstantState()
| img_three.getDrawable().getConstantState() == getResources().getDrawable(R.drawable.uploadimg_three).getConstantState()
| img_four.getDrawable().getConstantState() == getResources().getDrawable(R.drawable.uploadimg_four).getConstantState()
)
{
Toast.makeText(MainActivity.this,"There are no photos inserted",
Toast.LENGTH_SHORT).show();
mProgressDialog.dismiss();
}
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
mProgressDialog.show();
// t1.setText("");
// t2.setText("");
// img.setImageResource(R.drawable.uploadimg);
// img_two.setImageResource(R.drawable.uploadimg_two);
// img_three.setImageResource(R.drawable.uploadimg_three);
// img_four.setImageResource(R.drawable.uploadimg_four);
startActivity(new Intent(getApplicationContext(),MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION|Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK));
mProgressDialog.dismiss();
Toast.makeText(MainActivity.this,"Photos uploaded successfully",
Toast.LENGTH_SHORT).show();
// img.setImageResource(R.drawable.uploadimg);
// img_two.setImageResource(R.drawable.uploadimg_two);
// img_three.setImageResource(R.drawable.uploadimg_three);
// img_four.setImageResource(R.drawable.uploadimg_four);
//---------------------without refresh page-------------------
finish();
overridePendingTransition( 0, 0);
startActivity(getIntent());
overridePendingTransition( 0, 0);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mProgressDialog.dismiss();
Toast.makeText(MainActivity.this,"Please insert all photos",
Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<String, String>();
map.put("t1", name);
map.put("t2", dsg);
map.put("upload", encodeImageString);
map.put("upload_two", encodeImageString_two);
map.put("upload_three", encodeImageString_three);
map.put("upload_four", encodeImageString_four);
return map;
}
};
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
queue.add(request);
}
}
You can do it in the following way . I have used viewBinding in this project and have used the new activity contracts for getting images since startActivity is deprecated .The code is as follows .
public class MainActivity extends AppCompatActivity {
//Getting the binding
ActivityMainBinding binding;
//Defining a contract and assiging it to imageView
ActivityResultLauncher<String> mGetMultipleContent = registerForActivityResult(new ActivityResultContracts.GetMultipleContents(),
new ActivityResultCallback<List<Uri>>() {
#Override
public void onActivityResult(List<Uri> result) {
for (int i = 0; i < result.size(); i++) {
binding.imgone.setImageURI(result.get(0));
binding.imgtwo.setImageURI(result.get(1));
binding.imgthree.setImageURI(result.get(2));
binding.imgfour.setImageURI(result.get(3));
}
}
});
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
//Launching contract for getting images
binding.addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mGetMultipleContent.launch("image/*");
}
});
}
}
Use this xml layout for the above code :
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="#+id/imgone"
android:layout_width="match_parent"
android:layout_height="150dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/imgtwo"
android:layout_width="match_parent"
android:layout_height="150dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/imgone" />
<ImageView
android:id="#+id/imgthree"
android:layout_width="match_parent"
android:layout_height="150dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/imgtwo" />
<ImageView
android:id="#+id/imgfour"
android:layout_width="match_parent"
android:layout_height="150dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/imgthree" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/addButton"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="20dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Android: Reload method in main activity when method in second activity executes successfully and closes

I am trying to build an app that enables you to change your profile picture. When the app opens for the first time, it contains a Networkimageview for the current profile pic and a button to change the picture. When the button is pressed a new Activity is started that enables one to choose an image from the gallery and upload to a server.
When the upload is done, the new Activity is closed and the app returns to the MainActivity. How can I make the MainActivity to reload the image just uploaded to the server when the image uploads successfully from the new activity and closes? This is my code
Here's the MainActivity.java
public class MainActivity extends AppCompatActivity {
ImageLoader mImageLoader;
NetworkImageView mNetworkImageView;
private Button buttonChoose;
static final int PROFILE_PICTURE_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonChoose = (Button) findViewById(R.id.buttonChoose);
mNetworkImageView = (NetworkImageView) findViewById(R.id.networkImageView);
loadImage();
}
private String url = "http://10.0.2.2/images/0.jpg";
private void loadImage() {
mImageLoader = CustomVolleyRequest.getInstance(this).getImageLoader();
mNetworkImageView.setImageUrl(url, mImageLoader);
}
public void newActivity(View view) {
Intent profileIntent = new Intent(this, Activity2.class);
startActivityForResult(profileIntent, PROFILE_PICTURE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PROFILE_PICTURE_REQUEST) {
if (resultCode == RESULT_OK) {
loadImage();
}
}
}
}
The second activity Activity2.java
public class Activity2 extends AppCompatActivity implements View.OnClickListener {
private Bitmap bitmap;
private ImageView imageView;
private int PICK_IMAGE_REQUEST = 1;
private String UPLOAD_URL ="http://10.0.2.2/uploadd.php";
private String KEY_IMAGE = "image";
private Button buttonUpload;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
imageView = (ImageView) findViewById(R.id.imageView);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
buttonUpload.setOnClickListener(this);
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
public String getStringImage(Bitmap bmp) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
public void uploadImage() {
//Showing the progress dialog
final ProgressDialog loading = ProgressDialog.show(this, "Uploading...", "Please wait...", false, false);
StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
loading.dismiss();
Toast.makeText(Activity2.this, s, Toast.LENGTH_LONG).show();
Intent returnIntent = new Intent();
setResult(RESULT_OK,returnIntent);
finish();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
//Dismissing the progress dialog
loading.dismiss();
//Showing toast
Toast.makeText(Activity2.this, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Converting Bitmap to String
String image = getStringImage(bitmap);
//Creating parameters
Map<String, String> params = new Hashtable<String, String>();
//Adding parameters
params.put(KEY_IMAGE, image);
//returning parameters
return params;
}
};
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
//Getting the Bitmap from Gallery
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
//Setting the Bitmap to ImageView
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onClick(View v) {
if(v == buttonUpload){
uploadImage();
}
}
}
When you're finishing the Activity2 on a successful image upload, you need to put some extras in the intent which is passed to the launcher activity which is MainActivity.
So the onResponse segment of your uploadImage() function should look like the following. Declare the filePath variable as public so that you can use it here too.
// Declare filePath as public
Uri filePath;
#Override
public void onResponse(String s) {
loading.dismiss();
Toast.makeText(Activity2.this, s, Toast.LENGTH_LONG).show();
Intent returnIntent = new Intent();
returnIntent.putExtra("UPDATED_PIC", filePath.toString());
setResult(RESULT_OK,returnIntent);
finish();
}
Now from your MainActivity handle the retuneIntent to get the filePath and load the image from there. So the onActivityResult may look like -
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PROFILE_PICTURE_REQUEST) {
if (resultCode == RESULT_OK) {
if(data != null) {
Uri filePath = Uri.parse(extras.getString("UPDATED_PIC"));
try {
//Getting the Bitmap from Gallery
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
// Setting the Bitmap to ImageView
mNetworkImageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

Wont be able to upload image into the server

I want to upload image into the database(c panel) in File format.For doing this at first I select an image from gallery or capture an image,set the image in an imageview and try to pass the image as an input parameter through api. But wont be able to send the image file.
Select image
#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 {
//code for deny
}
break;
}
}
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(ProfileActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result=Utility.checkPermission(ProfileActivity.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("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
private void galleryIntent()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select File"),SELECT_FILE);
}
private void cameraIntent()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
iv_profile.setImageBitmap(thumbnail);
ProfileImageAPI api = new ProfileImageAPI(this,this);
api.processProfileImage(AppController.getInstance().userId,destination,"photo.jpg");
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm=null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
iv_profile.setImageBitmap(bm);
}
}
api.php
function process_updateUserProfileImage()
{
$user_id = isset($_REQUEST['user_id'])?$_REQUEST['user_id']:"";
if($user_id == "" ){
echo json_encode(array("error"=>"1", "error_type"=>"user updateUserProfile", "error_no" => "1009", "error_message" => "Input validation"));
exit;
}
$file_name = "";
$file_url = "";
if($_FILES["profile_image"]["name"]!="")
{
$file_name=time().$_FILES["profile_image"]["name"];
$tmp_name=$_FILES["profile_image"]["tmp_name"];
$file_type=$_FILES['profile_image']['type'];
$file_size=$_FILES['profile_image']['size'];
$upload_dir="../profile_image/";
fileUpload($upload_dir,$file_name,$tmp_name,$file_size,"image");
MakeThumbnail($upload_dir, $file_name ,100,100);
$file_url = SITE_URL.'profile_image/'.$file_name;
}
$sql = "update user set
`profile_image` = '".trim($file_url)."'
where user_id = '".$user_id."'
";
$rs = mysql_query($sql);
/*$userArr = array("success"=>"1", "sucess_type"=>"user registration", "success_message" => "User successfully registered");*/
$userInfo = mysql_fetch_array(mysql_query("select * from user where user_id = ".$user_id));
$userArr = array();
$userArr = array('user_id'=>$userInfo['user_id'],'profile_image'=>$userInfo['profile_image'],"success_message" => "profile image updated successfully");
echo json_encode($userArr);
exit();
}
ProfileImageApi class
public class ProfileImageAPI extends BaseAPI {
private Context mContext;
private NetworkCallback mCallback;
public ProfileImageAPI(Context context, NetworkCallback callback) {
super(context);
this.mContext = context;
this.mCallback = callback;
}
public void processProfileImage(final String userId, final File profileImg, final String imgName){
showProgressDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
ApiUtil.BASE_EDIT_PROFILE_IMAGE, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(ApiUtil.TAG_EDIT_PROFILE_IMAGE, response.toString());
mCallback.updateScreen(response,ApiUtil.TAG_EDIT_PROFILE_IMAGE);
hideProgressDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(ApiUtil.TAG_EDIT_PROFILE_IMAGE, "Error: " + error.getMessage());
mCallback.updateScreen("ERROR",ApiUtil.TAG_EDIT_PROFILE_IMAGE);
hideProgressDialog();
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put(ApiUtil.PARAM_USER_ID,userId);
params.put(ApiUtil.PARAM_PROFILE_IMG,profileImg.toString());
params.put(ApiUtil.PARAM_IMG_NAME,imgName);
return params;
}
};
// Adding request to request queue
AppController ctrl = AppController.getInstance();
ctrl.addToRequestQueue(strReq, ApiUtil.TAG_EDIT_PROFILE_IMAGE);
}
}
Which library you have used for api calls.
1. Retrofit
2. Okhttp.
Retrofit MultiPartWebservice : "Retrofit" multiple images attached in one multipart request
OKHttp MultiPartWebservice :
how to use okhttp to upload a file?

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

Post media tweets with Twitter Fabric SDK

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!

Categories

Resources