Android: java.lang.IllegalStateException: Could not execute method of the activity - java

Why am i getting this error??
04-27 16:09:19.823 32255-32255/com.example.myapplication D/AndroidRuntime﹕ Shutting down VM
04-27 16:09:19.823 32255-32255/com.example.myapplication W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41597db8)
04-27 16:09:19.823 32255-32255/com.example.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 32255
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3830)
at android.view.View.performClick(View.java:4445)
at android.view.View$PerformClick.run(View.java:18446)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5146)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3825)
            at android.view.View.performClick(View.java:4445)
            at android.view.View$PerformClick.run(View.java:18446)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5146)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
            at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.myapplication.MainActivity.storeImage(MainActivity.java:139)
at com.example.myapplication.MainActivity.save_btn(MainActivity.java:150)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at android.view.View$1.onClick(View.java:3825)
            at android.view.View.performClick(View.java:4445)
            at android.view.View$PerformClick.run(View.java:18446)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5146)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
            at dalvik.system.NativeStart.main(Native Method)
What my application does is, opens up the camera application via an intent. Then loads the image/bitmao into an imageview. Whenever i click the save_btn button it gives me this error. Could anybody tell me why and give me a solution? Thank you.
package com.example.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.text.SimpleDateFormat;
public class MainActivity extends Activity {
static final int REQUEST_IMAGE_CAPTURE = 1;
ImageView imageView;
private static final String TAG = "MyActivity";
Bitmap image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
openCamera();
setContentView(R.layout.activity_main);
findViewById(R.id.captureImage).bringToFront();
findViewById(R.id.saveImage).bringToFront();
imageView = (ImageView) findViewById(R.id.imageView2);
}
protected void onSaveInstanceState(Bundle outState){
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "TMP.jpg");
file.delete();
}
public void openCamera() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "TMP.jpg");
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//Check that request code matches ours:
if (requestCode == REQUEST_IMAGE_CAPTURE) {
//Get our saved file into a bitmap object:
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "TMP.jpg");
Bitmap image = decodeSampledBitmapFromFile(file.getAbsolutePath(), 1000, 700);
imageView.setImageBitmap(image);
}
}
// Reduce the amount of dynamic heap used by expanding the JPEG into a memory array that's already scaled to match the size of the destination view
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);
}
public void capture_btn(View v) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "TMP.jpg");
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
/** Create a File for saving an image or video */
private File getOutputMediaFile(){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Pictures/Wiki_Camera"
+ getApplicationContext().getPackageName()
+ "/Files");
// 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()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="camera_wiki"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
public void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
public void save_btn(View v) {
storeImage(image);
}
}

Just guessing but it seems you store taken image only for local variable
Bitmap image = decodeSampledBitmapFromFile(file.getAbsolutePath(), 1000, 700);
While later in the code you try to store image from class variable with the same name
image.compress(Bitmap.CompressFormat.PNG, 90, fos);

public void storeImage(Bitmap image) {
imageView.buildDrawingCache();
Bitmap bm_img = imageView.getDrawingCache();
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
bm_img.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}

Related

Capture, store and retrieve photo in activity

