android.app.SuperNotCalledException: Activity did not call through to super.onCreate() - java

Here is my Android Media player code. I don't know what I am missing in this code, when I run with breakpoint at line MediaPlayer mp = new MediaPlayer() in Debug mode. All the files in zip folder is played. But when I run the application in normal mode the first file is played and then I get this error:
android.app.SuperNotCalledException: Activity {com.example.mediaplayer/com.example.mediaplayer.MainActivity} did not call through to super.onCreate()
Code:
package com.example.mediaplayer;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.commons.io.IOUtils;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.Button;
public class MainActivity extends Activity {
private MediaPlayer mp;
private static final String MAIN_TAG ="ERROR";
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
//final String file_loc= Environment.getExternalStorageDirectory().toString();
//Log.i("location",file_loc);
ZipFile zip = new ZipFile("/storage/emulated/0/AjeshDocument/sample.zip");
for(int i=1;i<7;i++){
ZipEntry entry = zip.getEntry("sample/rihanna_"+i+".mp3");
if (entry != null) {
InputStream in = zip.getInputStream(entry);
// see Note #3.
File tempFile = File.createTempFile("_AUDIO_", ".wav");
FileOutputStream out = new FileOutputStream(tempFile);
IOUtils.copy(in, out);
// do something with tempFile (like play it)
File f = tempFile;
try {
if (f.exists())
{
Log.i(MAIN_TAG,"Audio file found!");
MediaPlayer mp = new MediaPlayer();
FileInputStream fis = new FileInputStream(f);
mp.setDataSource(fis.getFD());
mp.prepare();
//mp.setLooping(false);
mp.start();
//mp.stop();
// mp.release();
Log.i(MAIN_TAG,"Pronounciation finished!");
}
else
{
Log.i(MAIN_TAG,"File doesn't exist!!");
}
}
catch (IOException e)
{
Log.i(MAIN_TAG,e.toString());
}
}
else {
// no such entry in the zip
}
} //for end
mp.release();
}
catch (Exception e) {
// handle your exception cases...
Log.i(MAIN_TAG,e.toString());
}
}
#Override
protected void onResume() {
Log.w("Info", "App Resume");
super.onResume();
}
#Override
protected void onStop() {
Log.w("Info", "App stopped");
super.onStop();
}
#Override
protected void onDestroy() {
Log.w("Info", "App destoryed");
super.onDestroy();
}
}

You didn't call the Activity's onCreate() method, i.e the super class' one. Add the call to MainActivity's onCreate() method:
public class MainActivity extends Activity {
private MediaPlayer mp;
private static final String MAIN_TAG ="ERROR";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // this line is missing
// your code below ...

Related

App crashes when writing sensor data on a .txt file in a public folder

I am very new to Java & Android but I need to write a txt file which contains sensor data in Environment.DIRECTORY_DOCUMENTS. I scanned questions about it and tried examples. Version used here is Android 5.1 (API 22). My final trial is here:
package com.example.accgy;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.TextView;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class MainActivity extends AppCompatActivity implements SensorEventListener {
private static final String TAG = "MainActivity";
private SensorManager sensorManager;
Sensor accelerometer;
Sensor gyroscope;
FileWriter writer;
TextView Xa,Ya,Za,Xg,Yg,Zg;
float[] accel = new float[3];
float[] gyro = new float[3];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Xa = (TextView)findViewById(R.id.Xa);
Ya = (TextView)findViewById(R.id.Ya);
Za = (TextView)findViewById(R.id.Za);
Xg = (TextView)findViewById(R.id.Xg);
Yg = (TextView)findViewById(R.id.Yg);
Zg = (TextView)findViewById(R.id.Zg);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
gyroscope = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
}
#Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
public void onStart(View view){
super.onStart();
sensorManager.registerListener(this,accelerometer,SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(this,gyroscope,SensorManager.SENSOR_DELAY_NORMAL);
String savedirect = getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).toString();
try {
File folder = new File(savedirect,"/example.txt");
folder.mkdir();
writer = new FileWriter(folder);
} catch (IOException e) {
e.printStackTrace();
}
}
public void onStop(View view) {
super.onStop();
sensorManager.unregisterListener(this);
try {
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER){
accel = sensorEvent.values;
Xa.setText("Xa: " + accel[0]);
Ya.setText("Ya: " + accel[1]);
Za.setText("Za: " + accel[2]);
}
if (sensorEvent.sensor.getType() == Sensor.TYPE_GYROSCOPE) {
gyro = sensorEvent.values;
Xg.setText("Xg: " + gyro[0]);
Yg.setText("Yg: " + gyro[1]);
Zg.setText("Zg: " + gyro[2]);
}
try {
writer.write(accel[0]+" "+accel[1]+" "+accel[2]+" "+gyro[0]+" "+gyro[1]+" "+gyro[2]+"\n");
} catch (IOException e) {
e.printStackTrace();
}
}
}
But when I run the code over a physical device and touch the start button, the app crashes. Is there a way to prevent this?
Note: I also provide permission for writing external storages in manifest file.
EDIT: I checked logcat and found:
Java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.FileWriter.write(java.lang.String)' on a null object reference
at:
try {
writer.write(accel[0]+" "+accel[1]+" "+accel[2]+" "+gyro[0]+" "+gyro[1]+" "+gyro[2]+"\n");
} catch (IOException e) {
e.printStackTrace();
}
When I change this line:
writer = new FileWriter(folder);
to this:
writer = new FileWriter(folder+"example.txt",true);
App succesfully writes the data. But the name of file becomes "Documentsexample.txt". But my desire is "example.txt". I tried to remove "folder+" part from the line, tried to create folder in different ways. But same error returns after re-run. It seems no way other than above.

