unable to share image using intent - URI null - java

Im using a grid view to represent all the images/photos, after the user selection ImageView activity is executed and then the following code is to share that selected image.
Im getting bit confuse i think im missing something hence URI is showing null value.
here is the whole code if necessary!!
public class Full_image extends ActionBarActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.full_image);
// get intent data
Intent i = getIntent();
// Selected image id
int position = i.getExtras().getInt("id");
ImageAdapt imageAdapter = new ImageAdapt(this);
ImageView imageView = (ImageView) findViewById(R.id.full_image_view);
imageView.setImageResource(imageAdapter.mThumbIds[position]);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_share) {
return true;
}
// Handle item selection
ImageView image = (ImageView) findViewById(R.id.full_image_view);
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap(); //file to be saved as per user selection
File sd = Environment.getExternalStorageDirectory();
String fileName = "test.png"; //saved as png file
File dest = new File(sd, fileName);
try {
FileOutputStream out;
out = new FileOutputStream(dest);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
switch (item.getItemId()) {
case R.id.action_share:
Uri uri = Uri.fromFile(dest);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.setType("image/png");
startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.action_share))); //shared via Intent
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}

I think this code will work for you, test file you are creating doesn't have write permission we need to tell explicitly to make it writable rest is same.
package com.desimeme.jai.desimeme;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Full_image extends ActionBarActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.full_image);
// get intent data
Intent i = getIntent();
// Selected image id
int position = i.getExtras().getInt("id");
ImageAdapt imageAdapter = new ImageAdapt(this);
ImageView imageView = (ImageView) findViewById(R.id.full_image_view);
imageView.setImageResource(imageAdapter.mThumbIds[position]);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
// if (id == R.id.action_share) {
// return true;
// }
switch (item.getItemId()) {
case R.id.action_share:
// Handle item selection
ImageView image = (ImageView) findViewById(R.id.full_image_view);
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap(); //file to be saved as per user selection
if (isExternalStorageWritable()) {
String sd = Environment.getExternalStorageDirectory().getAbsolutePath();
File ssd = new File(sd, "share");
if (!ssd.exists())
ssd.mkdirs();
String fileName = "test"; //saved as png file
File dest = new File(ssd, fileName + ".png");
FileOutputStream out = null;
if (dest.canWrite()) {
dest.setWritable(true);
}
try {
out = new FileOutputStream(dest);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
// PNG is a lossless format, the compression factor (100) is ignored
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Uri uri = Uri.fromFile(dest);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("*/*");
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.action_share))); //shared via Intent
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}

Related

what code would I need to add to be able to use this App on phone? [duplicate]

