I've just followed this guide: http://www.androidhive.info/2013/09/android-working-with-camera-api/
Trying to create a camera feature for my app, however when I click either take a picture or record a video (Either of the buttons), it crashes on me. I've checked through the code, but I can't seem to find the error.
CameraActivity.java:
package com.example.frederik.snapsule;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.VideoView;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class CameraActivity extends AppCompatActivity {
//Activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
//Storing of content
private static final String IMAGE_DIRECTORY_NAME = "Hello Camera";
private Uri fileUri; //Content url storing
private ImageView imgPreview;
private VideoView videoPreview;
private Button btnCapturePicture, btnRecordVideo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_camera);
imgPreview = (ImageView) findViewById(R.id.imgPreview);
videoPreview = (VideoView) findViewById(R.id.videoPreview);
btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
btnRecordVideo = (Button) findViewById(R.id.btnRecordVideo);
btnCapturePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
captureImage();
}
});
btnRecordVideo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
recordVideo();
}
});
}
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
// code to check capture image response
} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// video successfully recorded
// preview the recorded video
previewVideo();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getApplicationContext(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
} else {
// failed to record video
Toast.makeText(getApplicationContext(),
"Sorry! Failed to record video", Toast.LENGTH_SHORT)
.show();
}
}
}
private void previewCapturedImage() {
try {
videoPreview.setVisibility(View.GONE);
imgPreview.setVisibility(View.VISIBLE);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
imgPreview.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
private void recordVideo() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}
private void previewVideo() {
try {
imgPreview.setVisibility(View.GONE);
videoPreview.setVisibility(View.VISIBLE);
videoPreview.setVideoPath(fileUri.getPath());
videoPreview.start();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable("file_uri", fileUri);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
fileUri = savedInstanceState.getParcelable("file_uri");
}
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
private static File getOutputMediaFile(int type) {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create " + IMAGE_DIRECTORY_NAME + " directory" );
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).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;
}
}
And my logcat:
11-04 15:18:42.487 23065-23065/com.example.frederik.snapsule E/AndroidRuntime: FATAL EXCEPTION: main
11-04 15:18:42.487 23065-23065/com.example.frederik.snapsule E/AndroidRuntime: Process: com.example.frederik.snapsule, PID: 23065
11-04 15:18:42.487 23065-23065/com.example.frederik.snapsule E/AndroidRuntime: java.lang.NullPointerException: file
11-04 15:18:42.487 23065-23065/com.example.frederik.snapsule E/AndroidRuntime: at android.net.Uri.fromFile(Uri.java:452)
11-04 15:18:42.487 23065-23065/com.example.frederik.snapsule E/AndroidRuntime: at com.example.frederik.snapsule.CameraActivity.getOutputMediaFileUri(CameraActivity.java:161)
11-04 15:18:42.487 23065-23065/com.example.frederik.snapsule E/AndroidRuntime: at com.example.frederik.snapsule.CameraActivity.captureImage(CameraActivity.java:72)
11-04 15:18:42.487 23065-23065/com.example.frederik.snapsule E/AndroidRuntime: at com.example.frederik.snapsule.CameraActivity.access$000(CameraActivity.java:26)
11-04 15:18:42.487 23065-23065/com.example.frederik.snapsule E/AndroidRuntime: at com.example.frederik.snapsule.CameraActivity$1.onClick(CameraActivity.java:57)
11-04 15:18:42.487 23065-23065/com.example.frederik.snapsule E/AndroidRuntime: at android.view.View.performClick(View.java:5198)
11-04 15:18:42.487 23065-23065/com.example.frederik.snapsule E/AndroidRuntime: at android.view.View$PerformClick.run(View.java:21147)
11-04 15:18:42.487 23065-23065/com.example.frederik.snapsule E/AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:739)
11-04 15:18:42.487 23065-23065/com.example.frederik.snapsule E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:95)
11-04 15:18:42.487 23065-23065/com.example.frederik.snapsule E/AndroidRuntime: at android.os.Looper.loop(Looper.java:148)
11-04 15:18:42.487 23065-23065/com.example.frederik.snapsule E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5417)
11-04 15:18:42.487 23065-23065/com.example.frederik.snapsule E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
11-04 15:18:42.487 23065-23065/com.example.frederik.snapsule E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
11-04 15:18:42.487 23065-23065/com.example.frederik.snapsule E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
My guess is it's an issue with Uri, but I'm unsure.
Also, the preview is not showing
It is a null pointer exception at line 161.
Apparently you hand in null into Uri.fromFile().
Therefore getOutputMediaFile(int type) returns null.
That may be the case if you see "Oops! Failed create" in your log.
It may be the case if type is neither MEDIA_TYPE_IMAGE nor MEDIA_TYPE_VIDEO.
It may be the case if new File(...) returned null.
Did you try debugging that method?
Your method
File getOutputMediaFile(int type)
its returning null, you have 2 return null; statements in it.
You should make a null check before calling Uri.fromFile()
EDIT
Just change this code to get rid of the crash, but it will still fail, you need to fix the original cause.
public Uri getOutputMediaFileUri(int type) {
File f = getOutputMediaFile(type);
if(f != null)
return Uri.fromFile(f);
else{
//Show some error message
return null;
}
}
Hope this helps.
Related
i made a small method to check whether defined folder has files with a specific extension or not. I m getting null point exception on run.pls help to find mistake.method is checking .mp4 files and returning true if found and message is displayed.
Here is Code:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView filecheck;
filecheck = (TextView) findViewById(R.id.filecheck);
filecheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (accept()) {
Toast.makeText(MainActivity.this, "Files Found", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Files Not Found", Toast.LENGTH_SHORT).show();
}
}
});
}
public boolean accept() {
final File pathname = new File("/sdcard/test/");
String files[] = pathname.list();
System.out.println(files.length);
for (String s : files) {
if (s.contains(".mp4")) {
System.out.println(s);
return true;
}
return false;
}
return false;
}
}
Here is exception:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: jss.testmethods, PID: 23659
java.lang.NullPointerException
at jss.testmethods.MainActivity.accept(MainActivity.java:38)
at jss.testmethods.MainActivity$1.onClick(MainActivity.java:24)
at android.view.View.performClick(View.java:4478)
at android.view.View$PerformClick.run(View.java:18698)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:149)
at android.app.ActivityThread.main(ActivityThread.java:5257)
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:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
at dalvik.system.NativeStart.main(Native Method)
i was expecting simple error, i missed to add permission for read storage. it is working now.
package com.jtunes.josh.watchtunes;
import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.wearable.view.WatchViewStub;
import android.view.View;
import android.widget.TextView;
public class playMedia extends Activity {
private TextView mTextView;
public MediaPlayer myMediaPlayer;
MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_media);
}
//Play song
public void playButtonClicked(View view) {
Context context = this;
mediaPlayer = new MediaPlayer();
System.out.println("Play button clicked" + mediaPlayer.toString());
try{
MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.dre);
mediaPlayer.start();
System.out.println("Song started");
}
catch (Exception e){
System.out.println("Error: " + e);
}
}
}
The same code works on a normal android emulator/device but when I attempt to do audio playback on android wear I get the following errors. Is it even possible to use MediaPlayer() on wear? Any ways around this?
07-27 19:12:45.374 7815-7830/com.jtunes.josh.watchtunes E/MediaPlayer﹕ error (1, -2147483648)
07-27 19:12:45.375 7815-7815/com.jtunes.josh.watchtunes D/MediaPlayer﹕ create failed:
java.io.IOException: Prepare failed.: status=0x1
at android.media.MediaPlayer._prepare(Native Method)
at android.media.MediaPlayer.prepare(MediaPlayer.java:1135)
at android.media.MediaPlayer.create(MediaPlayer.java:933)
at android.media.MediaPlayer.create(MediaPlayer.java:904)
at com.jtunes.josh.watchtunes.playMedia.playButtonClicked(playMedia.java:31)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4015)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
07-27 19:12:45.375 7815-7815/com.jtunes.josh.watchtunes I/System.out﹕ Error: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
Maybe try that:
public class playMedia extends Activity {
private TextView mTextView;
public MediaPlayer myMediaPlayer;
MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_media);
}
//Play song
public void playButtonClicked(View view) {
Context context = this;
mediaPlayer = new MediaPlayer();
System.out.println("Play button clicked" + mediaPlayer.toString());
try{
mediaPlayer = MediaPlayer.create(context, R.raw.dre);
mediaPlayer.start();
System.out.println("Song started");
}
catch (Exception e){
System.out.println("Error: " + e);
}
}
}
Hello developers I have a piece of that grabs the frames of a video...It seems it will work fine except a part of it where I am getting illegal argument exception...As I set the path of the video it crashes..Here is my code it crashes at the line
mediaMetadataRetriever.setDataSource(getBaseContext(),uri)
Here is the full code:
import java.io.IOException;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;
public class MainActivity extends Activity {
MediaMetadataRetriever mediaMetadataRetriever;
MediaController myMediaController;
VideoView myVideoView;
String viewSource = "/storage/test.mp4";
// String viewSource = "/storage/test.mp4";
Uri uri = null;
#TargetApi(Build.VERSION_CODES.GINGERBREAD_MR1)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
AssetFileDescriptor afd = getAssets().openFd("test.mp4");
Log.v("MA", "Before setdatasource");
uri = Uri.parse("E:/test.mp4");
mediaMetadataRetriever = new MediaMetadataRetriever();
**mediaMetadataRetriever.setDataSource(getBaseContext(),uri);**
// mediaMetadataRetriever.setDataSource(afd.getFileDescriptor(),
// afd.getStartOffset(), afd.getLength());
Log.v("MA", "After setdatasource" + afd.getStartOffset());
myVideoView = (VideoView) findViewById(R.id.videoview);
Log.v("MA", "VIdeoview found");
myVideoView.setVideoURI(Uri.parse(viewSource));
Log.v("MA", "After setdatasource");
myMediaController = new MediaController(this);
Log.v("MA", "After setdatasource");
myVideoView.setMediaController(myMediaController);
Log.v("MA", "myMediaController initialised");
myVideoView.setOnCompletionListener(myVideoViewCompletionListener);
Log.v("MA", "setOnCompletionListener");
myVideoView.setOnPreparedListener(MyVideoViewPreparedListener);
Log.v("MA", "setOnPreparedListener");
myVideoView.setOnErrorListener(myVideoViewErrorListener);
Log.v("MA", "setOnErrorListener");
myVideoView.requestFocus();
Log.v("MA", "focus set");
myVideoView.start();
Log.v("MA", "video started");
Button buttonCapture = (Button) findViewById(R.id.capture);
buttonCapture.setOnClickListener(new OnClickListener() {
#TargetApi(Build.VERSION_CODES.GINGERBREAD_MR1)
#Override
public void onClick(View arg0) {
int currentPosition = myVideoView.getCurrentPosition(); // in
// millisecond
Toast.makeText(MainActivity.this,
"Current Position: " + currentPosition + " (ms)",
Toast.LENGTH_LONG).show();
Bitmap bmFrame = mediaMetadataRetriever
.getFrameAtTime(currentPosition * 1000); // unit in
// microsecond
if (bmFrame == null) {
Toast.makeText(MainActivity.this, "bmFrame == null!",
Toast.LENGTH_LONG).show();
} else {
AlertDialog.Builder myCaptureDialog = new AlertDialog.Builder(
MainActivity.this);
ImageView capturedImageView = new ImageView(
MainActivity.this);
capturedImageView.setImageBitmap(bmFrame);
LayoutParams capturedImageViewLayoutParams = new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
capturedImageView
.setLayoutParams(capturedImageViewLayoutParams);
myCaptureDialog.setView(capturedImageView);
myCaptureDialog.show();
}
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
MediaPlayer.OnCompletionListener myVideoViewCompletionListener = new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer arg0) {
Toast.makeText(MainActivity.this, "End of Video", Toast.LENGTH_LONG)
.show();
}
};
MediaPlayer.OnPreparedListener MyVideoViewPreparedListener = new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
long duration = myVideoView.getDuration(); // in millisecond
Toast.makeText(MainActivity.this,
"Duration: " + duration + " (ms)", Toast.LENGTH_LONG)
.show();
}
};
MediaPlayer.OnErrorListener myVideoViewErrorListener = new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Toast.makeText(MainActivity.this, "Error!!!", Toast.LENGTH_LONG)
.show();
return true;
}
};
}
Trace:
E/AndroidRuntime( 4317): FATAL EXCEPTION: main
E/AndroidRuntime( 4317): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.captureframe/com.example.captureframe.MainActivity}: java.lang.IllegalArgumentException
E/AndroidRuntime( 4317): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
E/AndroidRuntime( 4317): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
E/AndroidRuntime( 4317): at android.app.ActivityThread.access$600(ActivityThread.java:141)
E/AndroidRuntime( 4317): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
E/AndroidRuntime( 4317): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime( 4317): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime( 4317): at android.app.ActivityThread.main(ActivityThread.java:5103)
E/AndroidRuntime( 4317): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 4317): at java.lang.reflect.Method.invoke(Method.java:525)
E/AndroidRuntime( 4317): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
E/AndroidRuntime( 4317): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
E/AndroidRuntime( 4317): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime( 4317): Caused by: java.lang.IllegalArgumentException
E/AndroidRuntime( 4317): at android.media.MediaMetadataRetriever.setDataSource(MediaMetadataRetriever.java:165)
E/AndroidRuntime( 4317): at com.example.captureframe.MainActivity.onCreate(MainActivity.java:46)
E/AndroidRuntime( 4317): at android.app.Activity.performCreate(Activity.java:5133)
E/AndroidRuntime( 4317): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
E/AndroidRuntime( 4317): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
Any ideas will be really appreciated.
Use this method.
public static Bitmap retriveVideoFrameFromVideo(String videoPath)
throws Throwable
{
Bitmap bitmap = null;
MediaMetadataRetriever mediaMetadataRetriever = null;
try
{
mediaMetadataRetriever = new MediaMetadataRetriever();
if (Build.VERSION.SDK_INT >= 14)
mediaMetadataRetriever.setDataSource(videoPath, new HashMap<String, String>());
else
mediaMetadataRetriever.setDataSource(videoPath);
// mediaMetadataRetriever.setDataSource(videoPath);
bitmap = mediaMetadataRetriever.getFrameAtTime();
}
catch (Exception e)
{
e.printStackTrace();
throw new Throwable(
"Exception in retriveVideoFrameFromVideo(String videoPath)"
+ e.getMessage());
}
finally
{
if (mediaMetadataRetriever != null)
{
mediaMetadataRetriever.release();
}
}
return bitmap;
}
I'm a newbie android developer and I am making, or trying to make a File explorer that wil be capable of opening almost all file types. From music files, through video files, document files and many others. BUT, I came across a huge problem that my app compiled successfully but it does not open. Here is my code:
package com.tstudios.openit;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class MainActivity extends ListActivity {
private List<String> item = null;
private List<String> path = null;
private String root;
private TextView myPath;
private ImageView mImageView=(ImageView) findViewById(R.id.gallery);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myPath = (TextView)findViewById(R.id.path);
root = Environment.getExternalStorageDirectory().getPath();
getDir(root);
}
private void getDir(String dirPath)
{
myPath.setText("Location: " + dirPath);
item = new ArrayList<String>();
path = new ArrayList<String>();
File f = new File(dirPath);
File[] files = f.listFiles();
if(!dirPath.equals(root))
{
item.add(root);
path.add(root);
item.add("../");
path.add(f.getParent());
}
String filename = f.getName();
String filenameArray[] = filename.split("\\.");
String extension = filenameArray[filenameArray.length-1];
TextView row=(TextView)findViewById(R.id.rowtext);
//if(extension=="jpg"){
//mImageView.setImageBitmap(BitmapFactory.decodeFile(dirPath));
//}
//if(extension!=null){
//row.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_launcher,0,0,0);
//}
Arrays.sort(files, filecomparator);
for(int i=0; i < files.length; i++)
{
File file = files[i];
if(!file.isHidden() && file.canRead()){
path.add(file.getPath());
if(file.isDirectory()){
item.add(file.getName() + "/");
}else{
item.add(file.getName());
}
}
}
ArrayAdapter<String> fileList =
new ArrayAdapter<String>(this, R.layout.row, item);
setListAdapter(fileList);
}
Comparator<? super File> filecomparator = new Comparator<File>(){
public int compare(File file1, File file2) {
if(file1.isDirectory()){
if (file2.isDirectory()){
return String.valueOf(file1.getName().toLowerCase()).compareTo(file2.getName().toLowerCase());
}else{
return -1;
}
}else {
if (file2.isDirectory()){
return 1;
}else{
return String.valueOf(file1.getName().toLowerCase()).compareTo(file2.getName().toLowerCase());
}
}
}
};
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
File file = new File(path.get(position));
String filename = file.getName();
String filenameArray[] = filename.split("\\.");
String extension = filenameArray[filenameArray.length-1];
if (file.isDirectory())
{
if(extension=="jpg"){
mImageView.setImageBitmap(BitmapFactory.decodeFile(filename));
getDir(path.get(position));
}else{
new AlertDialog.Builder(this)
.setIcon(R.drawable.ic_launcher)
.setTitle("[" + file.getName() + "] folder can't be read!")
.setPositiveButton("OK", null).show();
}
}else {
new AlertDialog.Builder(this)
.setIcon(R.drawable.ic_launcher)
.setTitle("[" + file.getName() + "]")
.setPositiveButton("OK", null).show();
}
}
}
and this is logcat I get when I lauch the app, btw I am using Sony Xperia Z1 Compact if that helps
08-28 12:10:54.779 4169-4169/com.tstudios.openit D/AndroidRuntime﹕ Shutting down VM
08-28 12:10:54.779 4169-4169/com.tstudios.openit W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x4164cd88)
08-28 12:10:54.789 4169-4169/com.tstudios.openit E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.tstudios.openit, PID: 4169
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.tstudios.openit/com.tstudios.openit.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2163)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2286)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:212)
at android.app.ActivityThread.main(ActivityThread.java:5135)
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:877)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.app.Activity.findViewById(Activity.java:1884)
at com.tstudios.openit.MainActivity.<init>(MainActivity.java:25)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2154)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2286)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:212)
at android.app.ActivityThread.main(ActivityThread.java:5135)
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:877)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
at dalvik.system.NativeStart.main(Native Method)
And another question, how to put icons before file names ? Depending on extension
Thank you very much for your help
Move the
mImageView=(ImageView) findViewById(R.id.gallery);
to onCreate() after setContentView(), leaving just the member variable declaration at the class level:
private ImageView mImageView;
Before onCreate() there's no window yet for the activity and you'll get the NPE.
Before setContentView() there's no view hierarchy to search from and a null is returned.
private ImageView mImageView=(ImageView) findViewById(R.id.gallery);
to use findViewById you need a valid Activity. It happens after the activity has been attached
Place this line private ImageView mImageView=(ImageView) findViewById(R.id.gallery); after setContentView . It will resolve null pointer exception. After this, if you get any other exception, Pls tell.
I want to access Confirmation activity from login activity. i was able to launch confirmation activity when i didn't have login and registration activity. login and registration works perfect without confirmation activity. and dashboard activity and confirmation activity works perfect without login and registration activity.
Registration Activity.
package com.example.androidhive;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.androidhive.library.DatabaseHandler;
import com.example.androidhive.library.UserFunctions;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class RegisterActivity extends Activity {
Button btnRegister;
Button btnLinkToLogin;
EditText inputFullName;
EditText inputEmail;
EditText inputPassword;
TextView registerErrorMsg;
// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
// Importing all assets like buttons, text fields
inputFullName = (EditText) findViewById(R.id.registerName);
inputEmail = (EditText) findViewById(R.id.registerEmail);
inputPassword = (EditText) findViewById(R.id.registerPassword);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
registerErrorMsg = (TextView) findViewById(R.id.register_error);
// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name = inputFullName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(name, email, password);
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully registred
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Registration Screen
finish();
}else{
// Error in registration
registerErrorMsg.setText("Error occured in registration");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
// Link to Login Screen
btnLinkToLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
LoginActivity.class);
startActivity(i);
// Close Registration View
finish();
}
});
}
}
Login Activity:-
import java.util.HashMap;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.example.androidhive.library.DatabaseHandler;
import com.example.androidhive.library.UserFunctions;
public class LoginActivity extends Activity {
Button btnLogin;
Button btnLinkToRegister;
EditText inputEmail;
EditText inputPassword;
TextView loginErrorMsg;
// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
// Importing all assets like buttons, text fields
inputEmail = (EditText) findViewById(R.id.loginEmail);
inputPassword = (EditText) findViewById(R.id.loginPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
loginErrorMsg = (TextView) findViewById(R.id.login_error);
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
UserFunctions userFunction = new UserFunctions();
Log.d("Button", "Login");
JSONObject json = userFunction.loginUser(email, password);
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
loginErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully logged in
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Login Screen
finish();
}else{
// Error in login
loginErrorMsg.setText("Incorrect username/password");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});
}
}
Dashboard Activity:-
package com.example.androidhive;
import android.app.Activity;
import com.example.androidhive.ConfirmationActivity;
import com.example.androidhive.R;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Toast;
import android.widget.Button;
import com.example.androidhive.library.UserFunctions;
public class DashboardActivity extends Activity {
UserFunctions userFunctions;
Button btnLogout;
private String resultString="";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/**
* Dashboard Screen for the application
* */
// Check login status in database
userFunctions = new UserFunctions();
if(userFunctions.isUserLoggedIn(getApplicationContext())){
setContentView(R.layout.dashboard);
btnLogout = (Button) findViewById(R.id.btnLogout);
btnLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
userFunctions.logoutUser(getApplicationContext());
Intent login = new Intent(getApplicationContext(), LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Closing dashboard screen
finish();
}
});
}else{
// user is not logged in show login screen
Intent login = new Intent(getApplicationContext(), LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Closing dashboard screen
finish();
}
}
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
#JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==0)
if (resultCode == RESULT_OK) {
//Use Data to get string
resultString = data.getStringExtra("RESULT_STRING");
LaunchWebView(resultString);
}
super.onActivityResult(requestCode, resultCode, data);
}
private void LaunchWebView(String resultString)
{
WebView engine=(WebView)findViewById(com.example.androidhive.R.id.web_engine);
//engine.getSettings().setJavaScriptEnabled(true);
String[] array=resultString.split(":");
engine.getSettings().setLoadsImagesAutomatically(true);
//engine.getSettings().setBuiltInZoomControls(true);
engine.getSettings().setUseWideViewPort(true);
engine.setWebChromeClient(new MyJavaScriptChromeClient());
engine.loadUrl("http://74.101.168.139/snapshot.cgi?user="+array[0]+"&pwd="+array[1]+"&count=0" + "&resolution=32"+ "&rate=6");
}
public void btnRefresh_ClicHandler(View view)
{
if(resultString!="")
LaunchWebView(resultString);
}
public void btnHome(View arg)
{
Intent intent=new Intent(this,ConfirmationActivity.class);
int result=0;
startActivityForResult(intent, result);
}
private class MyJavaScriptChromeClient extends WebChromeClient {
#Override
public boolean onJsAlert(WebView view, String url, String message,
JsResult result) {
// TODO Auto-generated method stub
return super.onJsAlert(view, null, message, result);
}
}
}
Confirmation Activity : -
package com.example.androidhive;
import com.example.androidhive.R;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class ConfirmationActivity extends Activity {
EditText txtPassword=null;
EditText txtUsername=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_confirmation);
}
public static final class menu2 {
public static final int confirmation=0x7f080000;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(menu2.confirmation, menu);
return true;
}
public void btnCancel_ClickHandler(View arg)
{
finish();
}
public void btnOk_ClickHandler(View arg)
{
txtUsername=(EditText)findViewById(com.example.androidhive.R.id.txtUserName);
txtPassword=(EditText)findViewById(com.example.androidhive.R.id.txtPassword);
if(txtUsername.getText().length()==0)
{
Toast.makeText(getApplicationContext(),
"User name can not be empty.", Toast.LENGTH_LONG).show();
return;
}
if(txtPassword.getText().length()==0)
{
Toast.makeText(getApplicationContext(),
"Password can not be empty.", Toast.LENGTH_LONG).show();
return;
}
Intent intent=new Intent();
intent.putExtra("RESULT_STRING",txtUsername.getText()+ ":"+txtPassword.getText());
setResult(RESULT_OK, intent);
finish();
}
}
Android Manifest.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidhive"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8"
android:targetSdkVersion="18"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:label="#string/app_name"
android:name=".DashboardActivity" >
</activity>
<!-- Confirmation Activity -->
<activity
android:label="Confiramtion Activity"
android:name=".ConfiramtionActivity"></activity>
<!-- Login Activity -->
<activity
android:label="Login Account"
android:name=".LoginActivity"></activity>
<!-- Register Activity -->
<activity
android:label="Register New Account"
android:name=".RegisterActivity">
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Android Fatal Error PLeaseeee Help:-
11-15 16:55:40.948: E/AndroidRuntime(858): FATAL EXCEPTION: main
11-15 16:55:40.948: E/AndroidRuntime(858): android.os.NetworkOnMainThreadException
11-15 16:55:40.948: E/AndroidRuntime(858): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
11-15 16:55:40.948: E/AndroidRuntime(858): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
11-15 16:55:40.948: E/AndroidRuntime(858): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
11-15 16:55:40.948: E/AndroidRuntime(858): at libcore.io.IoBridge.connect(IoBridge.java:112)
11-15 16:55:40.948: E/AndroidRuntime(858): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
11-15 16:55:40.948: E/AndroidRuntime(858): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
11-15 16:55:40.948: E/AndroidRuntime(858): at java.net.Socket.connect(Socket.java:842)
11-15 16:55:40.948: E/AndroidRuntime(858): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
11-15 16:55:40.948: E/AndroidRuntime(858): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
11-15 16:55:40.948: E/AndroidRuntime(858): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
11-15 16:55:40.948: E/AndroidRuntime(858): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
11-15 16:55:40.948: E/AndroidRuntime(858): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
11-15 16:55:40.948: E/AndroidRuntime(858): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
11-15 16:55:40.948: E/AndroidRuntime(858): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
11-15 16:55:40.948: E/AndroidRuntime(858): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
11-15 16:55:40.948: E/AndroidRuntime(858): at com.example.androidhive.library.JSONParser.getJSONFromUrl(JSONParser.java:47)
11-15 16:55:40.948: E/AndroidRuntime(858): at com.example.androidhive.library.UserFunctions.loginUser(UserFunctions.java:32)
11-15 16:55:40.948: E/AndroidRuntime(858): at com.example.androidhive.LoginActivity$1.onClick(LoginActivity.java:61)
11-15 16:55:40.948: E/AndroidRuntime(858): at android.view.View.performClick(View.java:4240)
11-15 16:55:40.948: E/AndroidRuntime(858): at android.view.View$PerformClick.run(View.java:17721)
11-15 16:55:40.948: E/AndroidRuntime(858): at android.os.Handler.handleCallback(Handler.java:730)
11-15 16:55:40.948: E/AndroidRuntime(858): at android.os.Handler.dispatchMessage(Handler.java:92)
11-15 16:55:40.948: E/AndroidRuntime(858): at android.os.Looper.loop(Looper.java:137)
11-15 16:55:40.948: E/AndroidRuntime(858): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-15 16:55:40.948: E/AndroidRuntime(858): at java.lang.reflect.Method.invokeNative(Native Method)
11-15 16:55:40.948: E/AndroidRuntime(858): at java.lang.reflect.Method.invoke(Method.java:525)
11-15 16:55:40.948: E/AndroidRuntime(858): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-15 16:55:40.948: E/AndroidRuntime(858): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-15 16:55:40.948: E/AndroidRuntime(858): at dalvik.system.NativeStart.main(Native Method)
This exception is thrown when application tries to access network in main thread. This is forbidden as accessing resources over network may take indefinite amount of time and your main thread will be blocked untill network operation finishes, thus making your app frozen to the user.
Instead in your onClick() method you should start a new AsyncTask which will do the networking. After the task finishes proceed with updating the ui (changing activity etc.).