I am making an app with various activities and each activity uses the camera function which is defined in another class. I want that in each activity when the camera button is clicked the camera class is called.
This is my main class:-
package com.example.ishan.complainbox;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.lang.String;
public class Crime extends MainActivity implements View.OnClickListener
{
camera cam=new camera();
EditText str,city,pn,det;
Button save,pic;
crimeDBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crime);
// Get References of Views
str = (EditText) findViewById(R.id.str);
city = (EditText) findViewById(R.id.city);
pn = (EditText) findViewById(R.id.pin);
det = (EditText) findViewById(R.id.detail);
save = (Button) findViewById(R.id.save);
pic=(Button) findViewById(R.id.uploadpic);
dbHandler = new crimeDBHandler(this, null, null, 1);
}
public void onClick(View view) {
String street = str.getText().toString();
String cty = city.getText().toString();
String pin = pn.getText().toString();
String detail = det.getText().toString();
// check if any of the fields are vaccant
if(str.equals("")||city.equals("")||pn.equals("")||det.equals(""))
{
Toast.makeText(getApplicationContext(), "Field Vacant",
Toast.LENGTH_LONG).show();
return;
}
// check if both passwords match
else
{
// Save the Data in Database
dbHandler.insertEntry(street,cty,pin,detail);
Toast.makeText(getApplicationContext(), "Complaint Successfully
Filed ", Toast.LENGTH_LONG).show();
}
}
};
.....and this is the camera class..:-
package com.example.ishan.complainbox;
/**
* Created by ishan on 13/04/2017.
*/
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class camera extends MainActivity{
private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
private Button btnSelect;
private ImageView ivImage;
private String userChosenTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crime);
btnSelect = (Button) findViewById(R.id.uploadpic);
btnSelect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
ivImage = (ImageView) findViewById(R.id.imgView);
}
#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(userChosenTask.equals("Take Photo"))
cameraIntent();
else if(userChosenTask.equals("Choose from Library"))
galleryIntent();
} else {
}
break;
}
}
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(camera.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result=Utility.checkPermission(camera.this);
if (items[item].equals("Take Photo")) {
userChosenTask ="Take Photo";
if(result)
cameraIntent();
} else if (items[item].equals("Choose from Library")) {
userChosenTask ="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();
}
ivImage.setImageBitmap(thumbnail);
}
#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();
}
}
ivImage.setImageBitmap(bm);
}
}
This can be achieved through regular inter-activity communication mechanisms like passing intents or using broadcast receivers. I would suggest using intents - Refer this basic example from Android doc: https://developer.android.com/training/basics/firstapp/starting-activity.html
EDIT
Response to OP's question in comment-
You have to save the image file to FS in your Camera Class and pass the file name as an Extra with the intent to your Crime class. Since you are dealing with storage your Apps's manifest now would need additional permissions. I would recommend you go through this thread: Camera is not saving after taking picture
Related
I have 2 activity, Tambah and Tampil activity.
I use Tambah activity to add new data (form and button submit), and after submit, it will move to Tampil activity. in Tampil activity will show the list view of data (i'm using Volley). all script works, no error. but in Tampil activity only showing old data (like before add), not showing the newest data.
here my Tambah acitivity
package com.example.arif.upload;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import net.gotev.uploadservice.MultipartUploadRequest;
import net.gotev.uploadservice.UploadNotificationConfig;
import java.io.IOException;
import java.util.UUID;
public class Tambah extends AppCompatActivity implements View.OnClickListener{
//Declaring views
private Button buttonChoose;
private Button buttonUpload;
private ImageView imageView;
private EditText editText;
//Image request code
private int PICK_IMAGE_REQUEST = 1;
//storage permission code
private static final int STORAGE_PERMISSION_CODE = 123;
//Bitmap to get image from gallery
private Bitmap bitmap;
//Uri to store the image uri
private Uri filePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tambah);
//Requesting storage permission
requestStoragePermission();
//Initializing views
buttonChoose = (Button) findViewById(R.id.buttonChoose);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
imageView = (ImageView) findViewById(R.id.imageView);
editText = (EditText) findViewById(R.id.editTextName);
//Setting clicklistener
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
}
/*
* This is the method responsible for image upload
* We need the full image path and the name for the image in this method
* */
public void uploadMultipart() {
//getting name for the image
String name = editText.getText().toString().trim();
//getting the actual path of the image
String path = getPath(filePath);
//Uploading code
try {
String uploadId = UUID.randomUUID().toString();
//Creating a multi part request
new MultipartUploadRequest(this, uploadId, Konfigurasi.url_tambah_tentor)
.addFileToUpload(path, "foto") //Adding file
.addParameter("nama", name) //Adding text parameter to the request
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.startUpload(); //Starting the upload
Intent move = new Intent(getApplicationContext(),Tampil.class);
startActivity(move);
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
}
}
//method to show file chooser
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
//handling the image chooser activity result
#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) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
//method to get the file path from uri
public String getPath(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
String document_id = cursor.getString(0);
document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
cursor.close();
cursor = getContentResolver().query(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
cursor.moveToFirst();
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
return path;
}
//Requesting permission
private void requestStoragePermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
return;
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
//If the user has denied the permission previously your code will come to this block
//Here you can explain why you need this permission
//Explain here why you need this permission
}
//And finally ask for the permission
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
//This method will be called when the user will tap on allow or deny
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//Checking the request code of our request
if (requestCode == STORAGE_PERMISSION_CODE) {
//If permission is granted
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Displaying a toast
Toast.makeText(this, "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
} else {
//Displaying another toast if permission is not granted
Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onClick(View v) {
if (v == buttonChoose) {
showFileChooser();
}
if (v == buttonUpload) {
uploadMultipart();
}
}
}
and here Tampil activity
package com.example.arif.upload;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Tampil extends AppCompatActivity {
ListView list_tentor;
ArrayList<String>nama;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tampil);
list_tentor = (ListView)findViewById(R.id.list_tentor);
nama = new ArrayList<String>();
list_tentor.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent pindah = new Intent(Tampil.this,Tambah.class);
pindah.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(pindah);
finish();
}
});
RequestQueue req = Volley.newRequestQueue(getApplicationContext());
StringRequest sr = new StringRequest(Request.Method.GET, Konfigurasi.url_tampil_tentor, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jo = new JSONObject(response);
JSONArray tentor = jo.getJSONArray("tentor");
for (int i = 0; i < tentor.length(); i++){
JSONObject pertentor = tentor.getJSONObject(i);
nama.add(pertentor.getString("nama"));
}
Tampiladapter ta = new Tampiladapter(getApplicationContext(),nama);
list_tentor.setAdapter(ta);
}catch (JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
req.add(sr);
}
}
how can when Intent from Tambah activity to Tampil activity, the Tampil activity reload all data include newest data)?
It seems that you are not waiting until data is uploaded and redirecting to next screen.
Try this answer
Implementing ProgressDialog in Multipart Upload Request
onCompleted redirect to next screen
I am developing an android mobile application in which i am trying to upload the picture on server from android app. The .php files are working fine but the java code is not working and showing error that path is null. I have tried the several types of code but not working at all. Please help.
Thank you
Here is the code.
package com.example.pt_connect.attachmentuploadingandgetting;
import android.Manifest;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import net.gotev.uploadservice.MultipartUploadRequest;
import net.gotev.uploadservice.UploadNotificationConfig;
import java.io.IOException;
import java.util.UUID;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
//Declaring views
private Button buttonChoose;
private Button buttonUpload;
private ImageView imageView;
private EditText editText;
//Image request code
private int PICK_IMAGE_REQUEST = 1;
//storage permission code
private static final int STORAGE_PERMISSION_CODE = 123;
//Bitmap to get image from gallery
private Bitmap bitmap;
//Uri to store the image uri
private Uri filePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Requesting storage permission
requestStoragePermission();
//Initializing views
buttonChoose = (Button) findViewById(R.id.buttonChoose);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
imageView = (ImageView) findViewById(R.id.imageView);
editText = (EditText) findViewById(R.id.editTextName);
//Setting clicklistener
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
}
/*
* This is the method responsible for image upload
* We need the full image path and the name for the image in this method
* */
**public void uploadMultipart() {
//getting name for the image
String name = editText.getText().toString().trim();
//getting the actual path of the image
String path = getPath(MainActivity.this,filePath);
//Uploading code
try {
String uploadId = UUID.randomUUID().toString();
//Creating a multi part request
new MultipartUploadRequest(this, uploadId, Constants.UPLOAD_URL)
.addFileToUpload(path, "image") //Adding file
.addParameter("name", name) //Adding text parameter to the request
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.startUpload(); //Starting the upload
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
}
}**
//method to show file chooser
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
//handling the image chooser activity result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK) {
//Bitmap photo = (Bitmap) data.getData().getPath();
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
//method to get the file path from uri
public String getPath(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
//Requesting permission
private void requestStoragePermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
return;
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
//If the user has denied the permission previously your code will come to this block
//Here you can explain why you need this permission
//Explain here why you need this permission
}
//And finally ask for the permission
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
//This method will be called when the user will tap on allow or deny
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//Checking the request code of our request
if (requestCode == STORAGE_PERMISSION_CODE) {
//If permission is granted
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Displaying a toast
Toast.makeText(this, "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
} else {
//Displaying another toast if permission is not granted
Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onClick(View v) {
if (v == buttonChoose) {
showFileChooser();
}
if (v == buttonUpload) {
uploadMultipart();
}Error
}
}
You have to get the file path like below
String FilePath = data.getData().getPath();
String FileName = data.getData().getLastPathSegment();
on the onActivityResult. I made change to your code. Check below
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK) {
//Bitmap photo = (Bitmap) data.getData().getPath();
filePath = data.getData().getPath();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I think it will work. If not comment here, we will go for another method
MainActivity.java :
package com.example.dell.capcrop;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
final int CAMERA_CAPTURE=1;
private Uri picUri;
final int PIC_CROP=2;
Bundle bundle;
Bitmap bitmap;
ImageView img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button captureBtn=(Button)findViewById(R.id.capture_btn);
captureBtn.setOnClickListener(this);
}
#Override
public void onClick(View v){
if (v.getId()==R.id.capture_btn){
try {
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(captureIntent,CAMERA_CAPTURE);
}
catch (ActivityNotFoundException anfe){
String errorMessage ="Whoops - your device doesn't support capturing image";
Toast toast=Toast.makeText(this,errorMessage,Toast.LENGTH_SHORT);
toast.show();
}
}
}
private void performCrop() {
try{
Intent cropIntent=new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(picUri,"image/*");
cropIntent.putExtra("crop","true");
cropIntent.putExtra("aspectX",1);
cropIntent.putExtra("aspectY",1);
cropIntent.putExtra("outputX",256);
cropIntent.putExtra("outputY",256);
cropIntent.putExtra("return_data",true);
startActivityForResult(cropIntent,PIC_CROP);
}
catch (ActivityNotFoundException anfe)
{
String errorMessage="Whoops - your device doesn't support capturing image";
Toast toast=Toast.makeText(this,errorMessage,Toast.LENGTH_SHORT);
toast.show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==request&&resultCode==RESULT_OK)
{
bundle=data.getExtras();
bitmap=(Bitmap)bundle.get("data");
img.setImageBitmap(bitmap);
Thread thread=new Thread()
{
#Override
public void run() {
try {
sleep(2000);
Intent intent=new Intent(getApplicationContext(),result.class);
bundle.putParcelable("bmp",bitmap);
intent.putExtras(bundle);
startActivity(intent);
finish();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
}
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_CAPTURE) {
picUri = data.getData();
performCrop();
} else if (requestCode == PIC_CROP) {
Bundle extras = data.getExtras();
Bitmap thePic = extras.getParcelable("data");
ImageView picView = (ImageView) findViewById(R.id.picture);
picView.setImageBitmap(thePic);
}
}
}
}
My app is basically a sign language interpreter and I need to remove an error. Here is the code in which there is multiple onactivityresult() definition which is causing error. I do some changes but all in vain. In this code the mobile camera capture image and show a frame in which the user crop the required part of image and show in the next activity.
I am new at android as well as parse.com. I need a way in which a user can click a button to take a photo or another button to choose a photo from the gallery. Then store the image in my parse.com database so that I can manipulate it with other events in the system. So far I am able to have the user update his status and save to my parse database but I do not know how to manipulate images and ImageViews. Here is my code so far:
public class UpdateActivity extends Activity {
protected EditText mUpdateStatus;
protected Button mUpdateStatusButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
//initialization of variables
mUpdateStatus=(EditText)findViewById(R.id.updateStatusUpdate);
mUpdateStatusButton=(Button)findViewById(R.id.updateButtonUpdate);
//code update button click event
mUpdateStatusButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Get current user
ParseUser currentUser=ParseUser.getCurrentUser();//Identifies current user
String currentUserUsername=currentUser.getUsername();//stores username in variable
//Create new variable to store strings
String newStatus=mUpdateStatus.getText().toString();
//Event for an empty status
if (newStatus.isEmpty())
{AlertDialog.Builder builder=new AlertDialog.Builder(UpdateActivity.this);
builder.setMessage("STATUS SHOULD NOT BE EMPTY.");
builder.setTitle("OOPS!");
builder.setPositiveButton("OK",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog=builder.create();
dialog.show();}
else{
//Save the status in Parse.com
ParseObject statusObject = new ParseObject("Status");//Create a new parse class
statusObject.put("newStatus",newStatus);//Creates a new attribute and adds value from newStatus
statusObject.put("User",currentUserUsername);//Stores username in new parse class
//Save data and initiate callback method
statusObject.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if(e==null)
{//Event for a Successful storage
Toast.makeText(UpdateActivity.this,getString(R.string.succssfulUpdate),Toast.LENGTH_LONG).show();
//Take user back to profile
Intent main = new Intent(UpdateActivity.this, ProfileActivity.class);
UpdateActivity.this.startActivity(main);
}
else
{//Event for an Unsuccessful storage
AlertDialog.Builder builder=new AlertDialog.Builder(UpdateActivity.this);
builder.setMessage(e.getMessage());
builder.setTitle("SORRY!");
builder.setPositiveButton("OK",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog=builder.create();
dialog.show();
}
}
});}
}
});
}
#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_update, 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
switch(id) {
case R.id.logoutUpdateMenu:
{//logout the user
ParseUser.logOut();
//Take user back to login
Intent intent = new Intent(UpdateActivity.this, LoginActivity.class);
UpdateActivity.this.startActivity(intent);
UpdateActivity.this.finish();
Toast.makeText(getApplicationContext(), getString(R.string.logout_text), Toast.LENGTH_LONG).show();
break;}
}
return super.onOptionsItemSelected(item);
}
}
A complete example image upload for Parse.com with option to take a photo gallery or the camera.
Activity.class
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseObject;
import com.parse.SaveCallback;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends ActionBarActivity {
private static int RESULT_LOAD_CAMERA_IMAGE = 2;
private static int RESULT_LOAD_GALLERY_IMAGE = 1;
private String mCurrentPhotoPath;
private ImageView imgPhoto;
private Button btnUploadImage;
private File cameraImageFile;
private TextView mTextView;
#Override
public void onActivityResult (int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == RESULT_LOAD_GALLERY_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]);
mCurrentPhotoPath = cursor.getString(columnIndex);
cursor.close();
} else if (requestCode == RESULT_LOAD_CAMERA_IMAGE) {
mCurrentPhotoPath = cameraImageFile.getAbsolutePath();
}
File image = new File(mCurrentPhotoPath);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(), bmOptions);
imgPhoto.setImageBitmap(bitmap);
}
}
private File createImageFile () throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File folder = new File(storageDir.getAbsolutePath() + "/PlayIOFolder");
if (!folder.exists()) {
folder.mkdir();
}
cameraImageFile = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
folder /* directory */
);
return cameraImageFile;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgPhoto = (ImageView)findViewById(R.id.imgPhoto);
imgPhoto.setOnClickListener(chooseImageListener);
btnUploadImage = (Button)findViewById(R.id.btnUpload);
btnUploadImage.setOnClickListener(uploadListener);
}
View.OnClickListener chooseImageListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
dialogChooseFrom();
}
};
View.OnClickListener uploadListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
byte[] image = null;
try {
image = readInFile(mCurrentPhotoPath);
}
catch(Exception e) {
e.printStackTrace();
}
// Create the ParseFile
ParseFile file = new ParseFile("picturePath", image);
// Upload the image into Parse Cloud
file.saveInBackground();
// Create a New Class called "ImageUpload" in Parse
ParseObject imgupload = new ParseObject("Image");
// Create a column named "ImageName" and set the string
imgupload.put("Image", "picturePath");
// Create a column named "ImageFile" and insert the image
imgupload.put("ImageFile", file);
// Create the class and the columns
imgupload.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
Toast.makeText(getBaseContext(), "Done!", Toast.LENGTH_LONG).show();
}
});
}
};
private void dialogChooseFrom(){
final CharSequence[] items={"From Gallery","From Camera"};
AlertDialog.Builder chooseDialog =new AlertDialog.Builder(this);
chooseDialog.setTitle("Pick your choice").setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(items[which].equals("From Gallery")){
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_GALLERY_IMAGE);
} else {
try {
File photoFile = createImageFile();
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photoFile));
startActivityForResult(cameraIntent, RESULT_LOAD_CAMERA_IMAGE);
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
chooseDialog.show();
}
private byte[] readInFile(String path) throws IOException {
byte[] data = null;
File file = new File(path);
InputStream input_stream = new BufferedInputStream(new FileInputStream(file));
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
data = new byte[16384]; // 16K
int bytes_read;
while ((bytes_read = input_stream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, bytes_read);
}
input_stream.close();
return buffer.toByteArray();
}
}
Layout
<RelativeLayout 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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<RelativeLayout
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true"
android:layout_width="200dp"
android:layout_height="200dp"
android:background="#ccc">
<ImageView
android:id="#+id/imgPhoto"
android:layout_width="200dp"
android:layout_height="200dp"
/>
<TextView
android:text="Choose a image"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
android:layout_margin="2dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
<Button
android:id="#+id/btnUpload"
android:text="Upload Photo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
Android Manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
I have no experience with parse.com but If you are able to put images(bit map) into ParseObject, you just need to call take photo or pick photo action using intent and startActivityForResult. Example:
public void onClickTakePhoto(View view) {
dispatchTakePictureIntent();
}
public void onClickPickPhoto(View view) {
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, REQUEST_SELECT_IMAGE);
}
//Code from Android documentation
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if ((requestCode == REQUEST_IMAGE_CAPTURE ||Â requestCode == REQUEST_SELECT_IMAGE) && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
ParseObject statusObject = new ParseObject("Status");
//I think parse has similar support If not this
statusObject.put("profile_photo",imageBitmap);
statusObject.saveInBackground( new Callback(){...});
}
}
You need to convert your Bitmap or any Object into byte[].
And then use following code.
byte[] image= your byte array
final ParseFile files = new ParseFile(image);
files.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException exception) {
if (exception == null) {
ParseUser.getCurrentUser().put("<parse-column-name>", files);
ParseUser.getCurrentUser().saveInBackground();
}
}
});
Hope this helps.
This is how you can upload a file to a Parse server (Back4App):
ByteArrayOutputStream bos = new ByteArrayOutputStream();
newProfileImageBitmap.compress(Bitmap.CompressFormat.PNG, 0, bos);
byte[] bitmapData = bos.toByteArray();
ParseFile newImageFile = new ParseFile(bitmapData);
currentUser.put("userPicture", newImageFile);
currentUser.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if(e == null) {
// Image has been uploaded
} else {
// An error has happened when upoading
}
}
});
My app is to open the built in camera and save it into sd card then start a new activity and preview the captured image on it.
This is the loginActivity that start a new AsynTask to open the camera :
package com.android.grad;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import com.Camera.R;
public class LoginActivity extends Activity {
private final int MEDIA_TYPE_IMAGE = 1;
private CheckBox rememberMe;
private EditText userName, passWord;
private Button loginBtn;
private final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
private String path;
private Uri fileUri;
private OnClickListener loginOnClick = new OnClickListener() {
public void onClick(View v) {
new LoginTask(LoginActivity.this, fileUri).execute();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
path = fileUri.getPath();
loginBtn = (Button) findViewById(R.id.signInBtn);
loginBtn.setOnClickListener(loginOnClick);
rememberMe = (CheckBox) findViewById(R.id.keepMe);
userName = (EditText) findViewById(R.id.userNameID);
passWord = (EditText) findViewById(R.id.passwordID);
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences sp = getSharedPreferences("user", MODE_PRIVATE);
try {
userName.setText(sp.getString("username", ""));
passWord.setText(sp.getString("password", ""));
rememberMe.setChecked(sp.getBoolean("rememberMe", false));
} catch (ClassCastException ex) {
}
}
#Override
protected void onPause() {
super.onPause();
SharedPreferences sp = getSharedPreferences("user", MODE_PRIVATE);
Editor editor = sp.edit();
if (rememberMe.isChecked()) {
editor.putString("username", userName.getText().toString());
editor.putString("password", passWord.getText().toString());
} else {
editor.putString("username", "");
editor.putString("password", "");
}
editor.putBoolean("rememberMe", rememberMe.isChecked());
editor.commit();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Intent intent = new Intent(LoginActivity.this,
PreviewActivity.class);
intent.putExtra("path", path);
startActivity(intent);
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
Toast.makeText(getApplicationContext(),
"User cancelled the image capture", Toast.LENGTH_LONG)
.show();
} else {
// Image capture failed, advise user
}
}
}
/** Create a file Uri for saving an image or video */
private Uri getOutputMediaFileUri(int type) {
File f = getOutputMediaFile(type);
if (f == null) {
Toast.makeText(LoginActivity.this, "MyCameraApp File not found",
Toast.LENGTH_LONG);
return null;
}
return Uri.fromFile(f);
}
/** Create a File for saving an image or video */
private File getOutputMediaFile(int type) {
// Check if SD card is mounted
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
File externalFilesDir = LoginActivity.this
.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File outFile = new File(externalFilesDir, "IDOCR");
if (!outFile.exists())
outFile.mkdirs();
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
String path = outFile.getPath() + File.separator + "IMG"
+ timeStamp + ".jpg";
File mediaFile = new File(path);
return mediaFile;
}
Toast.makeText(LoginActivity.this, "SD card unmounted",
Toast.LENGTH_LONG);
return null;
}
}
And this is the AsynTask :-
package com.android.grad;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.MediaStore;
public class LoginTask extends AsyncTask<Void, Void, Boolean> {
private Activity activity;
private ProgressDialog pd;
private Uri fileUri;
private final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
public LoginTask(Activity activity, Uri fileUri) {
this.activity = activity;
this.fileUri = fileUri;
}
#Override
protected void onPreExecute() {
pd = ProgressDialog.show(activity, "Signing in",
"Please wait while we are signing you in..");
}
#Override
protected Boolean doInBackground(Void... arg0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
pd.dismiss();
pd = null;
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
activity.startActivityForResult(intent,
CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
}
and this is the previewActivity:-
package com.android.grad;
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import com.Camera.R;
import com.OCR.ID.AndroidImage;
import com.OCR.ID.Segement;
public class PreviewActivity extends Activity {
private ImageView previewIV;
private final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
private String path;
private boolean crop = true;
private boolean resample = true;
private ProgressDialog pd;
OnClickListener processOnClickListener = new OnClickListener() {
public void onClick(View v) {
try {
createProgressDialog();
pd.show();
new Segement(PreviewActivity.this, pd).execute(path);
} catch (IOException e) {
}
}
};
private void createProgressDialog() {
pd = new ProgressDialog(PreviewActivity.this);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setTitle("Extract ID");
pd.setMessage("Processing...");
pd.setIcon(R.drawable.ic_launcher);
pd.setProgress(0);
pd.setCancelable(false);
}
private OnClickListener backOnClickListener = new OnClickListener() {
public void onClick(View v) {
startActivityForResult(
new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(
MediaStore.EXTRA_OUTPUT,
Uri.fromFile(new File(path))),
CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
};
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
previewIV.setImageBitmap(BitmapFactory.decodeFile(path));
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.preview);
path = getIntent().getExtras().getString("path");
previewIV = (ImageView) findViewById(R.id.previewPicID);
previewIV.setImageBitmap(AndroidImage.decodeSampledBitmapFromSDcard(
path, 150, 150));
// previewIV.setImageBitmap(AndroidImage.readImage(path));
Button process = (Button) findViewById(R.id.processID);
process.setOnClickListener(processOnClickListener);
Button back = (Button) findViewById(R.id.back);
back.setOnClickListener(backOnClickListener);
}
}
The error that appear that sometimes when take picture it appear in the previewActivity and
sometime doesn't appear ?
Why that error
??