I have created an application where one can view images. The problem I am facing is that when I use ".nomedia" in folder it hides images from gallery and images are also hidden in my application. I need a method with help of which images can remain hidden from gallery but shown in my application. I am accessing images using path of folder.
Code:
public class SdActivity extends Activity implements
MediaScannerConnectionClient {
public String[] allFiles;
private String SCAN_PATH;
private static final String FILE_TYPE = "*/*";
private MediaScannerConnection conn;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
File folder = new File("/sdcard/DCIM");
allFiles = folder.list();
// uriAllFiles= new Uri[allFiles.length];
for (int i = 0; i < allFiles.length; i++) {
Log.d("all file path" + i, allFiles[i] + allFiles.length);
}
// Uri uri= Uri.fromFile(new
// File(Environment.getExternalStorageDirectory().toString()+"/yourfoldername/"+allFiles[0]));
SCAN_PATH = Environment.getExternalStorageDirectory().toString()
+ "/yourfoldername/" + allFiles[0];
Log.d("SCAN PATH", "Scan Path " + SCAN_PATH);
Button scanBtn = (Button) findViewById(R.id.buttonLoadPicture);
scanBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startScan();
}
});
}
private void startScan() {
Log.d("Connected", "success" + conn);
if (conn != null) {
conn.disconnect();
}
conn = new MediaScannerConnection(this, this);
conn.connect();
}
#Override
public void onMediaScannerConnected() {
Log.d("onMediaScannerConnected", "success" + conn);
conn.scanFile(SCAN_PATH, FILE_TYPE);
}
#Override
public void onScanCompleted(String path, Uri uri) {
try {
Log.d("onScanCompleted", uri + "success" + conn);
if (uri != null) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
}
} finally {
conn.disconnect();
conn = null;
}
}
}
Related
Hello I am facing Strange Problem I am making an gallery App which download images using volley and showing them to Viewpager called SlideActivity everything is working properly. Problem:- when I try to Download & share 1st image from viewpager nothing happens but when swipe and go to 2nd image share and download is working for 2nd image and when i swipe back to 1st image now share and download works? This is what i have done till now want some advice on this issue.Thank you in Advance!
SlideActivity.Java
public class TrendingSlideActivity extends AppCompatActivity {
private static final String URL = "API";
private ViewPager viewPager;
private Context context = TrendingSlideActivity.this;
private TrendingViewPagerAdapter adapter;
private int position;
private int currentImage;
private List<Trending> data;
private ImageView shareIcon, shareImage, downloadImage;
private int mAdCounter = 0;
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.trending_slide_activity);
viewPager = findViewById(R.id.viewPager);
ProgressBar progressBar = findViewById(R.id.progress);
shareIcon = findViewById(R.id.shareviewpager);
downloadImage = findViewById(R.id.iv_download_slide);
//final String fileName = getIntent().getStringExtra("filename");
position = getIntent().getIntExtra("pos", 0);
progressBar.setVisibility(View.VISIBLE);
StringRequest request = new StringRequest(URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("CODE", response);
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
TrendingData users = gson.fromJson(response, TrendingData.class);
data = users.getData();
adapter = new TrendingViewPagerAdapter(context, data);
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(1);
viewPager.setCurrentItem(position);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(TrendingSlideActivity.this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(request);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i1) {
}
#Override
public void onPageSelected(int i) {
currentImage = viewPager.getCurrentItem();
final String fileName1 = data.get(currentImage).getFileName();
Toast.makeText(TrendingSlideActivity.this, "===========" + fileName1, Toast.LENGTH_SHORT).show();
final String url2 = "API" + fileName1;
new LoadImage(TrendingSlideActivity.this).execute(url2);
shareIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onShareItem(shareImage);
}
});
downloadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveImageToGallery(shareImage);
}
});
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
}
private static class LoadImage extends AsyncTask<String, Integer, Drawable> {
private WeakReference<TrendingSlideActivity> activityWeakReference;
LoadImage(TrendingSlideActivity context) {
activityWeakReference = new WeakReference<>(context);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Drawable doInBackground(String... strings) {
Bitmap bmp = null;
try {
HttpURLConnection connection = (HttpURLConnection) new URL(strings[0]).openConnection();
connection.connect();
InputStream input = connection.getInputStream();
bmp = BitmapFactory.decodeStream(input);
} catch (IOException e) {
e.printStackTrace();
}
return new BitmapDrawable(bmp);
}
#Override
protected void onPostExecute(Drawable result) {
TrendingSlideActivity activity = activityWeakReference.get();
if (activity == null) return;
activity.shareImage = new ImageView(activity);
//Add image to ImageView
activity.shareImage.setImageDrawable(result);
}
}
public void onShareItem(View v) {
// Get access to bitmap image from view
// Get access to the URI for the bitmap
Uri bmpUri = getLocalBitmapUri((ImageView) v);
if (bmpUri != null) {
// Construct a ShareIntent with link to image
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
shareIntent.setType("image/*");
// Launch sharing dialog for image
context.startActivity(Intent.createChooser(shareIntent, "Share TrendingData"));
} else {
// ...sharing failed, handle error
}
}
public Uri getLocalBitmapUri(ImageView imageView) {
// Extract Bitmap from ImageView drawable
Drawable drawable = imageView.getDrawable();
Bitmap bmp;
if (drawable instanceof BitmapDrawable) {
bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
} else {
return null;
}
// Store image to default external storage directory
Uri bmpUri = null;
try {
// Use methods on Context to access package-specific directories on external storage.
// This way, you don't need to request external read/write permission.
File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "share_image_" + System.currentTimeMillis() + ".png");
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
// **Warning:** This will fail for API >= 24, use a FileProvider as shown below instead.
bmpUri = Uri.fromFile(file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}
public boolean isStoragePermissionGranted() {
String TAG = "Storage Permission";
if (Build.VERSION.SDK_INT >= 23) {
if (this.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "Permission is granted");
return true;
} else {
Log.i(TAG, "Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
} else { //permission is automatically granted on sdk<23 upon installation
Log.i(TAG, "Permission is granted");
return true;
}
}
public void saveImageToGallery(ImageView iv) {
// //to get the image from the ImageView (say iv)
// BitmapDrawable draw = (BitmapDrawable) iv.getDrawable();
// Bitmap bitmap = draw.getBitmap();
if (iv != null) {
Drawable drawable = iv.getDrawable();
Bitmap bmp = null;
if (drawable instanceof BitmapDrawable) {
bmp = ((BitmapDrawable) iv.getDrawable()).getBitmap();
} else {
}
FileOutputStream outStream = null;
String sdCard = Environment.getExternalStorageDirectory().toString();
if (isStoragePermissionGranted()) {
File dir = new File(sdCard, "/GalleryApp");
if (!dir.exists()) {
dir.mkdirs();
}
try {
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
assert bmp != null;
bmp.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
Toast.makeText(TrendingSlideActivity.this, "Saved", Toast.LENGTH_SHORT).show();
Log.i("TAAAAAAAAAAAAG", "onPictureTaken - wrote to " + outFile.getAbsolutePath());
String filePath = outFile.getPath();
MediaScannerConnection.scanFile(this,
new String[]{filePath}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}else {
Toast.makeText(TrendingSlideActivity.this,"Please Wait Image is Loading...",Toast.LENGTH_SHORT).show();
}
}
}
UPDATED ANSWER:
Reason why it isn't working is that you're setting image view inside onPageSelected() , and that method is not called for the first page, it's activated just after swiping.
Solution for this is move the entire code from onPageSelected() into function selectImage(int position) and call that function inside onPageSelected() as
selectImage(i).
This would be an improved version for code above, and will do the same as before, but now it's possible to set default state for the first view by calling
selectImage(0) after viewPager.setCurrentItem(position)
based on VR View sample code tutorial, how to get panorama image from url or database ?
Since the sample tutorial is load default image load assets manager and i want to know how to load it from internet/URL image link.
here my first activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_kuliner);
//INITIALIZE VIEWS
nama_kul = (TextView) findViewById(R.id.nameDetail_kul);
lokasi_kul = (TextView) findViewById(R.id.lokasi_kul);
desclong_kul = (TextView) findViewById(R.id.desclong_kul);
image_kul = (ImageView) findViewById(R.id.imageDetail_kul);
//RECEIVE DATA
Intent intent=this.getIntent();
String name_kul=intent.getExtras().getString("NAME_KEY");
String lokas_kul=intent.getExtras().getString("LOKASI_KEY");
final String descshor_kul=intent.getExtras().getString("DESCSHORT_KEY");
String desclon_kul=intent.getExtras().getString("DESCLONG_KEY");
final String images_kul=intent.getExtras().getString("IMAGE_KEY");
//BIND DATA
nama_kul.setText(name_kul);
lokasi_kul.setText(lokas_kul);
desclong_kul.setText(desclon_kul);
Glide.with(this).load(images_kul).into(image_kul);
//Intent to 2nd activity
detail2ButtonStart = (ImageButton) findViewById(R.id.detail2_but);
detail2ButtonStart.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent intent = new Intent(detail_kuliner.this, detail2_kuliner.class);
intent.putExtra("DESCSHORT2_KEY",descshor_kul);
intent.putExtra("IMAGE2_KEY",images_kul);
//open activity
startActivity(intent);
}
});
and this is my second activity
public class detail2_kuliner extends AppCompatActivity {
private static final String TAG = detail2_kuliner.class.getSimpleName();
private VrPanoramaView panoWidgetView;
public boolean loadImageSuccessful;
private Uri fileUri;
private Options panoOptions = new Options();
private ImageLoaderTask backgroundImageLoaderTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail2_kuliner);
panoWidgetView = (VrPanoramaView) findViewById(R.id.pano_view);
panoWidgetView.setEventListener(new ActivityEventListener());
handleIntent(getIntent());
}
#Override
protected void onNewIntent(Intent intent) {
Log.i(TAG, this.hashCode() + ".onNewIntent()");
setIntent(intent);
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_VIEW.equals(intent.getAction())) {
Log.i(TAG, "ACTION_VIEW Intent recieved");
fileUri = intent.getData();
if (fileUri == null) {
Log.w(TAG, "No data uri specified. Use \"-d /path/filename\".");
} else {
Log.i(TAG, "Using file " + fileUri.toString());
}
panoOptions.inputType = intent.getIntExtra("inputType", Options.TYPE_MONO);
Log.i(TAG, "Options.inputType = " + panoOptions.inputType);
} else {
Log.i(TAG, "Intent is not ACTION_VIEW. Using default pano image.");
fileUri = null;
panoOptions.inputType = Options.TYPE_MONO;
}
if (backgroundImageLoaderTask != null) {
backgroundImageLoaderTask.cancel(true);
}
backgroundImageLoaderTask = new ImageLoaderTask();
backgroundImageLoaderTask.execute(Pair.create(fileUri, panoOptions));
}
#Override
protected void onPause() {
panoWidgetView.pauseRendering();
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
panoWidgetView.resumeRendering();
}
#Override
protected void onDestroy() {
panoWidgetView.shutdown();
if (backgroundImageLoaderTask != null) {
backgroundImageLoaderTask.cancel(true);
}
super.onDestroy();
}
class ImageLoaderTask extends AsyncTask<Pair<Uri, Options>, Void, Boolean> {
#Override
protected Boolean doInBackground(Pair<Uri, Options>... fileInformation) {
Options panoOptions = null;
InputStream istr = null;
if (fileInformation == null || fileInformation.length < 1
|| fileInformation[0] == null || fileInformation[0].first == null) {
AssetManager assetManager = getAssets();
try {
istr = new URL("http://SOME URL IMAGE").openStream(); //How to get SOME URL IMAGE from intent sent at first activity
panoOptions = new Options();
panoOptions.inputType = Options.TYPE_STEREO_OVER_UNDER;
} catch (IOException e) {
Log.e(TAG, "Could not decode default bitmap: " + e);
return false;
}
} else {
try {
istr = new FileInputStream(new File(fileInformation[0].first.getPath()));
panoOptions = fileInformation[0].second;
} catch (IOException e) {
Log.e(TAG, "Could not load file: " + e);
return false;
}
}
panoWidgetView.loadImageFromBitmap(BitmapFactory.decodeStream(istr), panoOptions);
try {
istr.close();
} catch (IOException e) {
Log.e(TAG, "Could not close input stream: " + e);
}
return true;
}
}
}
so i want to adding the VR View to second activity with the data that came with the intent, the data is from the database that sent by json format, based on this tutorial VR View for android can i put the data with the intent from first activity to second activity (SOME URL IMAGE)?
thank you for the help
You can use Picasso, Glide or imageloader: example below:
Picasso.with(mContext)
.load("yoururl")
.config(Bitmap.Config.RGB_565)
.error(R.drawable.blank)
.centerInside()
.into(imageView);
Actually You can't get live from server, first you need to download from serve into your project and then use it from where you save that image in sdcard or internal folder.thanks..
I have three activities: MainActivity, DownloadServiceTest, ViewDetailDownload. Now, i want download files using Service (IntentService).
Corporeality :
MainActivity have buttons. When i click button_1 it to start a service (DownloadServiceTestextends IntentSerive ) perform download and I want when click button_2 it will startup ViewDetailDownload and update progress.
But when i start ViewDetailDownload i don't receive data(percent download, speed ) from DownloadServiceTest
My code here.
class MainActivity :
public class MainActivity extends Activity implements OnClickListener {
private final String LINK_MP3 = "http://data.chiasenhac.com/downloads/1471/5/1470643-c6ef1a26/320/Vo%20Hinh%20Trong%20Tim%20Em%20-%20Mr%20Siro%20%5BMP3%20320kbps%5D.mp3";
Activity activity;
Button btnDownload_1, btnDownload_2, btnDownload_3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_control);
activity = MainActivity.this;
btnDownload_1 = (Button) findViewById(R.id.btn_startdownload_1);
btnDownload_2 = (Button) findViewById(R.id.btn_startdownload_2);
btnDownload_3 = (Button) findViewById(R.id.btn_startdownload_3);
btnDownload_1.setOnClickListener(this);
btnDownload_2.setOnClickListener(this);
btnDownload_3.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btn_startdownload_1) {
Intent intent = new Intent(activity, DownloadServiceTest.class);
intent.putExtra(DownloadServiceTest.REQUEST_STRING, LINK_MP3);
startService(intent);
}
if (v.getId() == R.id.btn_startdownload_2) {
Intent intent = new Intent(MainActivity.this,
ViewDetailDownload.class);
startActivity(intent);
}
}
}
class DownloadServiceTest :
public class DownloadServiceTest extends IntentService {
public static final String REQUEST_STRING = "REQUEST_LINK";
public static final String PROGRESS_UPDATE_ACTION = DownloadServiceTest.class
.getName() + ".progress_update";
private LocalBroadcastManager mLocalBroadcastManager;
private String mUrl_mp3;
public DownloadServiceTest(String name) {
super(name);
}
public DownloadServiceTest() {
super("DownloadService");
}
#Override
public void onCreate() {
mLocalBroadcastManager = LocalBroadcastManager
.getInstance(DownloadServiceTest.this);
super.onCreate();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
protected void onHandleIntent(Intent intent) {
mUrl_mp3 = intent.getStringExtra(REQUEST_STRING);
DownloadTask task = new DownloadTask();
if (mUrl_mp3 != null) {
task.execute(mUrl_mp3);
}
}
private void onProgressUpdateReceiver(int progress, int speed) {
Intent intent = new Intent();
intent.setAction(PROGRESS_UPDATE_ACTION);
intent.putExtra("progress", progress);
intent.putExtra("speed", speed);
Log.i("", "abc onProgressUpdateReceiver progress "+progress);
Log.i("", "abc onProgressUpdateReceiver speed "+speed);
mLocalBroadcastManager.sendBroadcast(intent);
}
private class DownloadTask extends AsyncTask<String, Void, Void> {
String filename;
int mProgress;
int mSpeed;
private int checkExist;
File SDCardRoot;
private FileOutputStream fileOut;
private InputStream fileIn;
File file;
#Override
protected void onPreExecute() {
filename = mUrl_mp3.substring(mUrl_mp3.lastIndexOf("/") + 1);
try {
filename = URLDecoder.decode(filename, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
super.onPreExecute();
}
#Override
protected Void doInBackground(String... params) {
int contentLengh = 0;
try {
URL url = new URL(params[0]);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
if (HttpURLConnection.HTTP_OK == urlConnection
.getResponseCode()) {
contentLengh = urlConnection.getContentLength();
Log.i("", "abc " + contentLengh);
fileIn = urlConnection.getInputStream();
SDCardRoot = Environment.getExternalStorageDirectory();
file = new File(Environment.getExternalStorageDirectory()
+ "/Blog Radio");
boolean success = true;
if (!file.exists()) {
success = file.mkdir();
}
String getTypeFile = filename.substring(filename
.indexOf("."));
if (success) {
file = new File(SDCardRoot.getAbsolutePath()
+ "/Blog Radio/" + filename);
if (file.exists()) {
checkExist++;
String PATH = Environment
.getExternalStorageDirectory()
+ "/Blog Radio/"
+ filename.replace(filename
.substring(filename.indexOf(".")),
"")
+ "_"
+ checkExist
+ getTypeFile;
file = new File(PATH);
}
} else {
file = new File(SDCardRoot.getAbsolutePath()
+ "/Blog Radio/" + filename);
if (file.exists()) {
checkExist++;
String PATH = Environment
.getExternalStorageDirectory()
+ "/Blog Radio/"
+ filename.replace(filename
.substring(filename.indexOf(".")),
"")
+ "_"
+ checkExist
+ getTypeFile;
file = new File(PATH);
}
}
fileOut = new FileOutputStream(file);
int downloadSize = 0;
byte[] buffer = new byte[8192];
long tempTotal = 0;
long startTime = System.currentTimeMillis();
int bufferLengh = 0;
while ((bufferLengh = fileIn.read(buffer)) != -1) {
long interval = System.currentTimeMillis() - startTime;
if (isCancelled()) {
fileIn.close();
}
if (contentLengh > 0) {
downloadSize += bufferLengh;
tempTotal += bufferLengh;
mProgress = (int) ((downloadSize * 100L) / contentLengh);
if (interval >= 1000) {
Log.i("now = ", String.valueOf(System
.currentTimeMillis()));
Log.i("last = ", String.valueOf(startTime));
Log.i("currentDump = ",
String.valueOf(tempTotal));
mSpeed = (int) (tempTotal * 1000 / interval / 1024);
startTime = System.currentTimeMillis();
tempTotal = 0;
}
fileOut.write(buffer, 0, bufferLengh);
onProgressUpdateReceiver(mProgress, mSpeed);
}
}
fileOut.flush();
fileOut.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
}
class ViewDetailDownload :
public class ViewDetailDownload extends Activity {
TextView tv_Title, tv_Info;
ProgressBar progressBar;
ImageView img;
MyRequestReceiver receiver;
IntentFilter intentToReceiveFilter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.download_service_layout);
img = (ImageView) findViewById(R.id.img);
tv_Title = (TextView) findViewById(R.id.title);
tv_Info = (TextView) findViewById(R.id.info);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
intentToReceiveFilter = new IntentFilter();
intentToReceiveFilter
.addAction(DownloadServiceTest.PROGRESS_UPDATE_ACTION);
receiver = new MyRequestReceiver();
}
#Override
protected void onResume() {
registerReceiver();
super.onResume();
}
private void registerReceiver() {
this.registerReceiver(receiver, intentToReceiveFilter);
}
#Override
protected void onPause() {
unregisterReceiver();
super.onPause();
}
protected void onProgressUpdate(int progress, int speed) {
progressBar.setProgress(progress);
tv_Info.setText(speed);
}
protected void onProgressUpdateOneShot(int progresses, int speeds) {
int progress = progresses;
int speed = speeds;
onProgressUpdate(progress, speed);
}
private void unregisterReceiver() {
this.unregisterReceiver(receiver);
}
public class MyRequestReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(
DownloadServiceTest.PROGRESS_UPDATE_ACTION)) {
int progresses = intent.getIntExtra("progress", -1);
int speeds = intent.getIntExtra("speed", -1);
Log.i("", "abc progresses onReceive" + progresses);
Log.i("", "abc speeds onReceive" + speeds);
onProgressUpdateOneShot(progresses, speeds);
}
}
}
}
I need help !
If you know... please give example.
Thanks all
add this in DownloadServiceTest.java in onCreate() method.
Intent iin= getIntent();
Bundle b = iin.getExtras();
if(b!=null)
{
String mname =(String) b.getString("LINK_MP3");
}
Now you can use this string mname anywhere in your DownloadServiceTest
I am new to opencv and trying to create a simple application which will open the camera and capture the photo. I have implemented the CvCameraViewListener interface for this purpose. My code looks as follows:
MainActivity.java
public class MainActivity extends Activity implements CvCameraViewListener2{
public String TAG = "MainActivity";
private int mCameraIndex;
private Mat mBgr;
private Boolean mIsPhotoPending;
private CameraBridgeViewBase mCameraView;
private static final String STATE_CAMERA_INDEX = "cameraIndex";
private Boolean mIsMenuLocked;
private CameraBridgeViewBase.CvCameraViewFrame inputFrame;
int screen_w, screen_h;
private Mat gray, frame, lowRes;
static {
if (!OpenCVLoader.initDebug()) {
Log.v("MainActivity","Loading of OpenCv Failed");
}
}
private BaseLoaderCallback mLoaderCallBack = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
switch(status) {
case LoaderCallbackInterface.SUCCESS:
{
String TAG = "";
Log.i(TAG, "Open CV successfully loaded");
mCameraView.enableView();
mBgr = new Mat();
}break;
default:
{
super.onManagerConnected(status);
}break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
if(savedInstanceState != null)
{
mCameraIndex = savedInstanceState.getInt(STATE_CAMERA_INDEX, 0);
}
else
{
mCameraIndex = 0;
}
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD)
{
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
Camera.getCameraInfo(mCameraIndex, cameraInfo);
}
mCameraView = new NativeCameraView(this, mCameraIndex);
//mCameraView.setCvCameraViewListener(this);
findViewById(R.id.HelloOpenCvView);
//mOpenCvCameraView = new JavaCameraView(this,-1);
setContentView(mCameraView);
}
#Override
public void onResume() {
super.onResume();
mLoaderCallBack.onManagerConnected(LoaderCallbackInterface.SUCCESS);
// OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_11, this, mLoaderCallBack);
mIsMenuLocked = false;
}
#Override
public void onPause() {
super.onPause();
if(mCameraView != null)
mCameraView.disableView();
}
public void onDestroy() {
super.onDestroy();
if(mCameraView != null)
mCameraView.disableView();
}
#Override
public void onCameraViewStarted(int width, int height) {
}
#Override
public void onCameraViewStopped() {
}
#Override
public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
Mat rgba = inputFrame.rgba();
if(mIsPhotoPending)
{
takePhoto(rgba);
}
return rgba;
}
private void takePhoto(Mat rgba)
{
//get the path of the photo
final long currentTimeMillis = System.currentTimeMillis();
final String appName = getString(R.string.app_name);
final String galleryPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
final String albumPath = galleryPath + "/" + appName;
final String photoPath = albumPath + "/" + currentTimeMillis + ".png";
final ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, photoPath);
values.put(MediaStore.Images.Media.MIME_TYPE, showActivity.PHOTO_MIME_TYPE);
values.put(MediaStore.Images.Media.TITLE, appName);
values.put(MediaStore.Images.Media.DESCRIPTION, appName);
values.put(MediaStore.Images.Media.DATE_TAKEN, currentTimeMillis);
//check if the album directory exists
File album = new File(albumPath);
if(!album.isDirectory() && !album.mkdirs())
{
Log.e(TAG,"Failed to create album directory at" + albumPath);
return;
}
//try to create the photo
Imgproc.cvtColor(rgba, mBgr, Imgproc.COLOR_RGBA2BGR, 3);
if(!Highgui.imwrite(photoPath, mBgr))
{
Log.d(TAG,"Photo saved successfully");
onTakePhotoFailed();
}
Log.d(TAG, "Photo saved successfully");
//insert photo in mediastore
Uri uri;
final Intent intent = new Intent();
try
{
uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
intent.putExtra(showActivity.EXTRA_PHOTO_URI, uri);
}catch(final Exception e)
{
Log.e(TAG, "Failed to insert photo into media store");
e.printStackTrace();
}
//delete the photo because insertion failed
File photo = new File(photoPath);
if(!photo.delete())
{
Log.e(TAG, "Failed to delete non-inserted photo");
}
onTakePhotoFailed();
intent.putExtra(showActivity.EXTRA_PHOTO_DATA_PATH, photoPath);
startActivity(intent);
return;
}
private void onTakePhotoFailed()
{
mIsMenuLocked = false;
//display error message
final String errorMessage = getString(R.string.photo_error_message);
runOnUiThread(new Runnable()
{
#Override
public void run()
{
Toast.makeText(MainActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
}
});
}
My problem is that the onCameraFrame() method is never being called which in turn does not call the takePhoto() method and I am not able to capture the photo. I have called the takePhoto() method within the onCamerFrame() method as the method will take the Mat details. Kindly let me know where did I go wrong.
Any help would be highly appreciated.
You've commented out the camera listener. That's why onCameraFrame() is never called. Uncomment this in onCreate():
mCameraView.setCvCameraViewListener(this);
You may need to implement the PictureCallBack interface your activity. Refer the Tutorial 3 - Camera Control App.
I wrote a code which takes picture from android device and then upload it on server.Can also upload pic from gallery. Uploading from gallery works perfectly.It is able to intent to mobile camera when clicked on capture button but when i return i didn't got any image and when i checked the gallery no image was captured.
Got menifest permission also
android.permission.WRITE_EXTERNAL_STORAGE"
android.permission.READ_EXTERNAL_STORAGE"
android.permission.CAMERA"
This is code in my Fragments onCreateView() class:
mTakePhoto = (Button) rootView.findViewById(R.id.take_photo);
mselectPhoto = (Button) rootView.findViewById(R.id.select_photo);
mImageView = (ImageView) rootView.findViewById(R.id.imageview);
mTakePhoto.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,
TAKE_PICTURE);
}
});
mselectPhoto.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i,
IMAGE_PICKER_SELECT);
}
});
In the above code i think intents works perfectly
In bellow code, the (requestCode == IMAGE_PICKER_SELECT) condition works perfectly. But it seems like i didn't get any data when i took PICTURE
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == IMAGE_PICKER_SELECT
&& resultCode == Activity.RESULT_OK) {
Bitmap bitmap = getBitmapFromCameraData(data, getActivity());
int nh = (int) (bitmap.getHeight() * (512.0 / bitmap.getWidth()));
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 512, nh, true);
mImageView.setImageBitmap(scaled);
new UploadTask().execute(bitmap);
}
if (requestCode == TAKE_PICTURE && resultCode == Activity.RESULT_OK
&& data != null) {
// get bundle
Bundle extras = data.getExtras();
// get bitmap
cameraBitmap = (Bitmap) extras.get("data");
int nh = (int) (cameraBitmap.getHeight() * (512.0 / cameraBitmap
.getWidth()));
Bitmap scaled = Bitmap.createScaledBitmap(cameraBitmap, 512, nh,
true);
mImageView.setImageBitmap(scaled);
new UploadTask().execute(cameraBitmap);
// setPic();
}
}
I m also giving the Code of my Multipartentity class
public class MultipartEntity implements HttpEntity {
enter code here
private String boundary = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
boolean isSetLast = false;
boolean isSetFirst = false;
public MultipartEntity() {
this.boundary = System.currentTimeMillis() + "";
}
public void writeFirstBoundaryIfNeeds(){
if(!isSetFirst){
try {
out.write(("--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
}
}
isSetFirst = true;
}
public void writeLastBoundaryIfNeeds() {
if(isSetLast){
return ;
}
try {
out.write(("\r\n--" + boundary + "--\r\n").getBytes());
} catch (final IOException e) {
}
isSetLast = true;
}
public void addPart(final String key, final String value) {
writeFirstBoundaryIfNeeds();
try {
out.write(("Content-Disposition: form-data; name=\"" +key+"\"\r\n").getBytes());
out.write("Content-Type: text/plain; charset=UTF-8\r\n".getBytes());
out.write("Content-Transfer-Encoding: 8bit\r\n\r\n".getBytes());
out.write(value.getBytes());
out.write(("\r\n--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
}
public void addPart(final String key, final String fileName, final InputStream fin){
addPart(key, fileName, fin, "application/octet-stream");
}
public void addPart(final String key, final String fileName, final InputStream fin, String type){
writeFirstBoundaryIfNeeds();
try {
type = "Content-Type: "+type+"\r\n";
out.write(("Content-Disposition: form-data; name=\""+ key+"\"; filename=\"" + fileName + "\"\r\n").getBytes());
out.write(type.getBytes());
out.write("Content-Transfer-Encoding: binary\r\n\r\n".getBytes());
final byte[] tmp = new byte[4096];
int l = 0;
while ((l = fin.read(tmp)) != -1) {
out.write(tmp, 0, l);
}
out.flush();
} catch (final IOException e) {
} finally {
try {
fin.close();
} catch (final IOException e) {
}
}
}
public void addPart(final String key, final File value) {
try {
addPart(key, value.getName(), new FileInputStream(value));
} catch (final FileNotFoundException e) {
}
}
#Override
public long getContentLength() {
writeLastBoundaryIfNeeds();
return out.toByteArray().length;
}
#Override
public Header getContentType() {
return new BasicHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
}
#Override
public boolean isChunked() {
return false;
}
#Override
public boolean isRepeatable() {
return false;
}
#Override
public boolean isStreaming() {
return false;
}
#Override
public void writeTo(final OutputStream outstream) throws IOException {
outstream.write(out.toByteArray());
}
#Override
public Header getContentEncoding() {
return null;
}
#Override
public void consumeContent() throws IOException,
UnsupportedOperationException {
if (isStreaming()) {
throw new UnsupportedOperationException(
"Streaming entity does not implement #consumeContent()");
}
}
#Override
public InputStream getContent() throws IOException,
UnsupportedOperationException {
return new ByteArrayInputStream(out.toByteArray());
}
}
I m stuck for almost the fullday. Help!!
Open your camera with below code and check with it:
private Uri mImageCaptureUri;
mImageCaptureUri = Uri.parse("content://YOUR PACKAGE NAME/");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,mImageCaptureUri);
intent.putExtra("return-data", true);
startActivityForResult(intent,TAKE_PICTURE);
I created a method to call whn button is clicked
mTakePhoto.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
takePhoto();
}
});
method to intent and getTempFile() to keel temporary file..
private void takePhoto(){
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(getActivity())) );
startActivityForResult(intent, TAKE_PICTURE);
}
private File getTempFile(Context context){
final File path = new File( Environment.getExternalStorageDirectory(), context.getPackageName() );
if(!path.exists()){
path.mkdir();
}
return new File(path, "image.tmp");
}
this link help me
http://www.tutorialforandroid.com/2010/10/take-picture-in-android-with.html