I have a problem, that I can't fix. I have spent almost all day today trying to get this to work, but I can't and I am out of any ideas, so decided to ask for your help.
Also, I have looked around google and stackoverflow for answers, none of which helped me.
The problem regards photo capturing with android. I have an activity, where I can "create" a new item that is later on stored in a database. I can pass it a name and location, as well as take a photo that binds to it. When I press "add" it is saved to the database. Everything works, except the Camera intent. I want to be able to take a photo in that activity, that binds to the "object" I'm creating, so later on I can view that photo when I click on a particular "object" on a list. I do have permissions (write and read) in my AndroidManifest, but still they dont help.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
android:maxSdkVersion="18"
/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18"
/>
<uses-feature android:name="android.hardware.camera"
android:required="false"
/>
My android version is 6.0.
This code is the most recent compilation of solutions that I have gathered to try to make it work. I would very much appreciate your help with my issue.
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
public class CreateItemFragment extends Fragment {
private static final int REQUEST_PHOTO = 2;
private static final String TAG = "button clicked";
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
private TextView mNameText;
private TextView mLocationText;
private Button mAddButton;
private ImageButton mPhotoButton;
private ImageView mPhotoView;
private String mCurrentPhotoPath;
private File mPhotoFile;
private Item mItem;
private List<Item> mItems;
private static ItemStash sItemStash;
public static CreateItemFragment newInstance(){
return new CreateItemFragment();
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_create_item, container, false);
mNameText = (TextView)view.findViewById(R.id.item_name);
mLocationText = (TextView)view.findViewById(R.id.item_location);
sItemStash = sItemStash.get(getContext());
mAddButton = (Button)view.findViewById(R.id.add_button);
mAddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mNameText.getText().length() > 0 && mLocationText.getText().length() > 0){
sItemStash.addItem(
new Item(mNameText.getText().toString(),
mLocationText.getText().toString()));
Toast.makeText(getActivity(), mNameText.getText().toString() + " added to the list!", Toast.LENGTH_SHORT).show();
}
mNameText.setText("");
mLocationText.setText("");
}
});
mPhotoButton = (ImageButton)view.findViewById(R.id.photo_button);
//final Intent captureImage = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
/*
PackageManager packageManager = getActivity().getPackageManager();
boolean canTakePhoto = mPhotoFile != null && captureImage.resolveActivity(packageManager) != null;
mPhotoButton.setEnabled(canTakePhoto);
if(canTakePhoto) {
Uri uri = Uri.fromFile(mPhotoFile);
captureImage.putExtra(MediaStore.EXTRA_OUTPUT, uri);
}
*/
mPhotoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
verifyStoragePermissions(getActivity());
capturePhotoIntent();
//startActivityForResult(captureImage, REQUEST_PHOTO);
//mPhotoFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString());
//mPhotoFile = new File(mItem.setPhotoFilename(mNameText.getText().toString()));
}
});
mPhotoView = (ImageView)view.findViewById(R.id.item_photo);
//updatePhotoView();
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == REQUEST_PHOTO && resultCode == Activity.RESULT_OK){
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap)extras.get("data");
//mPhotoFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString());
mPhotoView.setImageBitmap(imageBitmap);
}
}
/*
private void updatePhotoView(){
if(mPhotoFile == null || !mPhotoFile.exists()){
Log.d(TAG, "is clicked");
mPhotoView.setImageDrawable(null);
}else{
Bitmap bitmap = PhotoUtils.getScaledBitmap(mPhotoFile.getPath(), getActivity());
mPhotoView.setImageBitmap(bitmap);
}
}
*/
private void capturePhotoIntent(){
Intent photoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
PackageManager packageManager = getActivity().getPackageManager();
if(photoIntent.resolveActivity(packageManager) != null){
File photoFile = null;
try{
photoFile = createImageFile();
}catch (IOException ioe){
ioe.printStackTrace();
}
if(photoFile != null) {
photoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(photoIntent, REQUEST_PHOTO);
}
}
}
public File createImageFile() throws IOException {
verifyStoragePermissions(getActivity());
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName,
".jpg",
storageDir
);
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
public static void verifyStoragePermissions(Activity activity) {
int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
}
*EDIT
Forgot to paste in my stack trace. I do get this:
04-21 22:34:56.688 3574-3604/com.bignerdranch.android.tingleapp
W/OpenGLRenderer: Fail to change FontRenderer cache size, it already initialized
04-21 22:34:56.704 3574-3574/com.bignerdranch.android.tingleapp D/android.widget.GridLayout: horizontal constraints: x1-x0>=163, x2-x1>=1080, x2-x0<=1080 are inconsistent; permanently removing: x2-x0<=1080.
04-21 22:34:56.708 3574-3574/com.bignerdranch.android.tingleapp D/android.widget.GridLayout: vertical constraints: y2-y0>=745, y2-y1<=136, y1-y0<=136 are inconsistent; permanently removing: y2-y1<=136.
04-21 22:34:56.819 3574-3604/com.bignerdranch.android.tingleapp E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb8767340
04-21 22:34:57.533 3574-3574/com.bignerdranch.android.tingleapp W/System.err: java.io.IOException: open failed: EACCES (Permission denied)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at java.io.File.createNewFile(File.java:939)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at java.io.File.createTempFile(File.java:1004)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at com.bignerdranch.android.tingleapp.CreateItemFragment.createImageFile(CreateItemFragment.java:173)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at com.bignerdranch.android.tingleapp.CreateItemFragment.capturePhotoIntent(CreateItemFragment.java:154)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at com.bignerdranch.android.tingleapp.CreateItemFragment.access$300(CreateItemFragment.java:30)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at com.bignerdranch.android.tingleapp.CreateItemFragment$2.onClick(CreateItemFragment.java:108)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at android.view.View.performClick(View.java:5226)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at android.view.View$PerformClick.run(View.java:21266)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at android.os.Handler.handleCallback(Handler.java:739)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at android.os.Looper.loop(Looper.java:168)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5845)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at java.lang.reflect.Method.invoke(Native Method)
04-21 22:34:57.538 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
04-21 22:34:57.539 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
04-21 22:34:57.539 3574-3574/com.bignerdranch.android.tingleapp W/System.err: Caused by: android.system.ErrnoException: open failed: EACCES (Permission denied)
04-21 22:34:57.539 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at libcore.io.Posix.open(Native Method)
04-21 22:34:57.539 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
04-21 22:34:57.539 3574-3574/com.bignerdranch.android.tingleapp W/System.err: at java.io.File.createNewFile(File.java:932)
04-21 22:34:57.539 3574-3574/com.bignerdranch.android.tingleapp W/System.err: ... 14 more
the method verisfyStoragePermission() was supposed to fix that error as I found in other topics, but I still get this error