After 'takePicture' call, 'onPictureTaken' response is dependent on location in app...why?

I'm trying to build an app which will periodically call the Camera to take a picture and save it.
My problem is that unless I put the 'takePictuce' call in the 'onCreate' the response to 'takePicture' (onPictureTaken) is never called.
I've broken down the app as simply as possible to illustrate.
if a class to handle the camera is partially defined as:
public class CameraHandler {
private Camera mCamera;
public CameraHandler(){
mCamera = Camera.open();
mCamera.setPreviewTexture(new SurfaceTexture(10));
mCamera.startPreview();
mCamera.takePicture(null, null, mPicture);
}
Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
} catch (IOException e) { }
}
};
Then when I put the following code into MainActivity.java, 'onPictureTaken' IS called when CameraHandler is instantiated.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CameraHandler cameraHandler = new CameraHandler();
}
However, putting the call to instantiate CameraHandler in a click event in the MainActivity.java will NOT call 'onPictureTaken' in response to the takePicture call.
(This snippet is located in MainACtivity.java)
public void onClickListener(View view){
CameraHandler cameraHandler = new CameraHandler();
}
So why is this occurring, and how can I get the call to take a picture in the class where it belongs and not in the 'main' of the program?
All help welcome
Finally figured out how to set the phone to take timed pics without any screen display.
There were 2 main issues I struggled with. First, I wanted to take the pics without displaying to screen. Along those lines, I found an example where they used :
mCamera.setPreviewTexture(new SurfaceTexture(10));
and nothing showed on the screen when using this preview method. It appears that some sort of preview is required. Another method was to set the preview to 1 pixel. This method had examples online which appeared to work as well, but I did not try it.
The second and bigger problem had to do with 'onPictureTaken' method. This method processes your picture after the 'takePicture' call.
It seemed that no matter what looping method I used, or where in the code the call to 'takePicture' was located, all of the 'onPictureTaken' methods were queued up and called one after another once the parent of the 'takePicture' caller ended.
Although the picture data processed by onPictureTaken were in a proper time sequence, I could see that having several hundred pics stored and waiting to process could cause problems, and a method needed to be found where on pic was processed and stored before the next pic was taken.
Along those lines, I stumbled upon the AlarmManager and coupled that with the BroadcastReceiver and Future classes to solve the problem.
What I've done is set the alarmManger to go off at a set time or time frequency. The BroadcaseReceiver captures this call & in turn calls a method which creates
a thread where a 'Future' object makes the call to take a picture.
'Future' object is nice, because it will wait for the physical camera to take the picture (takePicture) and then process it (onPictureTaken). This all occurs in one thread, then terminates. So no queuing of pics to process and each picture sequence is handled separately.
Code is contained below. Note that some of the default 'Overrides' have been left out to save space. Also, the visible screen was basically a button which captured the click event...very basic.
MainActivity.java:
package myTest.com.test;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class MainActivity extends Activity {
CameraHandler cameraHandler;
public BroadcastReceiver br;
public PendingIntent pi;
public AlarmManager am;
final static private long LOOPTIME = 20000;
private static final ExecutorService threadpool = Executors.newFixedThreadPool(3);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setup();
}
private void setup() {
try{
cameraHandler = new CameraHandler();
br = new BroadcastReceiver() {
#Override
public void onReceive(Context c, Intent i) {
//Toast.makeText(c, "Taking a pic!", Toast.LENGTH_LONG).show();
TryAThread();
}
};
registerReceiver(br, new IntentFilter("com.timedActivity.activity") );
pi = PendingIntent.getBroadcast(this, 0, new Intent("com.timedActivity.activity"), 0);
am = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));
}
catch (Exception e){ }
}
private void TryAThread() {
try{
CameraCaller cameraCaller = new CameraCaller(cameraHandler);
Future future = threadpool.submit(cameraCaller);
while (!future.isDone()) {
try {
Thread.sleep(5000);
} catch (Exception ex) { }
}
}
catch (Exception e){ }
}
#Override
protected void onDestroy() {
am.cancel(pi);
unregisterReceiver(br);
super.onDestroy();
}
public void onClickListener(View view){
try{
am.setRepeating(am.ELAPSED_REALTIME,SystemClock.elapsedRealtime(), LOOPTIME, pi);
}
catch (Exception e){ }
}
}
CameraCaller.java:.
package myTest.com.test;
import java.util.concurrent.Callable;
public class CameraCaller implements Callable {
private CameraHandler cameraHandler;
public CameraCaller(CameraHandler ch){
cameraHandler = ch;
}
#Override
public Object call() throws Exception {
cameraHandler.takeAPic();
return true;
}
}
CameraHandler.java:.
package myTest.com.test;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.os.Environment;
import android.util.Log;
import junit.runner.Version;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CameraHandler implements Camera.PictureCallback{
private Camera mCamera;
public CameraHandler(){
}
public Boolean takeAPic(){
try{
if (mCamera == null){
mCamera = Camera.open();
mCamera.enableShutterSound(false);
try {
mCamera.setPreviewTexture(new SurfaceTexture(10));
}
catch (IOException e1) {Log.e(Version.id(), e1.getMessage());
}
}
mCamera.startPreview();
mCamera.takePicture(null, null, this);
}
catch (Exception ex){ }
return true;
}
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
} catch (IOException e) { }
try {
Thread.sleep(2000);
}catch (Exception ex){}
}
public static File getOutputMediaFile() {
File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File mediaStorageDir = new File(file, "MyCameraApp");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
return mediaFile;
}
}