This question already has an answer here:
NetworkOnMainThreadException with AsyncTask
(1 answer)
Closed 6 years ago.
Would some one tell where and what code I would need to add to my Java file to make my app work using NetworkOnMainThreadException because I am really struggling. App crashed when it starts saying the app has stopped working.
package com.airrocketapps.matthillman.guessthecelebrity;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainActivity extends Activity {
ArrayList<String> celebURLs = new ArrayList<String>();
ArrayList<String> celebNames = new ArrayList<String>();
int chosenCeleb = 0;
int locationOfCorrectAnswer = 0;
String[] answers = new String[4];
ImageView imageView;
Button button0;
Button button1;
Button button2;
Button button3;
public void celebChosen(View view) {
if (view.getTag().toString().equals(Integer.toString(locationOfCorrectAnswer))) {
Toast.makeText(getApplicationContext(), "Correct!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Wrong! It was " + celebNames.get(chosenCeleb), Toast.LENGTH_LONG).show();
}
createNewQuestion();
}
public class ImageDownloader extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream inputStream = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(inputStream);
return myBitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection)url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
button0 = (Button) findViewById(R.id.button);
button1 = (Button) findViewById(R.id.button2);
button2 = (Button) findViewById(R.id.button3);
button3 = (Button) findViewById(R.id.button4);
DownloadTask task = new DownloadTask();
String result = null;
try {
result = task.execute("http://www.posh24.com/celebrities").get();
String[] splitResult = result.split("<div class=\"sidebarContainer\">");
Pattern p = Pattern.compile("<img src=\"(.*?)\"");
Matcher m = p.matcher(splitResult[0]);
while (m.find()) {
celebURLs.add(m.group(1));
}
p = Pattern.compile("alt=\"(.*?)\"");
m = p.matcher(splitResult[0]);
while (m.find()) {
celebNames.add(m.group(1));
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
createNewQuestion();
}
public void createNewQuestion() {
Random random = new Random();
chosenCeleb = random.nextInt(celebURLs.size());
ImageDownloader imageTask = new ImageDownloader();
Bitmap celebImage;
try {
celebImage = imageTask.execute(celebURLs.get(chosenCeleb)).get();
imageView.setImageBitmap(celebImage);
locationOfCorrectAnswer = random.nextInt(4);
int incorrectAnswerLocation;
for (int i=0; i<4; i++) {
if (i == locationOfCorrectAnswer) {
answers[i] = celebNames.get(chosenCeleb);
} else {
incorrectAnswerLocation = random.nextInt(celebURLs.size());
while (incorrectAnswerLocation == chosenCeleb) {
incorrectAnswerLocation = random.nextInt(celebURLs.size());
}
answers[i] = celebNames.get(incorrectAnswerLocation);
}
}
button0.setText(answers[0]);
button1.setText(answers[1]);
button2.setText(answers[2]);
button3.setText(answers[3]);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Everything looks fine in your code.
Make sure you have active internet connection in your mobile where you are trying to run this application.
If you are using Internet, then don't forget to add this to your AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
More help: https://stackoverflow.com/a/6343299/7004388

How can I get my app to read external text file correctly? Only showing weird characters and diamonds

I'm working on my first app. Got everything set up and working correctly, except displaying a random quote from a text file. Clicking the button shows weird characters (diamonds, question marks, etc) and not the actual text except for the placeholder off and on.
I followed the github source correctly as far as I know.
package drewstephensdesigns.com.dailyquotes;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.ShareActionProvider;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
private TextView mTextView;
private String STATE_DQ;
private static String TEXT_VALUE = "";
private ShareActionProvider mShareActionProvider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.dq_view);
//Adds scrolling to the TextView
mTextView.setMovementMethod(ScrollingMovementMethod.getInstance());
}
//Code to save state on orientation change
#Override
public void onSaveInstanceState(Bundle outState) {
mTextView = (TextView) findViewById(R.id.dq_view);
outState.putString(STATE_DQ, mTextView.getText().toString());
super.onSaveInstanceState(outState);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mTextView = (TextView) findViewById(R.id.dq_view);
mTextView.setText(STATE_DQ);
}
private AssetManager getApplicationAssets() {
// open random quotes file
AssetManager assetmanager = getAssets();
return assetmanager;
}
private String getAssetPath(AssetManager assetmanager) {
String[] dirs = null;
String[] files = null;
String path = null;
try {
dirs = assetmanager.list(""); //get list of files / dirs from the project 'assets' directory
files = assetmanager.list(dirs[2]); //Directories are listed in alphabetical order so fetch the 'txt' directory
path = dirs[2].toString() + "/" + files[0].toString(); //construct the path (there is only 1 file in the dir)
} catch (IOException e) {
e.printStackTrace();
}
return path;
}
// Get the path for the random quote file
private InputStreamReader getQuoteReader() throws IOException {
// open random quotes file
AssetManager assets = getApplicationAssets();
String path = null;
path = getAssetPath(assets);
InputStream inputStream = null;
try {
inputStream = assets.open(path);
Log.v("QotD path", path);
} catch (IOException e) {
e.printStackTrace();
}
InputStreamReader textReader = new InputStreamReader(inputStream);
return textReader;
}
// Get the total number of lines in the file
private int getFileLineCount(InputStreamReader textReader) {
BufferedReader br = new BufferedReader(textReader);
int lineCount = 0;
try {
while ((br.readLine()) != null) {
lineCount++;
}
} catch (IOException e) {
e.printStackTrace();
}
return lineCount; // total number of lines in the text file
}
// Return a random line number from where to get the
// corresponding quote string
private int getRandomLineNumber(int totalLines) {
Random rand = new Random();
return rand.nextInt(totalLines);
}
private String getRandomQuote(int lineToFetch)
throws IOException {
//1. get path
AssetManager assets = getApplicationAssets();
String path = null;
path = getAssetPath(assets);
//2. open assets
InputStream stream = assets.open(path);
InputStreamReader randomQuote = new InputStreamReader(stream);
//3. Get BufferedReader object
BufferedReader buf = new BufferedReader(randomQuote);
String quote = null;
String line = null;
int currLine = 0;
//4. Loop through using the new InputStreamReader until a match is found
while ((line = buf.readLine()) != null && currLine < lineToFetch) {
currLine++;
}
//Got the quote
quote = line;
//Clean up
randomQuote.close();
buf.close();
return quote;
}
// Set the EditText widget to display the new random quote
private void displayQuote(String quote) {
TextView quoteDisplay = (TextView) findViewById(R.id.dq_view);
TEXT_VALUE = quote;
quoteDisplay.setText(TEXT_VALUE);
}
// onClick handler for the button click
public void fetch_quote(View view) throws IOException {
// open random quotes file
InputStreamReader textReader = getQuoteReader();
final int totalLines = getFileLineCount(textReader);
int lineToFetch = 0;
String quote = null;
// We want to get the quote at the following line number
lineToFetch = getRandomLineNumber(totalLines);
quote = getRandomQuote(lineToFetch);
displayQuote(quote);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem shareItem = menu.findItem(R.id.menu_item_share);
mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(shareItem);
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(item.getItemId()){
case R.id.menu_item_share:
if(TEXT_VALUE == "") {
Toast.makeText(this, "Nothing to share! First generate a quote by clicking the button", Toast.LENGTH_SHORT).show();
} else {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, TEXT_VALUE);
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Thought you might like this interesting Quote");
startActivity(Intent.createChooser(shareIntent, "Share the quote via..."));
}
break;
case R.id.action_settings:
Toast.makeText(getApplicationContext(), "Settings not yet implemented", Toast.LENGTH_LONG).show();
break;
case R.id.action_about:
Intent aboutIntent = new Intent(this, AboutActivity.class);
startActivity(aboutIntent);
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
}
This is what I see:
I had a folder called "fonts" that was not being used. My code was looking for the assets folder with just the randomquote.txt file. Due to the extra folder in there, it was unable to locate the txt file. Deleted the folder since it wasn't being used, saved, boom and progress.

Trying to get a simple Camera application to work

I'm a beginner to Android app development. I'm getting the hang of it, and I've read a lot of tutorials, but I still can't get the camera to work. Basically what I want to do is take a picture, store the image internally within the app and then display that image to (later) be able to draw on it. I'm not worried about the drawing part at the moment because I'm still getting an error for SetOnClickListener...Here's the code.
import android.hardware.Camera;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create an instance of Camera
Camera mCamera = getCameraInstance();
// Create our Preview view and set it as the content of our activity.
CameraPreview mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
}
private Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null){
// Log.d("erre", "Error creating media file, check storage permissions: " +
// getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d("erra", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("erra", "Error accessing file: " + e.getMessage());
}
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/** A safe way to get an instance of the Camera object. */
public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
// Add a listener to the Capture button
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Camera mCamera = getCameraInstance();
// get an image from the camera
mCamera.takePicture(null, null, mPicture);
}
}
);
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
}
Simply move this part:
// Add a listener to the Capture button
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Camera mCamera = getCameraInstance();
// get an image from the camera
mCamera.takePicture(null, null, mPicture);
}
}
);
into your onCreate() function, at the end of it. Then it should work.
You need to find views / setup click events in the onCreate of Activities.

