My app crashes when linking to another page - android

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.

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>

How to build a URL in Koush ion

I am building an app to upload images to my company server
I am using koush-ion for the upload,
now my problem is I have to dynamically change the URL for upload depending on information entered in another activity(LoginActivity) via edittext boxes
and I don't understand how to do that
so what I want to happen is the client enters thier Email, password and clientID(4 digits)(in LoginActivity) and the app uses that to build a url for the upload
like this one(in CameraActivity)
https://www.blahpractice.co.za/files-upload-ruben.asp?MyForm=Yes&ClientID=1234&Username=man#blahpractice.co.za&Pwd=BlahBlah123#
I got this From the koush github, and i am unsure if this is what i am looking for and also how to implement data from another activity in koush-ion
Post application/x-www-form-urlencoded and read a String
Ion.with(getContext())
.load("https://koush.clockworkmod.com/test/echo")
.setBodyParameter("goop", "noop")
.setBodyParameter("foo", "bar")
.asString()
.setCallback(...)
Camera Activity
public class CameraActivity extends AppCompatActivity implements
View.OnClickListener{
private final int PICK_IMAGE = 12345;
private final int REQUEST_CAMERA = 6352;
private static final int REQUEST_CAMERA_ACCESS_PERMISSION =5674;
private Bitmap bitmap;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
imageView =findViewById(R.id.imageView);
Button fromCamera=findViewById(R.id.fromCamera);
Button fromGallery=findViewById(R.id.fromGallery);
Button upload=findViewById(R.id.upload);
upload.setOnClickListener(this);
fromCamera.setOnClickListener(this);
fromGallery.setOnClickListener(this);
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)) {
fromCamera.setVisibility(View.GONE);
}
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.fromCamera:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA_ACCESS_PERMISSION);
}else {
getImageFromCamera();
}
break;
case R.id.fromGallery:
getImageFromGallery();
break;
case R.id.upload:
if (bitmap != null)
uploadImageToServer();
break;
}
}
private void uploadImageToServer() {
I want to call the url here
File imageFile = persistImage(bitmap, "SP_Upload");
Ion.with(this)
.load("https://www.Blahpractice.co.za/files-upload-ruben.asp?MyForm=Yes")
.setMultipartFile("SP-LOG", "image/jpeg", imageFile)
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
#Override
public void onCompleted(Exception e, JsonObject result) {
}
});
}
private File persistImage(Bitmap bitmap, String name) {
File filesDir = getApplicationContext().getFilesDir();
File imageFile = new File(filesDir, name + ".jpg");
OutputStream os;
try {
os = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
os.flush();
os.close();
} catch (Exception e) {
Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
}
return imageFile;
}
private void getImageFromCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
private void getImageFromGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE) {
if (resultCode == Activity.RESULT_OK) {
try {
InputStream inputStream = getContentResolver().openInputStream(data.getData());
bitmap = BitmapFactory.decodeStream(inputStream);
imageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
} else if (requestCode == REQUEST_CAMERA) {
if (resultCode == Activity.RESULT_OK) {
Bundle extras = data.getExtras();
bitmap = (Bitmap) extras.get("data");
imageView.setImageBitmap(bitmap);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == REQUEST_CAMERA_ACCESS_PERMISSION) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getImageFromCamera();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
LoginActivity
public class LoginActivity extends AppCompatActivity {
private EditText email, password, id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
email=findViewById(R.id.emailtext);
password=findViewById(R.id.pwdtext);
id=findViewById(R.id.clientid);
Button loginBtn=findViewById(R.id.button);
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String emailAddress=email.getText().toString().trim();
String userPassword=password.getText().toString().trim();
String clientId=id.getText().toString().trim();
Intent intent=new Intent(LoginActivity.this, CameraActivity.class);
intent.putExtra("clientId", clientId);
intent.putExtra("email", emailAddress);
intent.putExtra("password", userPassword);
startActivity(intent);
}
});
}
}
You could store the url on the shared preferences and retrieve it every time you execute your upload task and set it on the .load() method.
Also, what you need to send an image to your server is a multipart post. I haven't used Ion but I have used multipart in other libraries like OkHttp, I´ve copied the method that appears on the Ion documentation:
String dynamicUrl = PreferenceManager.getDefaultSharedPreferences(context).getString(CURRENT_SELECTED_URL, null);
File myImage = new File(myImagePath);
if(dynamicUrl != null) {
Ion.with(getContext())
.load(dynamicUrl)
.uploadProgressBar(uploadProgressBar)
.setMultipartParameter("goop", "noop")
.setMultipartFile("myImageName", "image/*", myImage)
.asJsonObject()
.setCallback(...)
}

