mediaMetadataRetriever.setDataSource(getBaseContext(),uri) throws illegal argument exception - java

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;
}

Related

Application crashes when trying to take pictures/record video

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.

android app crashes when killing one activity and start another one

There is one button I set in Scene2.java.I want to use the button to get in other activities Scene3.java,GameOver.java Everything worked fine until its about to open the new activity,every time the app crashed there. I want to know if there're any mistake I made in the connection,which I mean the newIntent and getIntent inScene2.java GameOver.javaand Scene3.java
Scene2.java
package com.group5.littlered;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class Scene2 extends Activity {
MediaPlayer bird;
MediaPlayer bgm;
int position = 0;
String[] conversation;
TextView frame;
ImageView conframe;
final String[] ListStr = { "Wake up and ask her", "Peek her secretly" };
int plot = 0;
#Override
public void onBackPressed() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_scene2);
Intent intent1 = getIntent();
conversation = getResources().getStringArray(R.array.scene2);
frame = (TextView) findViewById(R.id.textView1);
Button next = (Button) findViewById(R.id.wtf);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (position < 2) {
String sentence = conversation[position];
frame.setText(sentence + "");
position++;
} else {
if (plot < 1) {
AlertDialog choice = new AlertDialog.Builder(
Scene2.this).create();
choice.setTitle("Pick a choice");
choice.setMessage(" ");
choice.setButton("Get up and ask her what happened",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
plot = 1;
}
});
choice.setButton2("Peek her secretly",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
plot = 2;
position = 4;
}
});
choice.show();
} else {
if (plot < 2) {
if (position < 4) {
String sentence = conversation[position];
frame.setText(sentence + "");
position++;
} else {
Intent intent2 = new Intent(Scene2.this,
GameOver.class);
startActivity(intent2);
finish();
}
} else {
if (position < 6) {
String sentence = conversation[position];
frame.setText(sentence + "");
position++;
} else {
Intent intent3 = new Intent(Scene2.this,
Scene3.class);
startActivity(intent3);
finish();
}
}
}
}
}
});
// BGM
bgm = MediaPlayer.create(Scene2.this, R.raw.voyager);
bgm.setLooping(true);
bgm.start();
// bird
bird = MediaPlayer.create(Scene2.this, R.raw.bird);
bird.setLooping(false);
bird.start();
}
}
Scene3.java
package com.group5.littlered;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class Scene3 extends Activity {
int position = 0;
String[] conversation;
TextView frame;
ImageView conframe;
#Override
public void onBackPressed() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_scene3);
Intent intent3 = getIntent();
conversation = getResources().getStringArray(R.array.scene1);
frame = (TextView) findViewById(R.id.textView1);
Button next = (Button) findViewById(R.id.wtf);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (position < 6) {
String sentence = conversation[position];
frame.setText(sentence + "");
position++;
} else {
{
}
}
}
});
}
}
Again sorry for my poor ENGLISH, plz tell me what I need to post more to help you understand my problem.
my logcat
04-30 09:37:39.497: E/AndroidRuntime(4862): FATAL EXCEPTION: main
04-30 09:37:39.497: E/AndroidRuntime(4862): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.group5.littlered/com.group5.littlered.Scene3}: java.lang.NullPointerException
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread.access$600(ActivityThread.java:141)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.os.Handler.dispatchMessage(Handler.java:99)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.os.Looper.loop(Looper.java:137)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread.main(ActivityThread.java:5103)
04-30 09:37:39.497: E/AndroidRuntime(4862): at java.lang.reflect.Method.invokeNative(Native Method)
04-30 09:37:39.497: E/AndroidRuntime(4862): at java.lang.reflect.Method.invoke(Method.java:525)
04-30 09:37:39.497: E/AndroidRuntime(4862): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
04-30 09:37:39.497: E/AndroidRuntime(4862): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
04-30 09:37:39.497: E/AndroidRuntime(4862): at dalvik.system.NativeStart.main(Native Method)
04-30 09:37:39.497: E/AndroidRuntime(4862): Caused by: java.lang.NullPointerException
04-30 09:37:39.497: E/AndroidRuntime(4862): at com.group5.littlered.Scene3.onCreate(Scene3.java:45)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.Activity.performCreate(Activity.java:5133)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
04-30 09:37:39.497: E/AndroidRuntime(4862): ... 11 more
The line that is crashing is the line 45 of Scene3:
Button next = (Button) findViewById(R.id.wtf);
next.setOnClickListener(new View.OnClickListener() { // <-- THIS ONE
...
});
The cause is a NullPointerException. This means that the identifier "wtf" exists in R (this wouldn't compile otherwise) but is not found in the layer activity_scene3, as we wave the following statement line 38 of Scene3.onCreate():
setContentView(R.layout.activity_scene3); // and later on findViewById() returns `null`
You have to revisit this layout to ensure that the Button you are willing to access to actually exists, with the ID wtf.
Generally speaking, this is the danger in using a same ID in different layouts. This is prone to hide errors that would easily be found otherwise as this would just not compile.
Check your manifest file and add Scene3.java in it
<activity
android:name=".Scene3" >
</activity>
Always post question with exception, second this is may be you have not mention your other activity in manifest file like:
<activity
android:name=".Scene3">
</activity>
<activity
android:name=".GameOver">
</activity>

Unable to retrieve the value of textfield

i am the newbee in Android Development.
I had developed an app contains a login, the credentials must be passed in the text field and later it will call a webservice.
I am facing the issue as user and password is not getting copied at the required position.
Please help me out.
package com.authorwjf.http_get;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class Main extends Activity implements OnClickListener {
EditText txtUserName;
EditText txtPassword;
#Override
public void onCreate(Bundle savedInstanceState) {
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(false);
new LongRunningGetIO().execute();
}
private class LongRunningGetIO extends AsyncTask <Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n>0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n>0) out.append(new String(b, 0, n));
}
return out.toString();
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
String user= txtUserName.getText().toString();
String pass= txtPassword.getText().toString();
System.out.println("USERRRR"+user);
System.out.println(pass);
//String user="at#ril.com";
//String pass= "123456";
String accessTokenQry = "{"+
"\"uid\":\""+user+"\","+
"\"password\":\""+pass+"\","+
"\"consumptionDeviceId\":\"fder-et3w-3adw2-2erf\","+
"\"consumptionDeviceName\":\"Samsung Tab\""+
"}";
HttpPost httpPost = new HttpPost("http://devssg01.ril.com:8080/v2/dip/auth/login");
httpPost.setHeader("Content-Type",
"application/json");
httpPost.setHeader("X-API-Key",
"l7xx7914b8704b2d4b029ab9c4b1b9c66dbf");
StringEntity input;
try {
input = new StringEntity(accessTokenQry);
httpPost.setEntity(input);
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String text = null;
try {
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
protected void onPostExecute(String results) {
if (results!=null) {
EditText et = (EditText)findViewById(R.id.my_edit);
et.setText(results);
}
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(true);
}
}
}
The LogCat Output is:
08-10 01:20:23.977: W/dalvikvm(760): threadid=14: thread exiting with uncaught exception (group=0x414c4700)
08-10 01:20:23.984: E/AndroidRuntime(760): FATAL EXCEPTION: AsyncTask #4
08-10 01:20:23.984: E/AndroidRuntime(760): java.lang.RuntimeException: An error occured while executing doInBackground()
08-10 01:20:23.984: E/AndroidRuntime(760): at android.os.AsyncTask$3.done(AsyncTask.java:299)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.lang.Thread.run(Thread.java:841)
08-10 01:20:23.984: E/AndroidRuntime(760): Caused by: java.lang.NullPointerException
08-10 01:20:23.984: E/AndroidRuntime(760): at com.authorwjf.http_get.Main$LongRunningGetIO.doInBackground(Main.java:66)
08-10 01:20:23.984: E/AndroidRuntime(760): at com.authorwjf.http_get.Main$LongRunningGetIO.doInBackground(Main.java:1)
08-10 01:20:23.984: E/AndroidRuntime(760): at android.os.AsyncTask$2.call(AsyncTask.java:287)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
08-10 01:20:23.984: E/AndroidRuntime(760): ... 3 more
You are trying to initialize EditTexts before layout loaded.
If you want to get EditText on layout, you must initialize it after layout loaded.
Here is correct code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
}
use this
EditText textw3d =(EditText) findViewById(R.id.editText3d);
final String strd3d = textw3d.getText().toString();
I suggest following change in your code.
Just write following lines
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
above
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
Move the lines where you get the reference to text views after the setContentView function call:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
}
The fact is you need to call setContentView before initializing any widget in your layout because this is the call that "loads" your layout defined in layout_main.xml file into your activity.
Thanks a lot Guyz,
The issue is resolved now.
Special appreciation to JustWork
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
}

