I have written below codes where when user click attach button to select photos.
Below is code for same.
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(Intent.createChooser(intent, "Select file to upload "), 1);
Below is code for OnActivityResult
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (null != data) { // checking empty selection
if (null != data.getClipData()) { // checking multiple selection or not
for (int i = 0; i < data.getClipData().getItemCount(); i++) {
Uri uri = data.getClipData().getItemAt(i).getUri();
Log.i(TAG, "Path" + getPath(uri));
filespath.add(getPath(uri));
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(getPath(uri), options);
bitmaps.add(bitmap);
}
} else {
Uri uri = data.getData();
}
}
}
}
Now user can select multiple photos and I realized that when photos are more than 10, I get warning too much work done on main thread. when user click on Done button after selecting photos, I have Recycler view where I am showing thumbnail of images selected by user before final upload.
Now issue is when user click Done and till it shows Thumbnail, how can I show ProgressDialog , handle freeze screen and avoid warning work done on main thread.
To keep the parsing and loading work off the main thread you can just wrap everything in an AsyncTask. Given the small amount of code shown, I don't know what functions do what in the above, so this might have to be adjusted a bit. Move all the parsing logic, etc to do in the background as such:
AsyncTask<Void, Void, List<Bitmap>>() {
#Override
protected void onPreExecute()
{
//show progress dialog
//Are you trying to prevent the user from clicking on the UI while updating?
//You can do something such as:
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
}
#Override
protected List<Bitmap> doInBackground(Void... voids) {
//perform the logic, this will return a list of all the Bitmaps to onPostExecute
//Do NOT perform any ui logic here.
}
#Override
protected void onPostExecute(List<Bitmap> bitmaps) {
//cancel progress dialog.
//Update the UI with the response.
//Clear the window lock:
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
}
};
Related
Team
My question is, how do I read the result from the startAtcivityForResult.
When the button is pressed, it calls bStock(), which makes a URL call and retrieves data. I have verified the URL call is correct and that I do get data.
I have used finishActivity(1) to not display the actual content or result. For the sake of this message here is what I get when not using finishActivity(1)
My goal is to read the result and only display certain values like name and last price. Here is my code
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setContentView(R.layout.content_layout_id);
final Button buttonStock = findViewById(R.id.buttonS);
buttonStock.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
bStock();
}
});
}
static final int REQUEST_CODE = 1;
protected void bStock() {
String url = "http://dev.markitondemand.com/Api/v2/Quote/jsonp?symbol=AG";
Uri uri = Uri.parse(url);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
i.setPackage("com.android.chrome");
startActivityForResult(i, REQUEST_CODE);
finishActivity(1);
}
#Override
protected void onActivityResult ( int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE) {
// Make sure the request was successful
//if (resultCode == RESULT_OK) { // 0 -1
// Get the URI that points to the selected contact
Uri o = data.getData();
Toast.makeText(MainActivity.this, "Name ", Toast.LENGTH_LONG).show();});
}
}
I am using a Toast (for now) just to display the name, but I do not know how to read data. Any help would be appreciated.
Jesse
That does not work as you expect, because the activity you are trying to start (chrome browser) is not prepared to return the result you want, to you. The intent (VIEW) tells the browser, to do just that -- view the given URL.
For activities that are not your own, you have to carecully check their description to see if they support any calls for results, and how they return it -- e.g. there is a 'take a picture' intent, that will return the picture taken to you via some uri data.
Most of the time, startActivityForResult is used to start your own activities, which you want to return data to the calling activity. In that case, you can define yourself, on how to pass the results back to the calling activity.
you may need to iterate through a cursor
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request it is that we're responding to
if (requestCode == PICK_CONTACT_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// Get the URI that points to the selected contact
Uri contactUri = data.getData();
// We only need the NUMBER column, because there will be only one row in the result
String[] projection = {Phone.NUMBER};
// Perform the query on the contact to get the NUMBER column
// We don't need a selection or sort order (there's only one result for the given URI)
// CAUTION: The query() method should be called from a separate thread to avoid blocking
// your app's UI thread. (For simplicity of the sample, this code doesn't do that.)
// Consider using CursorLoader to perform the query.
Cursor cursor = getContentResolver()
.query(contactUri, projection, null, null, null);
cursor.moveToFirst();
// Retrieve the phone number from the NUMBER column
int column = cursor.getColumnIndex(Phone.NUMBER);
String number = cursor.getString(column);
// Do something with the phone number...
}
}
}
Having some trouble figuring out how to set the imageview to the picture I just captured with the camera. Would be a bonus if there was some way to display multiple captured pictures at once. Whenever I click the button, a previous image captured appears, then the camera opens, which isn't right. Id like the imageview to be blank, I click the button, take a picture, then that picture is displayed in the imageview. I believe that this line is out of place, but i'm unsure as to how/ where to move it. mimageView.setImageURI(outputFileUri);
public class cameraclass extends Activity {
int TAKE_PHOTO_CODE = 0;
public static int count = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
final ImageView mimageView;
mimageView = (ImageView) this.findViewById(R.id.image_from_camera);
// Here, we are making a folder named picFolder to store
// pics taken by the camera using this application.
final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/";
File newdir = new File(dir);
newdir.mkdirs();
Button capture = (Button) findViewById(R.id.take_image_from_camera);
capture.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Here, the counter will be incremented each time, and the
// picture taken by camera will be stored as 1.jpg,2.jpg
// and likewise.
count++;
String file = dir+count+".jpg";
File newfile = new File(file);
try {
newfile.createNewFile();
}
catch (IOException e)
{
}
//Uri outputFileUri = Uri.fromFile(newfile);
Uri outputFileUri = FileProvider.getUriForFile(getApplicationContext() , "com.example.android.com220finalapp.provider", newfile);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
mimageView.setImageURI(outputFileUri);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
Log.d("CameraDemo", "Pic saved");
}
}
}
I believe that this line is out of place, but i'm unsure as to how/ where to move it.
startActivityForResult() is asynchronous. Your photo will not have been taken by the time that method returns. You need to load the image into the ImageView in onActivityResult(), if you got a RESULT_OK response.
However, while setImageURI() may work, it has never been an especially good idea, as it will freeze your app for a while as it loads the photo. There are many image loading libraries for Android that will handle loading your ImageView asynchronously.
I'll just go straight to the problem. In UploadNotesActivity.java....
First, I pick a .pdf file using intent
chooseNotesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Create intent to Open Image applications like Gallery, Google Photos
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
// Start the Intent
startActivityForResult(intent, RESULT_LOAD_FILE);
}
});
and then, in `onActivityResult, I save the filePath of the picked file.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_FILE && resultCode == RESULT_OK && data != null) {
data.putExtra("filePath", data.getData().getPath());
choosenFile.setText(data.getStringExtra("filePath"));
} else {
Toast.makeText(this, "Error in choosing file",
Toast.LENGTH_LONG).show();
}
}
click Upload button to start upload the file
uploadNotesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onUploadButtonClick();
}
});
the onUploadButtonClick()
private void onUploadButtonClick() {
final String serverUrlString = "http://XXXX/uploadNotes.php";
if (getIntent().getStringExtra("filePath").isEmpty()) {
Log.d(TAG, "filePath is null");
} else {
Log.d(TAG, getIntent().getStringExtra("filePath"));
}
final String fileToUploadPath = getIntent().getStringExtra("filePath");
final String paramNameString = "uploaded_file";
String fileName[] = fileToUploadPath.split("/");
final MultipartUploadRequest request =
new MultipartUploadRequest(this, UUID.randomUUID().toString(), serverUrlString);
request.addFileToUpload(fileToUploadPath, paramNameString,
fileName[fileName.length-1]+".pdf", ContentType.APPLICATION_OCTET_STREAM);
request.setNotificationConfig(R.drawable.ic_launcher,
getString(R.string.app_name),
getString(R.string.uploading),
getString(R.string.upload_success),
getString(R.string.upload_error),
false);
// if you comment the following line, the system default user-agent will be used
request.setCustomUserAgent("UploadServiceDemo/1.0");
// set the intent to perform when the user taps on the upload notification.
// currently tested only with intents that launches an activity
// if you comment this line, no action will be performed when the user taps
// on the notification
// request.setNotificationClickIntent(new Intent(this, MainActivity.class));
// set the maximum number of automatic upload retries on error
request.setMaxRetries(2);
try {
request.startUpload();
} catch (Exception exc) {
Toast toast = Toast.makeText(getApplicationContext(), "Malformed upload request. " + exc.getLocalizedMessage(), Toast.LENGTH_LONG);
toast.show();
}
}
But the problem is, it will throw null pointer exception, which I don't quite get the reason.
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.isEmpty()' on a null object reference
at com.fyp.mycyberlaw.Lecturer.UploadNotesActivity.onUploadButtonClick(UploadNotesActivity.java:73)
at com.fyp.mycyberlaw.Lecturer.UploadNotesActivity.access$100(UploadNotesActivity.java:19)
at com.fyp.mycyberlaw.Lecturer.UploadNotesActivity$2.onClick(UploadNotesActivity.java:53)
line 73: if (getIntent().getStringExtra("filePath").isEmpty())
line 19: public class UploadNotesActivity extends Activity
line 53: onUploadButtonClick();
Seems like the filePath in line 73 is empty and the way I save filePath into bundle (?) is incorrect. How to get the filePath from onActivityResult? Here's the .java class, just in case. Thank you in advance. Really need your help.
An Intentobject is used to pass params between activities. Ones you receives the file path you must to keep it in your activity.
Create a filePathvariable inside your activity, set it on onActivityResult and read it on onUploadButtonClick.
Notice that must save variable value during the onSaveInstanceState callback and restore it in onCreate because every time you turn your phone the activity is destroyed and recreated. Check this for more information: Recreating an Activity
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
The problem class:
public class problem extends Activity {
ImageView iv;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.problem);
iv=(ImageView) findViewById(R.id.imageView1);
Button b=(Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
Bitmap bm=(Bitmap) data.getExtras().get("data");
iv.setImageBitmap(bm);
}
}
This is what I wanted to do:
Take multiple photos
show them in the screen
store them in the mysql databse.
I am new to android please tell me how to do that.I searched.But I could not find a answer.
From this code IT TAKE ONLY ONE PHOTO.
Show Image on Screen Before Saving :
Use my Code. I am taking a picture using camera intent and before saving it to gallery , it is showed to the user with a Save and Cancel Button :- Call Camera Intent :-
// This code is to call the camera intent. Basically it will start your camera. Put this code in a button or something
String SD_CARD_TEMP_DIR = Environment.getExternalStorageDirectory() + File.separator +CommonFunction.getDateTime()+".jpg"; // Get File Path
Intent takePictureFromCameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
takePictureFromCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(SD_CARD_TEMP_DIR)));
startActivityForResult(takePictureFromCameraIntent, 123);
onActivityResult : -
// This function is called when you come back to your activity after the intent has finished. Do read android documentation on Google. It will Help
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_RESULT)
{
if (resultCode == Activity.RESULT_OK)
{
String galleryImatePath = SD_CARD_TEMP_DIR; // make SD_CARD_TEMP_DIR Global so that you can access it here from camera intent or pass it in put Extra method and retrieve it here
File f = new File(galleryImatePath);
try {//This code will rotate your image if you have taken the image by rotating the camera
Bitmap cameraBitmap = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = false;
bmOptions.inPurgeable = true;
bmOptions.inBitmap = cameraBitmap;
bmOptions.inMutable = true;
cameraBitmap = BitmapFactory.decodeFile(galleryImatePath,bmOptions);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
cameraBitmap.compress(Bitmap.CompressFormat.JPEG, 50, bos);
//To Rotate image Code
ExifInterface exif = new ExifInterface(galleryImatePath);
float rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
System.out.println(rotation);
float rotationInDegrees = exifToDegrees(rotation);
System.out.println(rotationInDegrees);
Matrix matrix = new Matrix();
matrix.postRotate(rotationInDegrees);
final Bitmap rotatedBitmap = Bitmap.createBitmap(cameraBitmap , 0, 0, cameraBitmap.getWidth(), cameraBitmap.getHeight(), matrix, true);
FileOutputStream fos=new FileOutputStream(galleryImatePath);
rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 50, fos);
fos.write(bos.toByteArray());
cameraBitmap.recycle();
System.gc();
fos.flush();
fos.close();
// To set image in imageview in dialog. This code will set your image in a custon dialog box "captiondialog". It will contain a full width and height imageview and two textviews - done and cancel. It is upto u what you want to define in the textview's click listener. For example, you can pass the storing image in database in the "Done" textview and "Cancel" textview will dismiss your captiondialog and you app will return to your activity
Capdialog = new Dialog(AddToDo.this,android.R.style.Theme_NoTitleBar_Fullscreen);
Capdialog.setContentView(R.layout.captiondialog);
Capdialog.setCancelable(false);
TextView cancel = (TextView) Capdialog
.findViewById(R.id.cancel);
TextView done = (TextView) Capdialog.findViewById(R.id.done);
Capdialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
ImageView img = (ImageView) Capdialog.findViewById(R.id.image);
img.setImageBitmap(rotatedBitmap);
}
catch(Exception e){}
}
}
}
implement your done and cancel on click listener - what you want to do in them. My code will capture your image, rotate it in the right direction irrespective of camera rotation and show it to you in a dialog before saving it
This code will store your image in DB.You have to use "blob" to store image.. Use This Code :-
public void insertImageInDb(int id , Bitmap img ) {
byte[] data = bos.toByteArray(); // Use This or the code in comments below
/* ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, outputStream);
byte[] data = outputStream.toByteArray();*/
insertStatement_logo.bindLong(1, id);
insertStatement_logo.bindBlob(2, data);
insertStatement_logo.executeInsert();
insertStatement_logo.clearBindings() ;
}
There's an alternative intent action for the device camera that launches the camera in still image mode and does not exit until the user is finished with the activity:
Intent intent = new Intent(
MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA);
this.startActivity(intent);
Used with a ContentObserver this was exactly what I needed to accomplish. or Handle this in ActivityResult.
Note :- if you are new to android, this is too hard for you to understand now. Please read the android documentation first on google and read tutorials. Make basic apps. Learn first
in my app i have some layout to edit a task and select a RingTone and save it into the database.
When i update the task, i one also to update the ringtone name. I use for that the ringtone picker, start a new Intent and get the selected ringtone uri inside the onActivityResult() method.
The problem ist, every time when i click to pick the new RingTone the page reload and i lose all the populated data in my formular, that come from the database.
How can i solve this problem. Is there a way to open the ringtone picker without reload the complete activity after selecting the ringtone?
Here is how i open picker:
protected void openRingtoneDialog() {
final Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, false);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_ALL);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, getString(R.string.ringtone_choose));
if (mAlarmTonUri != null) {
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, mAlarmTonUri);
}
else {
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, (Uri) null);
}
startActivityForResult(intent, RINGTONE_RESULT);
}
and here, how i get the selected ringtone.
#Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
String ringTonTitle = "";
// Get the result from RingtoneActivity
if (resultCode == RESULT_OK && requestCode == RINGTONE_RESULT) {
mAlarmTonUri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
if (mAlarmTonUri != null) {
mAlarmTonValue = mAlarmTonUri.toString();
ringTonTitle = RingtoneManager.getRingtone(this, mAlarmTonUri).getTitle(this);
}
else {
ringTonTitle = "unknow";
}
mAlarmTonTextView.setText(ringTonTitle);
}
Thank you for your help!
I ran into this in my app. I had overridden onResume to reload my view in case changes were made while my app wasn't on top. Coming back from the ringtone picker was setting off my onResume. For me, it was safe to move everything from onResume to onStart. There it would run when my app came to the foreground or first started but not when the ringtone picker was dismissed.