I am a newbie on android app development. My team and I are creating an app that uses photo gallery folders to upload the photo. The app is able to take a photo and upload that photo immediately. But specifically with samsung devices, when I try to upload photo from camera folder, app either crashes or uploads a white page. When I try a different folder from the gallery besides than camera folder, that works perfect too. It gives this error only with camera folder. I tested my app with different nexus devices and it worked absolutely perfect. I have been searching this any where and everywhere. I wrote all the codes on Android Studio along with Java and XML. Did anyone have the same issue and were able to solve? I really need a guidance. Thanks for your time and your attention.
Here is my Java onGalleryClick method:
public void onGalleryClick(View v) {
isCameraReleased = true;
//TODO
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), SELECT_PICTURE);
}
I think I figured it out with implementing Picasso library. Finally I can access to Camera folder( Some of the devices it is DCIM) when I got into gallery option. I believe Samsung devices has a very low virtual memories and somehow it doesn't allow you to see the imageView on the android app that you create. Basically I created a very simple button on android studio and it's called activity_main.xml. Which is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/imgView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1" >
</ImageView>
<Button
android:id="#+id/buttonLoadPicture"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="0"
android:onClick="loadImagefromGallery"
android:text="Load Picture" >
</Button>
</LinearLayout>
Afterward, I created MainActivity.java that gives all the functionality. Which is:
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
private static int RESULT_LOAD_IMG = 1;
String imgDecodableString;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void loadImagefromGallery(View view) {
// Create intent to Open Image applications like Gallery, Google Photos
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
ImageView imgView = (ImageView) findViewById(R.id.imgView);
// Set the Image in ImageView after decoding the String
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgDecodableString));
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
}
And this is the line of code that you have to add on AndroidManifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Here is the tricky part of everything. in your build.gradle(Module:app) you are going to add
compile 'com.squareup.picasso:picasso:2.3.3' at dependencies section.
After you gotta add
ImageView imageView = (ImageView) findViewById(R.id.imageView);
Picasso.with(this)
.load("https://cms-assets.tutsplus.com/uploads/users/21/posts/19431/featured_image/CodeFeature.jpg")
.into(imageView);
And there you go!Please take a look http://code.tutsplus.com/tutorials/android-sdk-working-with-picasso--cms-22149
Related
This question already has answers here:
Low picture/image quality when capture from camera
(3 answers)
Closed 3 years ago.
I created a project that allow user to take a picture and view it. I have no face any issue while taking, view, save and retrieve the photo. But my problem is the image that camera took is in bad quality, I don't know how to set the quality of the camera Intent. Here is my code looks like.
....
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
....
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap userPhoto = (Bitmap) data.getExtras().get("data");
iv_user.setImageBitmap(userPhoto);
}
}
Here is a screenshot of while camera is on.
And here is in preview camera mode after the image is captured.
If we compare these two photos, we can see the image in preview mode is blur.
Im actually not sure why it's like that but it's same here after every method tried, so I suggest the solution that you make use of a very simple library like below, good things is your picture quality remains intact.
simple add to your gradle file:
implementation 'com.theartofdev.edmodo:android-image-cropper:2.7.+'
Simple call startCameraAndOptions(); method to start you camera
startCameraAndOptions(); //call to starts you camera with other additional option like gallery.
public void startCameraAndOptions(View view) {
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setActivityTitle("My Crop")
.setCropShape(CropImageView.CropShape.RECTANGLE)
.setCropMenuCropButtonTitle("Done")
// .setRequestedSize(400, 400)
.setAllowRotation(true)
.setOutputCompressQuality(100)
.setCropMenuCropButtonIcon(R.drawable.arrow)
.start(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
BitmapDrawable background;
Bitmap bitmap;
ImageView img_preview = (ImageView) findViewById(R.id.img_preview);
// handle result of CropImageActivity
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), result.getUri());
background = new BitmapDrawable(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
Picasso.get()
.load(result.getOriginalUri())
// .resize(200, 200)
// .centerCrop()
.into(img_preview);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Toast.makeText(this, "Cropping failed: " + result.getError(), Toast.LENGTH_LONG).show();
}
}
}
**/* LAYOUT SECTION */ optional (style it your own way)**
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context="com.hollaport.hollaport.Demo">
<Button
android:layout_marginTop="10dp"
android:layout_gravity="center"
android:id="#+id/trigger"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#drawable/camera"/>
<!--<com.theartofdev.edmodo.cropper.CropImageView-->
<!--android:id="#+id/cropImageView"-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="0dp"-->
<!--android:layout_weight="1"/>-->
<android.support.v7.widget.CardView
android:id="#+id/view2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:layout_gravity="center"
android:adjustViewBounds="true"
android:innerRadius="0dp"
android:shape="rectangle"
android:thicknessRatio="2"
app:cardCornerRadius="0dp">
<ImageView
android:id="#+id/img_preview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:adjustViewBounds="true"
android:scaleType="fitXY"/>
</android.support.v7.widget.CardView>
</LinearLayout>
The Android Camera application encodes the photo in the return Intent delivered to onActivityResult() as a small Bitmap (we call it thumbnail) in the extras, under the key "data".
If you want to retrive full size image your app first need to store image to external storage and then read it back. You can access full code at
https://developer.android.com/training/camera/photobasics
I could select an image from gallery in android. But, i want to select next and previous images of the selected image. How do i do it?
This works fine.. for selecting and then displaying the image..now what do i do for selecting next and previous images?
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
// Show only images, no videos or anything else
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
// Log.d(TAG, String.valueOf(bitmap));
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I could select an image from gallery in android
Your code happens to bring up a gallery app on your device. You are requesting ACTION_GET_CONTENT for image/*. This means:
Other apps, besides a gallery, can respond to that Intent and can be chosen by the user
There will be devices that do not have an app that would be considered a "gallery"
How do i do it?
Write your own gallery. There is no concept of "next" or "previous" with ACTION_GET_CONTENT.
There are many image picker libraries for Android that might form the basis for your own gallery UI.
I forgot to write the most important thing, which is code for previous and next is not working.. till now i have written code only for previous, coz once it works; next ll be just few changes ahead.
moveToprevious is coming false n cursor is declared as global.. so that when a query for cusor s fired in getcontentresolver() is fired, it gets the needed value..
Please look into this!
I tried my best to find the solution before asking, however, I can't seem to locate a similar situation.
I've implemented a QR scanner for an app I am working on. I'm using the zxing library, specifically using the imports below. Also, the apps uses "Barcode Scanner" from play store (I was prompted to install).
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
The issue is that the scanner only works 1 out every 3-6 scans. I either get a null return, or no output. It always returns back to my source screen, and never produces an actual error.
I used this tutorial as a source: Android SDK: Create a Barcode Reader
Here is the relevant info from mainactivity:
public void onClick(View v){
//respond to clicks
if(v.getId()==R.id.scanQRButton){
//scan
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
formatTxt.setText( "Scan Initiated");
contentTxt.setText(" Scan Results: " + scanContent);
if(scanContent != null){
String userid,medname,tabstaken,dob;
StringTokenizer st = new StringTokenizer(scanContent, ",");
// token 0
dob = st.nextToken();
//token 1
medname = st.nextToken();
//token 2
tabstaken = st.nextToken();
//token 3
//rxnumber
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
HashMap<String,String> user = new HashMap<String, String>();
user = db.getUserDetails();
//Store the userlog by passing to UserLogEntry
userid = user.get("uid");
//debug.setText("Userid: "+ userid+ " medname: " + medname + " tabs: " +tabstaken);
UserLogEntry userlog = new UserLogEntry(getApplicationContext(),userid,medname,tabstaken);
userlog.addUserLog();
}
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//retrieve scan result
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
//we have a result
scanContent = scanningResult.getContents();
}
else{
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
}
And here are the ZXing classes from the library package I'm using:
IntentResults:
https://code.google.com/p/zxing/source/browse/trunk/android-integration/src/com/google/zxing/integration/android/IntentResult.java?r=1273
IntentIntegrator:
https://code.google.com/p/zxing/source/browse/trunk/android-integration/src/com/google/zxing/integration/android/IntentIntegrator.java?spec=svn2260&r=2260
Any ideas on how to get this to work %100 of the time?
Thanks!
So I tried several different ways to get the scanner to work with zxing, and nothing would work. It just felt buggy no matter what I did. That on top of the fact that integrating the scanner so it doesn't need a third party app (as in Barcode scanner) was a major pain. I decided to look for an alternative and found ZBar.
If anyone has any problems using zxing for QR scanning I'd recommend using Zbar instead. The code itself is much simpler. You can use the example given on the zbar page and pretty much copy and paste it into your project without changes(or very little). Also, integrating it as an all inclusive scanner is simple as can be.
I'm including the instructions here for a more inclusive answer. This information is available in tutorials, and at the ZBar page, however, it doesn't hurt to include them here in my answer.
First download the zip here: https://github.com/dm77/ZBarScanner
Then add "ZBarScannerLibrary" as an existing android project.
For ZBarScannerLibrary: Right click->properties->android and check "Is Library"
Select your project (the one you're adding qr scanner to), right click->properties->android->Add select ZBarScannerLibrary.
Now add the ZBar code given on the page: https://github.com/dm77/ZBarScanner (shown below to be helpful.
Enjoy qr scanning without pulling out your hair
Here is the main activity for the sample provided with ZBar. Don't forget to add the appropriate lines to android manifest:
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera" />
Within the application element, add the activity declaration:
<activity android:name="com.dm.zbar.android.scanner.ZBarScannerActivity"
android:screenOrientation="landscape"
android:label="#string/app_name" />
I used a String Tokenizer to pull apart the QR results and sort them into specific variables.
package com.dm.zbar.android.examples;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;
import com.dm.zbar.android.scanner.ZBarConstants;
import com.dm.zbar.android.scanner.ZBarScannerActivity;
import net.sourceforge.zbar.Symbol;
public class MainActivity extends Activity {
private static final int ZBAR_SCANNER_REQUEST = 0;
private static final int ZBAR_QR_SCANNER_REQUEST = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void launchScanner(View v) {
if (isCameraAvailable()) {
Intent intent = new Intent(this, ZBarScannerActivity.class);
startActivityForResult(intent, ZBAR_SCANNER_REQUEST);
} else {
Toast.makeText(this, "Rear Facing Camera Unavailable", Toast.LENGTH_SHORT).show();
}
}
public void launchQRScanner(View v) {
if (isCameraAvailable()) {
Intent intent = new Intent(this, ZBarScannerActivity.class);
intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{Symbol.QRCODE});
startActivityForResult(intent, ZBAR_SCANNER_REQUEST);
} else {
Toast.makeText(this, "Rear Facing Camera Unavailable", Toast.LENGTH_SHORT).show();
}
}
public boolean isCameraAvailable() {
PackageManager pm = getPackageManager();
return pm.hasSystemFeature(PackageManager.FEATURE_CAMERA);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ZBAR_SCANNER_REQUEST:
case ZBAR_QR_SCANNER_REQUEST:
if (resultCode == RESULT_OK) {
Toast.makeText(this, "Scan Result = " + data.getStringExtra(ZBarConstants.SCAN_RESULT), Toast.LENGTH_SHORT).show();
} else if(resultCode == RESULT_CANCELED && data != null) {
String error = data.getStringExtra(ZBarConstants.ERROR_INFO);
if(!TextUtils.isEmpty(error)) {
Toast.makeText(this, error, Toast.LENGTH_SHORT).show();
}
}
break;
}
}
}
I want to ask how I can use speech to text code on my emulator. My codes work on real device but not work on emulator. The error said :
No Activity found to handle Intent { act=android.speech.action.RECOGNIZE_SPEECH (has extras) }
What can I do?
package net.viralpatel.android.speechtotextdemo;
import java.util.ArrayList;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
protected static final int RESULT_SPEECH = 1;
private ImageButton btnSpeak;
private TextView txtText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtText = (TextView) findViewById(R.id.txtText);
btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);
btnSpeak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
try {
startActivityForResult(intent, RESULT_SPEECH);
txtText.setText("");
} catch (ActivityNotFoundException a) {
Toast t = Toast.makeText(getApplicationContext(),
"Ops! Your device doesn't support Speech to Text",
Toast.LENGTH_SHORT);
t.show();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_SPEECH: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> text = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txtText.setText(text.get(0));
}
break;
}
}
}
}
You need to install onto your emulator an app that contains an Activity that handles the RECOGNIZE_SPEECH-intent. You might be able to find Google's VoiceSearch.apk on the web.
There are certain things you can't test using an emulator. Speech to text is on of them.
I'm not sure about this, but you can't use this android feature with the emulator.
No matter what, you should handle this exception with a try/ catch an give some feedback to the user.
You can check if there is that Activity in current device running your app doing something like:
PackageManager pm = context.getPackageManager();
List<ResolveInfo> infoList = pm.queryIntentActivities(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (infoList.size() == 0) {
/** Show some feedback to user if there is the activity. Something like "Your device is not abl to run this feature..."*/
}else{
/**Your current code goes here.*/
}
Let me know if it helps.
You need to install com.google.android.voicesearch application on target device which has no voice recognition activity like:
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.google.android.voicesearch"));
startActivity(browserIntent);
if you try to install Google's Search app - it won't help since it doesn't contain the VR engine inside and thus it will try to do the same - install com.google.android.voicesearch app but it could fail due to a bug in package name (pname:com.google.android.voicesearch instead of just pure package name). However com.google.android.voicesearch installation might be impossible due to "Not available in your country".
You might need a virtual SD Card. You can refer here
I am making a program that takes a picture and then shows it's thumbnail.
When using the emulator all goes well and the discard button deletes the photo.
But on a real device the camera intent saves the image at the imageUri variable and a second one that is named like if I had just opened up the camera and took a picture by itself.
private static final int CAMERA_PIC_REQUEST = 1337;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
//start camera
values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION,"From your Camera");
imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
image = (ImageView) findViewById(R.id.ImageView01);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
//save the image buttons
Button save = (Button) findViewById(R.id.Button01);
Button close = (Button) findViewById(R.id.Button02);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_PIC_REQUEST && resultCode == RESULT_OK) {
try{
thumbnail = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
image.setImageBitmap(thumbnail);
}
catch(Exception e){
e.printStackTrace();
}
}
else{
finish();
}
}
public void myClickHandler(View view) {
switch (view.getId()) {
case R.id.Button01:
finish();
break;
case R.id.Button02:
dicard();
}
}
private void dicard(){
getContentResolver().delete(imageUri, null, null);
finish();
}
Some Android phones store the original photo in the gallery, and a thumbnail only in your location. It doesn't matter what you did with the original request. I have two different HTC phones doing it, and a slew of other brands not doing it.
I solved this another way. I ran a query of every item in the gallery and loaded the BucketIDs to an array. I do this when my app starts the camera app. When the camera app returns, I make the same query (with items recently added to save time). I compare this to my original list and find the new BucketID. Next, I compare the size of this image with the file I explicitly set as the output. If it's bigger, I copy it, replacing what I had. Then I delete the file and remove it from the gallery.
Pain in the you-know-what!
[EDIT] I had to change this around again when I discovered a phone that didn't keep unique bucket IDs... See my post in the link following this answer for more.