java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0

I'm new to android - I'm trying to populate textviews using data from external database but I'm receiving this error (LogCat below) I have had a long hard gander on the net but cant seem to find much to help me out.
LogCat
04-11 23:10:56.084: E/AndroidRuntime(333): FATAL EXCEPTION: main
04-11 23:10:56.084: E/AndroidRuntime(333): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.thickcrustdesigns.ufood/com.thickcrustdesigns.ufood.recipePage}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
04-11 23:10:56.084: E/AndroidRuntime(333): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
04-11 23:10:56.084: E/AndroidRuntime(333): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
04-11 23:10:56.084: E/AndroidRuntime(333): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
04-11 23:10:56.084: E/AndroidRuntime(333): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
04-11 23:10:56.084: E/AndroidRuntime(333): at android.os.Handler.dispatchMessage(Handler.java:99)
04-11 23:10:56.084: E/AndroidRuntime(333): at android.os.Looper.loop(Looper.java:123)
04-11 23:10:56.084: E/AndroidRuntime(333): at android.app.ActivityThread.main(ActivityThread.java:3683)
04-11 23:10:56.084: E/AndroidRuntime(333): at java.lang.reflect.Method.invokeNative(Native Method)
04-11 23:10:56.084: E/AndroidRuntime(333): at java.lang.reflect.Method.invoke(Method.java:507)
04-11 23:10:56.084: E/AndroidRuntime(333): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
04-11 23:10:56.084: E/AndroidRuntime(333): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
04-11 23:10:56.084: E/AndroidRuntime(333): at dalvik.system.NativeStart.main(Native Method)
04-11 23:10:56.084: E/AndroidRuntime(333): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
04-11 23:10:56.084: E/AndroidRuntime(333): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:257)
04-11 23:10:56.084: E/AndroidRuntime(333): at java.util.ArrayList.get(ArrayList.java:311)
04-11 23:10:56.084: E/AndroidRuntime(333): at com.thickcrustdesigns.ufood.recipePage.onCreate(recipePage.java:44)
04-11 23:10:56.084: E/AndroidRuntime(333): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-11 23:10:56.084: E/AndroidRuntime(333): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
04-11 23:10:56.084: E/AndroidRuntime(333): ... 11 more
recipePage
package com.thickcrustdesigns.ufood;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class recipePage extends Activity {
TextView txt_Recipe;
TextView txt_Ingredients;
TextView txt_Method;
Button btn_bk;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recipepage);
Bundle data = getIntent().getExtras();
String recipe = data.getString("recipie");
ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();
nvp.add(new BasicNameValuePair("request", "recipe"));
nvp.add(new BasicNameValuePair("recipe", recipe));
ArrayList<NameValuePair> nvp2 = new ArrayList<NameValuePair>();
nvp2.add(new BasicNameValuePair("request", "ingredients"));
nvp2.add(new BasicNameValuePair("recipe", recipe));
ArrayList<JSONObject> jsondefs = Request.fetchData(this, nvp);
String title = null;
try {
title = jsondefs.get(0).getString("Name");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String method = null;
try {
method = jsondefs.get(0).getString("Method");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrayList<JSONObject> jsonIngredients = Request.fetchData(this, nvp2);
String ingredients = "";
for (int i = 0; i < jsonIngredients.size(); i++){
String ji = null;
try {
ji = jsonIngredients.get(i).getString("Name") + "\n";
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ingredients += ji;
}
txt_Recipe.setText(title);
txt_Method.setText(method);
txt_Ingredients.setText(ingredients);
// Listening to button event
btn_bk.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(),
UFoodAppActivity.class);
startActivity(i);
}
});
}
}
request.java
package com.thickcrustdesigns.ufood;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
//import android.widget.TextView;
public class CatogPage extends ListActivity {
ListView listView1;
Button btn_bk;
String[] defs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.definition_main);
btn_bk = (Button) findViewById(R.id.btn_bk);
listView1 = (ListView) findViewById(android.R.id.list);
ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();
nvp.add(new BasicNameValuePair("request", "categories"));
ArrayList<JSONObject> jsondefs = Request.fetchData(this, nvp);
defs = new String[jsondefs.size()];
for (int i = 0; i < jsondefs.size(); i++) {
try {
defs[i] = jsondefs.get(i).getString("Name");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
uFoodAdapter adapter = new uFoodAdapter(this, R.layout.definition_list,
defs);
listView1.setAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String item = defs[position];
Intent i = new Intent(getApplicationContext(), Results.class);
i.putExtra("category", item);
startActivity(i);
}
});
btn_bk.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), CatogPage.class);
startActivity(i);
}
});
}
}
Many Thanks
Start looking on line 44 of recipePage.java
com.thickcrustdesigns.ufood.recipePage.onCreate(recipePage.java:44)
04-11 23:10:56.084: E/AndroidRuntime(333): at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-11 23:10:56.084: E/AndroidRuntime(333): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
MORE DETAILS:
Following line is not filling jsondefs
ArrayList<JSONObject> jsondefs = Request.fetchData(this, nvp);
Looks like this call is unsafe:
ArrayList<JSONObject> jsondefs = Request.fetchData(this, nvp);
String title = null;
try {
title = jsondefs.get(0).getString("Name"); //<--- Here jsondefs could be empty
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if jsondefs is empty, you could see the error you are mentionning.
Most likely thrown by one of the jsondefs.get(0)… You should add an if(!jsondefs.isEmpty()) and an else that prints something so that you know what the problem is.

Android radio streaming app crashes when you press pause or stop at the moment you haven't clicked play

When i start my app and press stop or pause the android app will crash. It works fine if you press play first and then stop or pause. I searched on google and stackoverflow but i couldn't find much about it. I think the problem is because of a NullPointerException but since i'm new too java it doesn't tell me much about the problem
The code:
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class myMain extends Activity implements
MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener,
MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener, OnClickListener {
private String TAG = getClass().getSimpleName();
private MediaPlayer mp= null;
private Button play;
private Button pause;
private Button stop;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
play = (Button) findViewById(R.id.play);
pause = (Button) findViewById(R.id.pause);
stop = (Button) findViewById(R.id.stop);
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
play();
}
});
pause.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
pause();
}
});
stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
stop();
}
});
}
private void play() {
Uri myUri = Uri.parse("url");
try {
if (mp == null) {
this.mp = new MediaPlayer();
} else {
mp.stop();
mp.reset();
}
mp.setDataSource(this, myUri); // Go to Initialized state
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setOnPreparedListener(this);
mp.setOnBufferingUpdateListener(this);
mp.setOnErrorListener(this);
mp.prepareAsync();
Log.d(TAG, "LoadClip Done");
} catch (Throwable t) {
Log.d(TAG, t.toString());
}
}
public void onPrepared(MediaPlayer mp) {
Log.d(TAG, "Stream is prepared");
mp.start();
}
private void pause() {
mp.pause();
}
private void stop() {
mp.stop();
}
#Override
public void onDestroy() {
super.onDestroy();
stop();
}
public void onCompletion(MediaPlayer mp) {
stop();
}
public boolean onError(MediaPlayer mp, int what, int extra) {
StringBuilder sb = new StringBuilder();
sb.append("Media Player Error: ");
switch (what) {
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
sb.append("Not Valid for Progressive Playback");
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
sb.append("Server Died");
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
sb.append("Unknown");
break;
default:
sb.append(" Non standard (");
sb.append(what);
sb.append(")");
}
sb.append(" (" + what + ") ");
sb.append(extra);
Log.e(TAG, sb.toString());
return true;
}
public void onBufferingUpdate(MediaPlayer mp, int percent) {
Log.d(TAG, "PlayerService onBufferingUpdate : " + percent + "%");
}
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
The errors:
02-11 20:45:43.837: D/AndroidRuntime(338): Shutting down VM
02-11 20:45:43.837: W/dalvikvm(338): threadid=1: thread exiting with uncaught exception (group=0x40015560)
02-11 20:45:43.857: E/AndroidRuntime(338): FATAL EXCEPTION: main
02-11 20:45:43.857: E/AndroidRuntime(338): java.lang.NullPointerException
02-11 20:45:43.857: E/AndroidRuntime(338): at wadio.media.internetradio.myMain.stop(myMain.java:95)
02-11 20:45:43.857: E/AndroidRuntime(338): at wadio.media.internetradio.myMain.access$2(myMain.java:94)
02-11 20:45:43.857: E/AndroidRuntime(338): at wadio.media.internetradio.myMain$3.onClick(myMain.java:55)
02-11 20:45:43.857: E/AndroidRuntime(338): at android.view.View.performClick(View.java:2485)
02-11 20:45:43.857: E/AndroidRuntime(338): at android.view.View$PerformClick.run(View.java:9080)
02-11 20:45:43.857: E/AndroidRuntime(338): at android.os.Handler.handleCallback(Handler.java:587)
02-11 20:45:43.857: E/AndroidRuntime(338): at android.os.Handler.dispatchMessage(Handler.java:92)
02-11 20:45:43.857: E/AndroidRuntime(338): at android.os.Looper.loop(Looper.java:123)
02-11 20:45:43.857: E/AndroidRuntime(338): at android.app.ActivityThread.main(ActivityThread.java:3683)
02-11 20:45:43.857: E/AndroidRuntime(338): at java.lang.reflect.Method.invokeNative(Native Method)
02-11 20:45:43.857: E/AndroidRuntime(338): at java.lang.reflect.Method.invoke(Method.java:507)
02-11 20:45:43.857: E/AndroidRuntime(338): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-11 20:45:43.857: E/AndroidRuntime(338): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-11 20:45:43.857: E/AndroidRuntime(338): at dalvik.system.NativeStart.main(Native Method)
In your stop() method you access the mp variable. However, the mp variable is null until you press play (and the play() method is called). So when you try to access the null variable a NullPointerException is thrown.
A very simple way to stop the NullPointerException is to do something like this:
private void pause() {
if(mp!=null) mp.pause();
}
private void stop() {
if(mp!=null) mp.stop();
}
Of course this solution doesn't account for cases where pause or stop is called twice. Take a look at the MediaPlayer documentation for more info on state management.

Categories