how to capture image from Camera in Android?

I have made an application to capture photos from the camera.
I have created two Activities: In Activity1 there is one Button which starts the camera wehen it is clicked. When the image is captured, it is passed to Activity2.
However, when I run the application and start the Activity1 (with the one Button) and I click on the button to start the camera it displays a pop up window showing the message "Unfortunately, camera has stopped". There are no errors in the log-cat or on the console.
Can anyone help me. Please. Thanks a lot.
You need only one Activity if you use startActiviyForResult():
Bello, a simple source code for take a picture from camera app, you need to start Activity with startActiviyForResult() and receive the intent from camera application.
Java source code:
package com.example.coursandroid_chp;
import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class MediaActivity extends Activity {
private static final String TAG = "MediaActivity";
private static final int REQUEST_IMAGE_CAPTURE = 1;
private static final int REQUEST_VIDEO_CAPTURE = 2;
private Button mCameraPhotoButton;
private Button mCameraVideoButton;
private ImageView mPhotoImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen_media);
mCameraPhotoButton = (Button) this.findViewById(R.id.screen_media_camera_photo_button);
mCameraVideoButton = (Button) this.findViewById(R.id.screen_media_camera_video_button);
mPhotoImageView = (ImageView) this.findViewById(R.id.screen_media_photo_imageview);
mCameraPhotoButton.setOnClickListener(onClickListener);
mCameraVideoButton.setOnClickListener(onClickListener);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.screen_media, menu);
return true;
}
private OnClickListener onClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.screen_media_camera_photo_button:
startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE), REQUEST_IMAGE_CAPTURE);
break;
case R.id.screen_media_camera_video_button:
startActivityForResult(new Intent(MediaStore.ACTION_VIDEO_CAPTURE), REQUEST_VIDEO_CAPTURE);
break;
}
}
};
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE) {
switch (resultCode) {
case RESULT_OK:
Log.v(TAG, "Picture taken! :)");
if (data != null) {
Bitmap bitmap = data.getParcelableExtra("data");
mPhotoImageView.setImageBitmap(bitmap);
}
break;
case RESULT_CANCELED:
Log.v(TAG, "Picture canceled! :(");
break;
}
} else if (requestCode == REQUEST_VIDEO_CAPTURE) {
switch (resultCode) {
case RESULT_OK:
Log.v(TAG, "Video taken! :)");
break;
case RESULT_CANCELED:
Log.v(TAG, "Video canceled! :(");
break;
}
}
}
}
Xml layout file
<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"
tools:context=".MediaActivity" >
<Button
android:id="#+id/screen_media_camera_photo_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="32dp"
android:text="Camera photo" />
<Button
android:id="#+id/screen_media_camera_video_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/screen_media_camera_photo_button"
android:layout_centerHorizontal="true"
android:layout_marginTop="28dp"
android:text="Camera video" />
<ImageView
android:id="#+id/screen_media_photo_imageview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/screen_media_camera_video_button"
android:layout_centerHorizontal="true"
android:layout_marginLeft="32dp"
android:layout_marginTop="57dp"
android:src="#drawable/ic_bitmap" />
</RelativeLayout>
Try the following code :
package com.example.sample1;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class CapturePhotoSample1 extends Activity implements OnClickListener
{
public static final int TAKE_PHOTO=1;
ImageView imageView=null;
private File folder;
String imageFileName=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_capture_photo_sample1);
Button button=(Button)this.findViewById(R.id.capture_button);
button.setOnClickListener(this);
button=null;
imageView=(ImageView)this.findViewById(R.id.image_view1);
folder = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES)+ "/sample1/");
if (!folder.exists()) {
folder.mkdir();
}
}
private void dispatchTakePictureIntent(int actionCode) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent,actionCode);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int id=v.getId();
if(id==R.id.capture_button)
this.dispatchTakePictureIntent(TAKE_PHOTO);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu1, menu);
return true;
}
public void handleCameraPhoto(Intent intent)
{
Bundle extras=intent.getExtras();
Bitmap bitmap=(Bitmap)extras.get("data");
this.imageView.setImageBitmap(bitmap);
if(this.isExternalStorageAvailable())
{
this.imageFileName="img_"+SDUtil.now(-1)+".png";
/*SDUtil.now() is our own library.It is for creating file name with respect to data and time.IF u copy the hole program means sdutil shows error.For that you write a logic for creating a file name. */
String path=folder+"/"+this.imageFileName;
FileOutputStream fos=null;
BufferedOutputStream bos=null;
try
{
fos=new FileOutputStream(path);
bos=new BufferedOutputStream(fos);
bitmap.compress(Bitmap.CompressFormat.PNG, 40, bos);
}
catch(Exception ex)
{
ex.printStackTrace();
}
if(bos!=null)
{
try
{
bos.flush();
//bos.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
if(bos!=null)
{
try
{
bos.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
if(fos!=null)
{
try
{
fos.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
bos=null;
fos=null;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==Activity.RESULT_OK)
{
if(requestCode==TAKE_PHOTO)
{
handleCameraPhoto(data);
}
}
}
private boolean isExternalStorageAvailable() {
StatFs stat = new StatFs(Environment.getExternalStorageDirectory()
.getPath());
double sdAvailSize = (double) stat.getAvailableBlocks()
* (double) stat.getBlockSize();
// One binary gigabyte equals 1,073,741,824 bytes.
double mbAvailable = sdAvailSize / 1048576;
String state = Environment.getExternalStorageState();
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Something else is wrong. It may be one of many other states, but
// all we need
// to know is we can neither read nor write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
if (mExternalStorageAvailable == true
&& mExternalStorageWriteable == true && mbAvailable > 10) {
return true;
} else {
return false;
}
}
}
make sure to add permissions
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
if that doesn't fix youre problem than u should show us youre code
check below code in your activity
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
//Check that request code matches ours:
if (requestCode == CAPTURE_IMAGE_THUMBNAIL_ACTIVITY_REQUEST_CODE)
{ //Check if your application folder exists in the external storage, if not create it:
your code should be here.....
//Check if data in not null and extract the Bitmap:
if (data != null)
{
String filename = "image";
String fileNameExtension = ".jpg";
File sdCard = Environment.getExternalStorageDirectory();
String imageStorageFolder = File.separator+"Your application Folder"+File.separator;
File destinationFile = new File(sdCard, imageStorageFolder + filename + fileNameExtension);
Log.d(TAG, "the destination for image file is: " + destinationFile );
if (data.getExtras() != null)
{
Bitmap bitmap = (Bitmap)data.getExtras().get("data");
try
{
FileOutputStream out = new FileOutputStream(destinationFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
}
catch (Exception e)
{
Log.e(TAG, "ERROR:" + e.toString());
}
}}}
The steps are:
1. So First of all as before we need to create a static int that will be our
public static final int CAPTURE_IMAGE_FULLSIZE_ACTIVITY_REQUEST_CODE = 1777;
2. Next we fire intent to start Activity for result:
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "image.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(intent, CAPTURE_IMAGE_FULLSIZE_ACTIVITY_REQUEST_CODE);
Here we are actually passing an URI as an extra to the intent in order to save the image at this location when it will be taken.
3. Finally we will receive the result in onActivityResult:
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
//Check that request code matches ours:
if (requestCode == CAPTURE_IMAGE_FULLSIZE_ACTIVITY_REQUEST_CODE)
{
//Get our saved file into a bitmap object:
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "image.jpg");
Bitmap bitmap = decodeSampledBitmapFromFile(file.getAbsolutePath(), 1000, 700);
}
}
When decodeSampledBitmapFromFile method is:
public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight)
{ // BEST QUALITY MATCH
//First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize, Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
options.inPreferredConfig = Bitmap.Config.RGB_565;
int inSampleSize = 1;
if (height > reqHeight)
{
inSampleSize = Math.round((float)height / (float)reqHeight);
}
int expectedWidth = width / inSampleSize;
if (expectedWidth > reqWidth)
{
//if(Math.round((float)width / (float)reqWidth) > inSampleSize) // If bigger SampSize..
inSampleSize = Math.round((float)width / (float)reqWidth);
}
options.inSampleSize = inSampleSize;
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
don't forget to add the relevent camera permissions to the manifest file:
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />

onCreateOptionMenu android Issue

It's the usual activity. The problem is in onCreateOptionMenu. When I click the menu button nothing is done. I don't see where the problem is.
I also try to comment all code without menu but It's still don't work.
It is either a very strange problem or I don't see some simple things..
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.LinearLayout;
public class Izu4aikaActivity extends Activity implements OnClickListener {
public final int INFO = 101;
public final int BLOCK = 102;
public final int CLOSE = 103;
final String sdDir = Environment.getExternalStorageDirectory()+"/izuchaika/";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
// Thread to write files to SD
final String file = "Files";
File dir = new File(sdDir);
dir.mkdir();
dir.mkdirs();
new Thread(new Runnable() {
public void run() {
copyFileOrDir(file);
}
}).start();
LinearLayout ll = (LinearLayout) findViewById(R.id.main_layout);
ll.setOnClickListener(this);
}
//Menu
public boolean onCreateOptionMenu(Menu menu) {
menu.add(Menu.NONE, INFO, Menu.NONE, "О программе").setIcon(
R.drawable.info);
menu.add(Menu.NONE, BLOCK, Menu.NONE, "Блокировать").setIcon(
R.drawable.block);
menu.add(Menu.NONE, CLOSE, Menu.NONE, "Выход").setIcon(R.drawable.exit);
return super.onCreateOptionsMenu(menu);
}
#Override
public void onClick(View v) {
Intent i = new Intent(this, mScr.class);
startActivity(i);
}
private void copyFileOrDir(String path) {
AssetManager assetManager = this.getAssets();
String assets[] = null;
try {
assets = assetManager.list(path);
if (assets.length == 0) {
copyFile(path);
} else {
String fullPath = sdDir + path;
File dir = new File(fullPath);
if (!dir.exists())
dir.mkdir();
for (int i = 0; i < assets.length; ++i) {
copyFileOrDir(path + "/" + assets[i]);
}
}
} catch (IOException ex) {
Log.e("tag", "I/O Exception", ex);
}
}
private void copyFile(String filename) {
AssetManager assetManager = this.getAssets();
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
String newFileName = sdDir + filename;
out = new FileOutputStream(newFileName);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
}
Help if you see a solution.
You've misspelled method name - it should be onCreateOptionsMenu(), not onCreateOptionMenu().
It's preferable to use #Override annotation to avoid such mistakes:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
This way it will give you compile time error if you misspell method name or use wrong parameters.
Change your onCreateOptionsMenu to:
//Menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(Menu.NONE, INFO, Menu.NONE, "О программе").setIcon(
R.drawable.info);
menu.add(Menu.NONE, BLOCK, Menu.NONE, "Блокировать").setIcon(
R.drawable.block);
menu.add(Menu.NONE, CLOSE, Menu.NONE, "Выход").setIcon(R.drawable.exit);
return true;
}
It should work now!
try to add
#Override to public boolean onCreateOptionMenu
And do you try to use MenuInflater and inflate menu from xml?

Categories