Attempt to invoke virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference

I keep getting this error and i'm not sure why. I've tried googling it but no luck there.
04-21 15:43:24.822 2461-2461/com.example.s.myapplication D/AndroidRuntime﹕ Shutting down VM
04-21 15:43:24.823 2461-2461/com.example.s.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.s.myapplication, PID: 2461
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.example.s.myapplication/com.example.s.myapplication.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:3539)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3582)
at android.app.ActivityThread.access$1300(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1327)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference
at com.example.s.myapplication.MainActivity.onActivityResult(MainActivity.java:46)
at android.app.Activity.dispatchActivityResult(Activity.java:6139)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3535)
            at android.app.ActivityThread.handleSendResult(ActivityThread.java:3582)
            at android.app.ActivityThread.access$1300(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1327)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
a
This is my main activity. What the application is meant to do is:
Take a photo
Save the photo in a tmp location
load the photo into a imageview
.
package com.example.s.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import java.io.File;
public class MainActivity extends Activity {
static final int REQUEST_IMAGE_CAPTURE = 1;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
openCamera();
setContentView(R.layout.activity_main);
}
public void openCamera() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "image.jpg");
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//Check that request code matches ours:
if (requestCode == REQUEST_IMAGE_CAPTURE) {
//Get our saved file into a bitmap object:
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "image.jpg");
Bitmap image = decodeSampledBitmapFromFile(file.getAbsolutePath(), 1000, 700);
imageView.setImageBitmap(image);
}
}
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight) {
//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);
}
public void capture_btn(View v) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "image.jpg");
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
imageView = (ImageView)findViewById(R.id.imageView2);
This worked for me:
I wrote wrong the id of my imageView. It supposed to be imageView2
imageView = findViewById(R.id.imageView2);
if above solutions did not work for you check
oncreate method again it should be like this
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);imageView=findViewById(R.id.imageView);
setContentView(R.layout.activity_main);
imageView=findViewById(R.id.imageView);
}

Run Time Error: FATAL EXCEPTION: main java.lang.ExceptionInInitializerError

Hi am new to Android App development and i was trying to implement a simple OCR App found here: https://github.com/GautamGupta/Simple-Android-OCR
Am using android studio, i found some errors that had to do with permission which i fixed but now i am getting this error:
03-31 20:07:55.010 822-822/com.example.zakaria.myapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.ExceptionInInitializerError
at engenoid.tessocrtest.MainActivity.onPhotoTaken(MainActivity.java:210)
at engenoid.tessocrtest.MainActivity.onActivityResult(MainActivity.java:134)
at android.app.Activity.dispatchActivityResult(Activity.java:5515)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3429)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3476)
at android.app.ActivityThread.access$1200(ActivityThread.java:157)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1337)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5317)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.UnsatisfiedLinkError: Couldn't load lept from loader dalvik.system.PathClassLoader[dexPath=/data/app/com.example.zakaria.myapp-10.apk,libraryPath=/data/app-lib/com.example.zakaria.myapp-10]: findLibrary returned null
at java.lang.Runtime.loadLibrary(Runtime.java:365)
at java.lang.System.loadLibrary(System.java:535)
at com.googlecode.tesseract.android.TessBaseAPI.<clinit>(TessBaseAPI.java:44)
            at engenoid.tessocrtest.MainActivity.onPhotoTaken(MainActivity.java:210)
            at engenoid.tessocrtest.MainActivity.onActivityResult(MainActivity.java:134)
            at android.app.Activity.dispatchActivityResult(Activity.java:5515)
            at android.app.ActivityThread.deliverResults(ActivityThread.java:3429)
            at android.app.ActivityThread.handleSendResult(ActivityThread.java:3476)
            at android.app.ActivityThread.access$1200(ActivityThread.java:157)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1337)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:176)
            at android.app.ActivityThread.main(ActivityThread.java:5317)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
            at dalvik.system.NativeStart.main(Native Method)