Mapping listView items with photos from the cloud

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

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

Get the content of image view in android

In my app the user can laod an image from Gallery or from Camera and it be shown in
imageView. What i want to do is to send the image to my server. In order to that,
i should to convert it to Base64 type.
Everything is well but i don't know how to get the content of the imageView for converting it,
and where exactly to put the code.
My activity is :
public class MainActivity extends Activity {
private static int FROM_CAMERA = 1;
private static int FROM_GALLERY = 2;
ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputEmail;
Button sendData;
JSONObject json;
ImageView userImg;
private static String url_create_user = "http://localhost/android_connect/create_user.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inputName = (EditText)findViewById(R.id.userName);
inputEmail = (EditText)findViewById(R.id.email);
sendData = (Button)findViewById(R.id.send);
userImg = (ImageView)findViewById(R.id.userImage);
sendData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isNetworkConnected())
new CreateNewUser().execute();
else
Toast.makeText(getApplicationContext(), "Please connect to internet!", Toast.LENGTH_LONG).show();
}
});
userImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String[] options = new String[]{"Camera","Gallery"};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setItems(options, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if(which == 0){
Intent c = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(c, FROM_CAMERA);
}
else{
Intent g = new Intent(Intent.ACTION_GET_CONTENT);
g.setType("image/*");
startActivityForResult(g, FROM_GALLERY);
}
}
});
builder.create();
builder.show();
}
});
}
class CreateNewUser extends AsyncTask<String, String,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Creating user...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
String username = inputName.getText().toString();
String email = inputEmail.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("email", email));
json = jsonParser.makeHttpRequest(url_create_user, "POST", params);
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
if(json != null){
Toast.makeText(getApplicationContext(), "The data has been sent successfully!", Toast.LENGTH_LONG).show();
}
else
Toast.makeText(getApplicationContext(), "Failed to send data!", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ImageView imageView = (ImageView)findViewById(R.id.userImage);
if (requestCode == FROM_GALLERY && 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]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
else{
if(requestCode == FROM_CAMERA && resultCode == RESULT_OK && null != data )
{
Bundle extras = data.getExtras();
Bitmap photo = extras.getParcelable("data");
imageView.setImageBitmap(photo);
}
}
}
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) return false;
else return true;
}
}
This is the code for convert the image to base64:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte [] byte_arr = stream.toByteArray();
String image_str = Base64.encodeToString(byte_arr, Base64.DEFAULT);
and i should add this sentence in doInBackground method:
params.add(new BasicNameValuePair("image", image_str));
Thanks!!!
This is how you get the bitmap of your Imageview:
Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
After you convert to base64.
I solved my problem. here is the solution:
To get the content of the image to bitmap i do this -
Bitmap bitmap = ((BitmapDrawable)userImg.getBackground()).getBitmap();
and this works very well without any errors.
I put the converting code in onActivityResult() like this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == FROM_GALLERY && resultCode == RESULT_OK && null != data) {
//Getting the image from gallery and set it to imageView
}
else{
if(requestCode == FROM_CAMERA && resultCode == RESULT_OK && null != data )
{
//Getting the image from camera and set it to imageView
}
}
Bitmap bitmap = ((BitmapDrawable)userImg.getBackground()).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte [] byte_arr = stream.toByteArray();
image = Base64.encodeToString(byte_arr, Base64.DEFAULT);
}
Everything get well.

Categories

Resources