Nanohttpd in android do not serve files

i am developing a android application which uses nanohttpd to create a webserver my code do not give me any error but the server is not running because when i go to xx.xxx.xxx.xxx:8765/index.htm then it gives my no result this is my code:
Please Help...
package dolphin.developers.com;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import dolphin.devlopers.com.R;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
public class AlertDialogActivity extends Activity {
private static final int PORT = 8765;
private MyHTTPD server;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onResume() {
super.onResume();
try {
server = new MyHTTPD();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onPause() {
super.onPause();
if (server != null)
server.stop();
}
public class MyHTTPD extends NanoHTTPD {
public MyHTTPD() throws IOException {
super(PORT, null);
}
public Response serve( String uri, String method, Properties header, Properties parms, Properties files ) {
File rootsd = Environment.getExternalStorageDirectory();
File path = new File(rootsd.getAbsolutePath() + "/samer");
Response r = super.serveFile("/index.htm", header, path, true);
return r;
}
}
}
Looks like a simple fix --- in onResume() you create the server but you still need to call "start()" on it.

Error Playing File: NullPointerException in Android

I want to play an mp3 file in android, but i get this error:
java.lang.NullPointerException at HelloAndroid.playMusic
My code below
package com.bestvalue.hello;
/*import android.util.Log;*/
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.media.MediaPlayer;
import android.net.Uri;
public class HelloAndroid extends Activity {
public static final String DebugTag = "LogInfo";
public MediaPlayer mp;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setText("keke napep");
playMusic();
setContentView(tv);
Log.i(DebugTag, "Info about my app na");
}
public void playMusic () {
try {
Uri fileName = Uri.parse("http://www.perlgurl.org/podcast/archives/podcasts/PerlgurlPromo.mp3");
mp= MediaPlayer.create(this, fileName);
mp.start();
} catch (Exception e){
Log.e(DebugTag, "Error Playing File", e);
}
}
#Override
protected void onStop() {
if (mp != null) {
mp.stop();
mp.release();
}
super.onStop();
}
}
What will i do to fix this error?
Thanks
UPDATE
package com.bestvalue.hello;
/*import android.util.Log;*/
import android.app.Activity;
//import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.media.AudioManager;
import android.media.MediaPlayer;
public class HelloAndroid extends Activity {
public static final String DebugTag = "LogInfo";
private MediaPlayer mp = new MediaPlayer();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setText("keke napep");
playMusic();
setContentView(tv);
}
public void playMusic () {
try {
String url = "http://www.perlgurl.org/podcast/archives/podcasts/PerlgurlPromo.mp3";
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setDataSource(url);
mp.prepare();
mp.start();
} catch (Exception e){
Log.e(DebugTag, "Error Playing File", e);
}
}
#Override
protected void onStop() {
if (mp != null) {
mp.stop();
mp.release();
}
super.onStop();
}
}
After implementing some of the answers, i now get this error: java.io.IOException: Prepare Failed .: status = 0x1
add mp.prepare(); before mp.start();
Your issue is you aren't checking mp before you call methods on it. According to the documentation, if MediaPlayer.create fails, it will return null.
Rule of thumb with NullPointerExceptions: go back and check your returns. Something is usually returning null when you aren't expecting it to, and you try to call a method on it. In this case, you aren't calling anything on fileName, so that's safe. You're calling something on mp, so that's probably what's doing you in.
[edit]
Why the audio isn't playing:
You aren't calling setAudioStreamType(AudioManager.STREAM_MUSIC); and the use of URIs in the creation of a MediaPlayer instance is only for locally stored media. Network media needs to have its location set by calling setDataSource(context, uri);.
From the (very good) documentation:
Uri myUri = ....; // initialize Uri here
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(getApplicationContext(), myUri);
mediaPlayer.prepare();
mediaPlayer.start();`

Android VideoRecording error, cannot create path to file

java.lang.IOException, path to file cannot be created. my catch is working by dont know why is isnt being created?
Im not sure why im getting this error, i assumed the setOutputFile() would create the file ..
any help appreciated, as there are a few errors in DDMS
this is my viderecorder class:
package com.sg86.quickrecord;
import java.io.File;
import java.io.IOException;
import android.media.MediaRecorder;
import android.os.Environment;
public class VideoRecorder {
final MediaRecorder recorder = new MediaRecorder();
final String path;
/**
* create a new video recording stored in SDcard Root
*/
public VideoRecorder(String path) {
this.path = organisePath(path);
}
private String organisePath(String path) {
if (!path.startsWith("/")) {
path = "/" + path;
}
if (!path.contains(".")) {
path += ".3gp";
}
return Environment.getExternalStorageDirectory().getAbsolutePath() + path;
}
public void start() throws IOException {
String state = android.os.Environment.getExternalStorageState();
if(!state.equals(android.os.Environment.MEDIA_MOUNTED)) {
throw new IOException("SD Card is not mounted. It is " + state + ".");
}
// make sure the directory we plan to store the recording in exists
File directory = new File(path).getParentFile();
if (!directory.exists() && !directory.mkdirs()) {
throw new IOException("Path to file could not be created.");
}
recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
recorder.setOutputFile(path);
recorder.prepare();
recorder.start();
}
public void stop() throws IOException {
recorder.stop();
recorder.release();
}
}
this is my main activity
package com.sg86.quickrecord;
import java.io.File;
import java.io.IOException;
import java.lang.IllegalStateException;
import android.app.Activity;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
#SuppressWarnings("unused")
public class QuickRecord extends Activity {
public static final String WRITE_EXTERNAL_STORAGE = "android.permission.WRITE_EXTERNAL_STORAGE";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button recordBtn = (Button) findViewById(R.id.button01);
Button stopBtn = (Button) findViewById(R.id.button02);
final VideoRecorder record = new VideoRecorder("/QuickRecord/recording");
recordBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
try {
record.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
stopBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
record.stop();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
Did you add <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> to your AndroidManifest.xml file?
See Security and Permissions for more details.

Categories