Here is the main Activity:
package engenoid.tessocrtest;
import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.example.zakaria.myapp.R;
import com.googlecode.tesseract.android.TessBaseAPI;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class MainActivity extends Activity {
public static final String PACKAGE_NAME = "com.datumdroid.android.ocr.simple";
public static final String DATA_PATH = Environment
.getExternalStorageDirectory().toString() + "/SimpleAndroidOCR/";
// You should have the trained data file in assets folder
// You can get them at:
// http://code.google.com/p/tesseract-ocr/downloads/list
public static final String lang = "eng";
private static final String TAG = "SimpleAndroidOCR.java";
protected Button _button;
// protected ImageView _image;
protected EditText _field;
protected String _path;
protected boolean _taken;
protected static final String PHOTO_TAKEN = "photo_taken";
#Override
public void onCreate(Bundle savedInstanceState) {
String[] paths = new String[] { DATA_PATH, DATA_PATH + "tessdata/" };
for (String path : paths) {
File dir = new File(path);
if (!dir.exists()) {
if (!dir.mkdirs()) {
Log.v(TAG, "ERROR: Creation of directory " + path + " on sdcard failed");
return;
} else {
Log.v(TAG, "Created directory " + path + " on sdcard");
}
}
}
// lang.traineddata file with the app (in assets folder)
// You can get them at:
// http://code.google.com/p/tesseract-ocr/downloads/list
// This area needs work and optimization
if (!(new File(DATA_PATH + "tessdata/" + lang + ".traineddata")).exists()) {
try {
AssetManager assetManager = getAssets();
InputStream in = assetManager.open("tessdata/" + lang + ".traineddata");
//GZIPInputStream gin = new GZIPInputStream(in);
OutputStream out = new FileOutputStream(DATA_PATH
+ "tessdata/" + lang + ".traineddata");
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
//while ((lenf = gin.read(buff)) > 0) {
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
//gin.close();
out.close();
Log.v(TAG, "Copied " + lang + " traineddata");
} catch (IOException e) {
Log.e(TAG, "Was unable to copy " + lang + " traineddata " + e.toString());
}
}
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// _image = (ImageView) findViewById(R.id.image);
_field = (EditText) findViewById(R.id.field);
_button = (Button) findViewById(R.id.button);
_button.setOnClickListener(new ButtonClickHandler());
_path = DATA_PATH + "/ocr.jpg";
}
public class ButtonClickHandler implements View.OnClickListener {
public void onClick(View view) {
Log.v(TAG, "Starting Camera app");
startCameraActivity();
}
}
// Simple android photo capture:
// http://labs.makemachine.net/2010/03/simple-android-photo-capture/
protected void startCameraActivity() {
File file = new File(_path);
Uri outputFileUri = Uri.fromFile(file);
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i(TAG, "resultCode: " + resultCode);
if (resultCode == -1) {
onPhotoTaken();
} else {
Log.v(TAG, "User cancelled");
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean(MainActivity.PHOTO_TAKEN, _taken);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
Log.i(TAG, "onRestoreInstanceState()");
if (savedInstanceState.getBoolean(MainActivity.PHOTO_TAKEN)) {
onPhotoTaken();
}
}
protected void onPhotoTaken() {
_taken = true;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
Bitmap bitmap = BitmapFactory.decodeFile(_path, options);
try {
ExifInterface exif = new ExifInterface(_path);
int exifOrientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
Log.v(TAG, "Orient: " + exifOrientation);
int rotate = 0;
switch (exifOrientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
}
Log.v(TAG, "Rotation: " + rotate);
if (rotate != 0) {
// Getting width & height of the given image.
int w = bitmap.getWidth();
int h = bitmap.getHeight();
// Setting pre rotate
Matrix mtx = new Matrix();
mtx.preRotate(rotate);
// Rotating Bitmap
bitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, false);
}
// Convert to ARGB_8888, required by tess
bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
} catch (IOException e) {
Log.e(TAG, "Couldn't correct orientation: " + e.toString());
}
// _image.setImageBitmap( bitmap );
Log.v(TAG, "Before baseApi");
TessBaseAPI baseApi = new TessBaseAPI();
baseApi.setDebug(true);
baseApi.init(DATA_PATH, lang);
baseApi.setImage(bitmap);
String recognizedText = baseApi.getUTF8Text();
baseApi.end();
// You now have the text in recognizedText var, you can do anything with it.
// We will display a stripped out trimmed alpha-numeric version of it (if lang is eng)
// so that garbage doesn't make it to the display.
Log.v(TAG, "OCRED TEXT: " + recognizedText);
if ( lang.equalsIgnoreCase("eng") ) {
recognizedText = recognizedText.replaceAll("[^a-zA-Z0-9]+", " ");
}
recognizedText = recognizedText.trim();
if ( recognizedText.length() != 0 ) {
_field.setText(_field.getText().toString().length() == 0 ? recognizedText : _field.getText() + " " + recognizedText);
_field.setSelection(_field.getText().toString().length());
}
}
}
And this is the manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.zakaria.myapp" >
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-feature
android:name="android.hardware.camera.flash"
android:required="false" />
<uses-feature android:name="android.hardware.camera" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<activity
android:name="engenoid.tessocrtest.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
So if i need to post any thing else please tell me and thanks in advance!
#GabeSechan you are right i went through the app files and there was supposed to be a file by that name, doing some further Google search i learnt that that file is supposed to be generated when building the tess-two library used in this app, i think i didn't do that right.
thank you so much.

Cannot save files to SDcard android app

Im having a problem saving/ creating a file on my sdcard to save text to, i am trying to check if the file is created and if not create it, then write certain data to it on button click. Here is my code and error output:
This is the error output:
java.lang.RuntimeException: Unable to start activity ComponentInfo{ibettergetagoodgradeforthisorillbepissed.sciencefair.beta.mmmeds.com.mmmeds/ibettergetagoodgradeforthisorillbepissed.sciencefair.beta.mmmeds.com.mmmeds.MainActivity}: java.lang.IllegalArgumentException: File /sdcard/output.txt contains a path separator
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2187)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2236)
at android.app.ActivityThread.access$800(ActivityThread.java:138)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1199)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5034)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1270)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1086)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalArgumentException: File /sdcard/output.txt contains a path separator
at android.app.ContextImpl.makeFilename(ContextImpl.java:2165)
at android.app.ContextImpl.getFileStreamPath(ContextImpl.java:964)
at android.content.ContextWrapper.getFileStreamPath(ContextWrapper.java:195)
at ibettergetagoodgradeforthisorillbepissed.sciencefair.beta.mmmeds.com.mmmeds.MainActivity.onCreate(MainActivity.java:207)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2151)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2236)
            at android.app.ActivityThread.access$800(ActivityThread.java:138)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1199)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5034)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
and here is the code for the file saving:
String SDRoot = Environment.getExternalStorageDirectory().getPath();
final File output = getFileStreamPath(SDRoot + "/output.txt");
if(!output.exists()){
try {
output.createNewFile();
Context context = getApplicationContext();
CharSequence text = "Output File Created!";
int duration = Toast.LENGTH_LONG;
Toast fileCreated = Toast.makeText(context, text, duration);
fileCreated.show();
} catch (IOException e) {
Context context = getApplicationContext();
CharSequence text = "Output File Not Created!";
int duration = Toast.LENGTH_LONG;
Toast fileNotCreated = Toast.makeText(context, text, duration);
fileNotCreated.show();
e.printStackTrace();
}
}
Button addbutton = (Button)findViewById(R.id.addMeds);
addbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String outputLine = medOut.toString() + doseOut.getText() + dayout.getText() + timeOut.getText();
try {
FileOutputStream fOut = new FileOutputStream(output);
OutputStreamWriter myOutputStreamWriter = new OutputStreamWriter(fOut);
myOutputStreamWriter.append(outputLine);
myOutputStreamWriter.flush();
myOutputStreamWriter.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
}
http://developer.android.com/reference/android/content/Context.html#getFileStreamPath(java.lang.String)
Parameters : name The name of the file for which you would like to get its path.
If you give a path (containing "/") instead, it will crash as you have already noticed.
Besides, this function applies only for your application private files, created with openFileOuput for instance.
http://developer.android.com/reference/android/content/Context.html#openFileOutput(java.lang.String, int)
Just do like this :
String SDRoot = Environment.getExternalStorageDirectory().getPath();
final File output = new File(SDRoot + "/output.txt");

Fatal Error On main Thread

I am receiving this fatal Error, when I try to access one particular function zipIt().
It doesn't matter from where I try to access it I always receive this error. This function simply zips a folder but program don't even go inside this function.
Logcat is displayed below:
Process: com.test.shahid, PID: 14839
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3823)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5050)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1264)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1080)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3818)
            at android.view.View.performClick(View.java:4438)
            at android.view.View$PerformClick.run(View.java:18422)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5050)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1264)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1080)
            at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at java.io.File.fixSlashes(File.java:185)
at java.io.File.<init>(File.java:134)
at java.io.FileOutputStream.<init>(FileOutputStream.java:128)
at java.io.FileOutputStream.<init>(FileOutputStream.java:117)
at com.test.shahid.MainActivity.zipIt(MainActivity.java:170)
at com.test.shahid.MainActivity.dispatchTakePictureIntent(MainActivity.java:490)
at com.test.shahid.MainActivity.onClickPhoto(MainActivity.java:468)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at android.view.View$1.onClick(View.java:3818)
            at android.view.View.performClick(View.java:4438)
            at android.view.View$PerformClick.run(View.java:18422)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5050)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1264)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1080)
            at dalvik.system.NativeStart.main(Native Method)
05-23 09:48:22.023 14839-14839/com.test.shahid I/Process﹕ Sending signal. PID: 14839 SIG: 9
Here is the function and variables associated with this function.
private static final File INPUT_FOLDER = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
private static final String ZIPPED_FOLDER = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES).toString();
protected void zipIt(File inputFolder, String zipFilePath) {
try {
FileOutputStream fileOutputStream = new FileOutputStream(zipFilePath);
ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);
String myname =inputFolder.toString();
ZipEntry folderZipEntry = new ZipEntry(myname);
zipOutputStream.putNextEntry(folderZipEntry);
File[] contents = inputFolder.listFiles();
for (File f : contents) {
if (f.isFile())
zipFile(f, zipOutputStream);
}
zipOutputStream.closeEntry();
zipOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
protected void zipFile(File inputFile, ZipOutputStream zipOutputStream) {
try { // A ZipEntry represents a file entry in the zip archive
// We name the ZipEntry after the original file's name
ZipEntry zipEntry = new ZipEntry(inputFile.getName());
zipOutputStream.putNextEntry(zipEntry);
FileInputStream fileInputStream = new FileInputStream(inputFile);
byte[] buf = new byte[1024];
int bytesRead;
// Read the input file by chucks of 1024 bytes
// and write the read bytes to the zip stream
while ((bytesRead = fileInputStream.read(buf)) > 0) {
zipOutputStream.write(buf, 0, bytesRead);
}
// close ZipEntry to store the stream to the file
zipOutputStream.closeEntry();
System.out.println("Regular file :" + inputFile.getCanonicalPath() + " is zipped to archive :" + ZIPPED_FOLDER);
} catch (IOException e) {
e.printStackTrace();
}
}
Well this is from where i am calling this function. I called this function just to check otherwise i have called this function from button and from several other functions. But nothing works.
public void onSync(View v) throws JSONException, IOException {
zipIt(INPUT_FOLDER, ZIPPED_FOLDER);
if (!isConnected()) {
AlertDialog.Builder mBuilder = new Builder(this);
mBuilder.setMessage("Please Enable Wifi to use this service");
mBuilder.setTitle("Enable WIFI");
mBuilder.setCancelable(false);
mBuilder.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i = new Intent(
Settings.ACTION_WIFI_SETTINGS);
startActivity(i);
}
}
);
mBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// This code might cause problem so check when
// device is available
MainActivity.this.finish();
}
}
);
// create alert dialog
AlertDialog alertDialog = mBuilder.create();
// show it
alertDialog.show();
tvIsConnected.setText("You are NOT conncted");
// Intent myIntent = new
// Intent(Settings.ACTION_WIFI_SETTINGS);
// startActivity(myIntent);
return;
}
tvIsConnected.setBackgroundColor(0xFF00CC00);
tvIsConnected.setText("You are conncted");
handler.sendEmptyMessage(MSG_SYNC);
}
NullPointerException
Do you have "WriteExternalStorage" permision in your manifest?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Did you check the file path?
Environment.getExternalStorageDirectory() + "/some_foulder/file.txt"

Categories

Resources