Google Glass Camera: setPreviewCallback - callback

I have an operating android app that utilizes preview callbacks, to process the image after every frame from the preview (the preview is paused for a minute while the calculations take place). It works great! But, now I am trying to get Google Glass to do the same thing: activate Preview, activate preview callback, activating the calculations.
This issue likely has to do with how Camera is defined:
Camera mCamera = null;
but, I cannot define it as Camera.open(); with Google Glass because it fails. Thus when i get to defining the callback, I'm told it may produce a NullPointerException, and indeed I get the following error string:
Process: com.ead.glasscam.app, PID: 14231
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ead.glasscam.app/com.ead.glasscam.app.MainActivity}:
java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2235)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2285)
at android.app.ActivityThread.access$800(ActivityThread.java:138)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1236)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:149)
at android.app.ActivityThread.main(ActivityThread.java:5061)
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:794)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:610)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.ead.glasscam.app.MainActivity.onCreate(MainActivity.java:100)
at android.app.Activity.performCreate(Activity.java:5236)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1089)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2199)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2285)
            at android.app.ActivityThread.access$800(ActivityThread.java:138)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1236)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:149)
            at android.app.ActivityThread.main(ActivityThread.java:5061)
            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:794)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:610)
            at dalvik.system.NativeStart.main(Native Method)
So, the code:
// Attach a callback for preview
mPreviewCallback camCallback = new mPreviewCallback();
mCamera.setPreviewCallback(camCallback);
What is mPreviewCallback?:
public class mPreviewCallback implements Camera.PreviewCallback {
public void onPreviewFrame(byte[] data, final Camera camera){
Log.i("CAMERA", "Triggered Preview Frame");
}
}
I really don't understand how to do this simple process on Android, with Google Glass. Thank you for reading.

Checkout this example from jaredsburrows, it uses the camera preview on Glass and I used it in a project once (It Works! ;) )
https://github.com/jaredsburrows/OpenQuartz/tree/master/example-apps/OG_CameraApp
public class CameraView extends SurfaceView implements SurfaceHolder.Callback
{
private SurfaceHolder surfaceHolder = null;
private Camera camera = null;
#SuppressWarnings("deprecation")
public CameraView(Context context)
{
super(context);
surfaceHolder = this.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
/*
* (non-Javadoc)
* #see android.view.SurfaceHolder.Callback#surfaceCreated(android.view.SurfaceHolder)
*/
#Override
public void surfaceCreated(SurfaceHolder holder)
{
camera = Camera.open();
// Set the Hotfix for Google Glass
this.setCameraParameters(camera);
// Show the Camera display
try
{
camera.setPreviewDisplay(holder);
}
catch (Exception e)
{
this.releaseCamera();
}
}
/*
* (non-Javadoc)
* #see android.view.SurfaceHolder.Callback#surfaceChanged(android.view.SurfaceHolder, int, int, int)
*/
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
{
// Start the preview for surfaceChanged
if (camera != null)
{
camera.startPreview();
}
}
/*
* (non-Javadoc)
* #see android.view.SurfaceHolder.Callback#surfaceDestroyed(android.view.SurfaceHolder)
*/
#Override
public void surfaceDestroyed(SurfaceHolder holder)
{
// Do not hold the camera during surfaceDestroyed - view should be gone
this.releaseCamera();
}
/**
* Important HotFix for Google Glass (post-XE11) update
* #param camera Object
*/
public void setCameraParameters(Camera camera)
{
if (camera != null)
{
Parameters parameters = camera.getParameters();
parameters.setPreviewFpsRange(30000, 30000);
camera.setParameters(parameters);
}
}
/**
* Release the camera from use
*/
public void releaseCamera()
{
if (camera != null)
{
camera.release();
camera = null;
}
}
}

Related

How to appoint values from Firestore to Datapoints

I want to graph blood glucose level with time. Im getting this error
FATAL EXCEPTION: main
Process: com.example.diabefreemob, PID: 4202
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.diabefreemob/com.example.diabefreemob.graph}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.firestore.CollectionReference com.google.firebase.firestore.FirebaseFirestore.collection(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
public class graph extends AppCompatActivity {
GraphView graphView;
FirebaseFirestore firestore;
FirebaseAuth mAuth;
String Email;
DocumentReference documentReference;
CollectionReference collectionReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_graph);
// on below line we are initializing our graph view.
graphView = findViewById(R.id.idGraphView);
mAuth = FirebaseAuth.getInstance();
// Email = Objects.requireNonNull(mAuth.getCurrentUser()).getEmail();
// firestore.collection("users").document(firebase.auth().currentUser.uid).collection("BG").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
List<DataPoint> datapoints = new ArrayList();
Query query = firestore.collection("users").document(Email).collection("BG")
.orderBy("timeStamp");
query.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot querySnapshot) {
Log.i(TAG, "Successfully fetched data from firestore");
int index = 0;
for (QueryDocumentSnapshot document : querySnapshot) {
Map data = document.getData();
String glucoseAmount = (String) data.get("Blood Glucose");
datapoints.add(new DataPoint(Double.parseDouble(glucoseAmount), index));
index++;
}
}
});
LineGraphSeries<DataPoint> series = new LineGraphSeries<>(datapoints.toArray(new DataPoint[datapoints.size()]));
graphView.setTitle("My Graph View");
graphView.setTitleColor(R.color.purple_200);
graphView.setTitleTextSize(18);
graphView.addSeries(series);
}
}
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.firestore.CollectionReference com.google.firebase.firestore.FirebaseFirestore.collection(java.lang.String)' on a null object reference
at com.example.diabefreemob.graph.onCreate(graph.java:60)
at android.app.Activity.performCreate(Activity.java:8000)
at android.app.Activity.performCreate(Activity.java:7984)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)`
Can someone please explain where im going wrong

Error switching screen Java Fx FXML

Hello. I'm kinda stuck.
I got an error, I'm not able to close my previous window to set the new one.
Here is my controller :
public class Controller implements Initializable {
//------------- init Order -------------//
#FXML
private Label text10;
#FXML
private Label text20;
#FXML
private Label text30;
#FXML
private Label text40;
#FXML
private Label text50;
#FXML
private TextField entry10;
#FXML
private TextField entry20;
#FXML
private TextField entry30;
#FXML
private Button btnConnect10;
//------------- init Reception -------------//
#FXML
private Label text11;
#FXML
private Label text21;
#FXML
private Label text31;
#FXML
private Label text41;
#FXML
private Label text51;
#FXML
private TextField entry11;
#FXML
private TextField entry21;
#FXML
private TextField entry31;
#FXML
private Button btnConnect11;
//------------- init Connexion -------------//
#FXML
private ImageView img;
#FXML
private Label user;
#FXML
private Label password;
#FXML
private TextField usr;
#FXML
private PasswordField passwd;
#FXML
private Button btnConnect13;
//------------- init popup -------------//
#FXML
private Label popup;
//------------- Stage -------------//
Stage prevStage;
public void setPrevStage(Stage stage) {
this.prevStage = stage;
}
#FXML
private void buttonPressed(KeyEvent e) {
if (e.getCode() == KeyCode.ENTER) {
System.out.println("je suis un krab");
}
}
#FXML
private void handleButtonAction(ActionEvent event) throws IOException {
//init classe
Controller ctr = new Controller();
//fenetre Commande
if (event.getSource() == btnConnect10) {
ctr.Commande(entry10.getText(), entry20.getText(), entry30.getText());
}
//fenetre Reception
if (event.getSource() == btnConnect11) {
ctr.Reception(entry11.getText(), entry21.getText(), entry31.getText());
}
//fenetre connexion
if (event.getSource() == btnConnect13) {
ctr.Connect(usr.getText(), passwd.getText());
}
}
//Menu d'affchage
private void menu(int access) throws IOException {
//init fenetre
Stage stage = new Stage();
Pane myPane = null;
Scene scene;
switch (access) {
case 1:
stage.setTitle("Commande OR tool");
myPane = FXMLLoader.load(getClass().getResource("CommandeFXML.fxml"));
scene = new Scene(myPane);
stage.setScene(scene);
prevStage.close();
stage.show();
break;
case 2:
//recupère les infos de la fenetre
stage.setTitle("Réception OR tool");
myPane = FXMLLoader.load(getClass().getResource("ReceptionFXML.fxml"));
scene = new Scene(myPane);
stage.setScene(scene);
prevStage.close();
stage.show();
break;
case 3:
stage.setTitle("Admin OR tool");
myPane = FXMLLoader.load(getClass().getResource("AdminFXML.fxml"));
scene = new Scene(myPane);
stage.setScene(scene);
prevStage.close();
stage.show();
break;
default:
//error
System.out.println("erreur changing window");
}
}private void Connect(String getuser, String getpasswd) throws IOException {
ConnectBDD bdd = new ConnectBDD();
Controller ctr = new Controller();
System.out.println("user = "+getuser+"\npassword ="+getpasswd);
//test
if (!getuser.isEmpty() && !getpasswd.isEmpty()) {
//check if user exist
if (bdd.connectUserTest(getuser, getpasswd) == true) {
//get the access level
int acces = bdd.connectUser (getuser, getpasswd);
//Changing window
ctr.menu(acces);
}
else {
System.out.println("user not in the data base");
}
} //message d'erreur
//to do faire un pop up
else {
System.out.println("no entry");
}
}
And the main
public class JavaFX extends Application {
#FXML
#Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("OR tool");
FXMLLoader myLoader = new FXMLLoader(getClass().getResource("ConnectFXML.fxml"));
Pane myPane = (Pane) myLoader.load();
Controller controller = (Controller) myLoader.getController();
controller.setPrevStage(primaryStage);
Scene myScene = new Scene(myPane);
primaryStage.setScene(myScene);
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
I got a nice stack
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1774)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Node.fireEvent(Node.java:8411)
at javafx.scene.control.Button.fire(Button.java:185)
at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:380)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:294)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(GlassViewEventHandler.java:416)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:415)
at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
at com.sun.glass.ui.View.notifyMouse(View.java:937)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1769)
... 48 more
The most important part is
Caused by: java.lang.NullPointerException
at javafx.Controller.menu(Controller.java:149)
at javafx.Controller.Connect(Controller.java:303)
at javafx.Controller.handleButtonAction(Controller.java:130)
ligne 149 is when i try to close the previous windows. "prevStage.close();" in the menu function of the controller
ligne 303 is the call of the fuction menu in the test of connexion.
ligne 130 is in the handleButtonAction when i call the connect function
When I try to open a new window in the handler it works perfectly. But I need to adpat the window to the access level of the user.
But now I've got a java.lang.NullPointerException.
#FXML
private void handleButtonAction(ActionEvent event) throws IOException {//init fenetre
Stage stage = new Stage();
Pane myPane = null;
Scene scene;stage.setTitle("Réception OR tool");
myPane = FXMLLoader.load(getClass().getResource("ReceptionFXML.fxml"));
scene = new Scene(myPane);
stage.setScene(scene);
prevStage.close();
stage.show(); }
You are repeatedly creating new controller instances in your code:
Controller ctr = new Controller();
For these new instances, nothing will be initialized: you never call setPrevStage() on these instances so prevStage will not be initialized and, since these instances are not created by the FXMLLoader, the #FXML-annotated fields will not be initialized.
Remove the calls to the Controller constructor, and invoke the methods on the current instance:
#FXML
private void handleButtonAction(ActionEvent event) throws IOException {
// remove this:
//Controller ctr = new Controller();
//fenetre Commande
if (event.getSource() == btnConnect10) {
// replace this
// ctr.Commande(entry10.getText(), entry20.getText(), entry30.getText());
// with this
Commande(entry10.getText(), entry20.getText(), entry30.getText());
// or equivalently
// this.Commande(entry10.getText(), entry20.getText(), entry30.getText());
}
//fenetre Reception
if (event.getSource() == btnConnect11) {
Reception(entry11.getText(), entry21.getText(), entry31.getText());
}
//fenetre connexion
if (event.getSource() == btnConnect13) {
Connect(usr.getText(), passwd.getText());
}
}
and similarly throughout your code.

Android - taking pictures every minute with Camera

I have a problem to solve - I was trying everything and nothing is working.
I am writing an application which should take picture every minute (period between pictures might be longer in future, but that isn't important) and upload it to ftp server. I am trying to open camera only for a while before taking photo and after taking photo release it and stop preview. But that doesn't work - there isn't even one picture taken. Opening camera etc. is doing by handler. If I put in handler only takePicture method - app works fine (and open camera once and keep it open in onCreate method), but I want to release camera and open it before taking picture to save battery.
I attach my source code and logcat.
MainActivity.java
public class MainActivity extends ActionBarActivity {
private Camera mCamera;
private CameraPreview mPreview;
private File pictureFile;
private File mediaStorageDir;
private Context context;
private Handler handler;
public Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d("TAG", "Error creating media file, check storage permissions: ");
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d("TAG", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("TAG", "Error accessing file: " + e.getMessage());
}
Log.d("ftp", "photo taken: " + pictureFile);
mCamera.release();
startFTP();
}
};
private Runnable runnable = new Runnable() {
#Override
public void run() {
try {
mCamera = Camera.open();
} catch (Exception e) {
}
Camera.Parameters params = mCamera.getParameters();
params.setPictureSize(1920, 1080);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
params.set("orientation", "portrait");
params.set("rotation", 90);
}
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
params.set("orientation", "landscape");
}
mCamera.setParameters(params);
mPreview = new CameraPreview(context, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
mCamera.startPreview();
mCamera.takePicture(null, null, mPicture);
try {
this.wait(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.postDelayed(this, 60000);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = getApplicationContext();
handler = new Handler();
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
handler.post(runnable);
}
}
);
}
public void startFTP() {
new Thread(new Runnable() {
#Override
public void run() {
Log.d("ftp", "photo uploading started: " + pictureFile);
String sendingPictureName = pictureFile.getName();
String serverAddress = "1111111";
String userId = "111111";
String password = "111111";
FTPClient ftp = new FTPClient();
try {
ftp.connect(serverAddress);
ftp.login(userId, password);
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
}
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
ftp.changeWorkingDirectory("/111111");
InputStream input;
input = new FileInputStream(pictureFile);
if (ftp.storeFile(pictureFile.getName(), input)) {
File fileToDelete = new File(mediaStorageDir.getPath() +"/"+ sendingPictureName);
//Log.d("ftp", "sciezka do usuwanego pliku: " + fileToDelete.getAbsolutePath());
fileToDelete.delete();
}
input.close();
Log.d("ftp", "photo uploading ended: " + sendingPictureName);
ftp.logout();
ftp.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private File getOutputMediaFile() {
mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_"+ timeStamp + ".jpg");
return mediaFile;
}
public void cancelTimer(View view) {
handler.removeCallbacks(runnable);
}
}
CameraPreview.java
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder mHolder;
private Camera mCamera;
public CameraPreview(Context context, Camera camera) {
super(context);
mCamera = camera;
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
try {
mCamera.setPreviewDisplay(holder);
mCamera.setDisplayOrientation(90);
mCamera.startPreview();
} catch (IOException e) {
Log.d("TAG", "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
if (mHolder.getSurface() == null){
// preview surface does not exist
return;
}
try {
mCamera.stopPreview();
} catch (Exception e){
}
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e){
Log.d("TAG", "Error starting camera preview: " + e.getMessage());
}
}
}
activity_main.xml - it's layout only for testing and it isn't perfect
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<FrameLayout
android:id="#+id/camera_preview"
android:layout_width="500px"
android:layout_height="500px"
android:layout_weight="0.1"
android:layout_above="#+id/button_capture" />
<Button
android:id="#+id/button_capture"
android:text="start timer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:layout_alignParentEnd="false"
android:layout_alignParentStart="false"
android:layout_centerVertical="true" />
<Button
android:id="#+id/timer_button"
android:text="stop timer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:layout_below="#+id/button_capture"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="false"
android:onClick="cancelTimer" />
Logcat:
08-24 09:42:42.828 8935-8935/? E/Zygote﹕ MountEmulatedStorage()
08-24 09:42:42.828 8935-8935/? I/libpersona﹕ KNOX_SDCARD checking this for 10185
08-24 09:42:42.828 8935-8935/? E/Zygote﹕ v2
08-24 09:42:42.828 8935-8935/? I/libpersona﹕ KNOX_SDCARD not a persona
08-24 09:42:42.828 8935-8935/? I/SELinux﹕ Function: selinux_compare_spd_ram , priority [2] , priority version is VE=SEPF_SM-A500FU_5.0.2_0023
08-24 09:42:42.838 8935-8935/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
08-24 09:42:42.838 8935-8935/? I/art﹕ Late-enabling -Xcheck:jni
08-24 09:42:42.878 8935-8935/? D/TimaKeyStoreProvider﹕ TimaSignature is unavailable
08-24 09:42:42.878 8935-8935/? D/ActivityThread﹕ Added TimaKeyStore provider
08-24 09:42:42.988 8935-8935/com.example.dawid.camerabezpodgladu D/PhoneWindow﹕ *FMB* installDecor mIsFloating : false
08-24 09:42:42.988 8935-8935/com.example.dawid.camerabezpodgladu D/PhoneWindow﹕ *FMB* installDecor flags : -2139029248
08-24 09:42:43.108 8935-8951/com.example.dawid.camerabezpodgladu D/OpenGLRenderer﹕ Render dirty regions requested: true
08-24 09:42:43.118 8935-8935/com.example.dawid.camerabezpodgladu D/PhoneWindow﹕ *FMB* isFloatingMenuEnabled mFloatingMenuBtn : null
08-24 09:42:43.118 8935-8935/com.example.dawid.camerabezpodgladu D/PhoneWindow﹕ *FMB* isFloatingMenuEnabled return false
08-24 09:42:43.138 8935-8935/com.example.dawid.camerabezpodgladu D/SRIB_DCS﹕ log_dcs ThreadedRenderer::initialize entered!
08-24 09:42:43.138 8935-8951/com.example.dawid.camerabezpodgladu I/Adreno-EGL﹕ <qeglDrvAPI_eglInitialize:379>: EGL 1.4 QUALCOMM build: SKARAJGA_AU_LINUX_ANDROID_LA.BR.1.1.2_RB1.05.00.02.031.018+PATCH[ES]_msm8916_32_refs/tags/AU_LINUX_ANDROID_LA.BR.1.1.2_RB1.05.00.02.031.018__release_ENGG (I856e09677e)
OpenGL ES Shader Compiler Version: E031.25.03.02
Build Date: 04/06/15 Mon
Local Branch:
Remote Branch: refs/tags/AU_LINUX_ANDROID_LA.BR.1.1.2_RB1.05.00.02.031.018
Local Patches: 112c106f3772623daa7b4181c6cf23491044ead1 Revert "Disable ASTC on A405"
58a118cb818fdc906095a49a90977c15f9d3b223 Remove ASTC
08-24 09:42:43.138 8935-8951/com.example.dawid.camerabezpodgladu I/OpenGLRenderer﹕ Initialized EGL, version 1.4
08-24 09:42:43.158 8935-8951/com.example.dawid.camerabezpodgladu D/OpenGLRenderer﹕ Get maximum texture size. GL_MAX_TEXTURE_SIZE is 4096
08-24 09:42:43.158 8935-8951/com.example.dawid.camerabezpodgladu D/OpenGLRenderer﹕ Enabling debug mode 0
08-24 09:42:43.258 8935-8935/com.example.dawid.camerabezpodgladu I/Timeline﹕ Timeline: Activity_idle id: android.os.BinderProxy#3d659231 time:4110726
08-24 09:42:44.648 8935-8935/com.example.dawid.camerabezpodgladu D/ViewRootImpl﹕ ViewPostImeInputStage ACTION_DOWN
08-24 09:42:45.678 8935-8935/com.example.dawid.camerabezpodgladu I/Choreographer﹕ Skipped 34 frames! The application may be doing too much work on its main thread.
08-24 09:43:45.138 8935-8935/com.example.dawid.camerabezpodgladu W/CameraBase﹕ An error occurred while connecting to camera: 0
08-24 09:43:45.498 8935-8935/com.example.dawid.camerabezpodgladu D/AndroidRuntime﹕ Shutting down VM
08-24 09:43:45.498 8935-8935/com.example.dawid.camerabezpodgladu E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.dawid.camerabezpodgladu, PID: 8935
java.lang.RuntimeException: startPreview failed
at android.hardware.Camera.startPreview(Native Method)
at com.example.dawid.camerabezpodgladu.CameraPreview.surfaceCreated(CameraPreview.java:31)
at android.view.SurfaceView.updateWindow(SurfaceView.java:682)
at android.view.SurfaceView$3.onPreDraw(SurfaceView.java:200)
at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:921)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2226)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1239)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6752)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:777)
at android.view.Choreographer.doCallbacks(Choreographer.java:590)
at android.view.Choreographer.doFrame(Choreographer.java:560)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:763)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6145)
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:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
08-24 09:43:48.818 8935-8935/com.example.dawid.camerabezpodgladu I/Process﹕ Sending signal. PID: 8935 SIG: 9
Even once method takePicture isn't called. Error is getting from bad realesing camera and reopening it after minute (next handler action).
I will be very thankful for even one tip
Dawid
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. This is where the first answer (above) was tripping me up.
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;
}
}
Well David, you want 1 tip? I'm working on a similar problem and this may get you a little further down the road...to where I'm currently stuck.
I can take a picture without preview using the following.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cameraHandler = new CameraHandler();
tryThis();
}
private void tryThis(){
cameraHandler.takeAPic();
}
And the class is:
public class CameraHandler implements Camera.PictureCallback{
private Camera mCamera;
public CameraHandler(){ }
public void takeAPic(){
try{
if (mCamera == null){
mCamera = Camera.open();
mCamera.enableShutterSound(false);
try {
mCamera.setPreviewTexture(new SurfaceTexture(10));
}
catch (IOException e1) { }
}
mCamera.startPreview();
mCamera.takePicture(null, null, this);
}
catch (Exception ex){ }
}
#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) { }
}
The problem I'm running into now is that any code I put in following the 'takePicture' is not causing the 'onPictureTaken' to be called.
However, this will at least get you to a spot where you can take a picture without a preview. Maybe you can figure out how to make multiple calls to snap the pictures

Cannot play music using MusicService in Fragment

I have a fragment that gives me the listView of all songs that that I have stored on my phone. When I click on a particular song in my list, I should be able to play it using a MusicService.
This fragment (menu2_Fragment) is initialized in an ActionBarActivity when a particular drawer item is selected. See following code:
#Override
public void onNavigationDrawerItemSelected(int position) {
Fragment objFragment = null;
switch(position){
case 0:
objFragment = new menu1_Fragment();
getSupportActionBar().setTitle("Scan for Users");
break;
case 1:
objFragment = new menu2_Fragment();
getSupportActionBar().setTitle("Your Music");
// objFragment = new MyMusicFragment();
break;
case 2:
objFragment = new menu3_Fragment();
getSupportActionBar().setTitle("Popular Music");
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, objFragment)
.commit();
}
This is the Fragment code:
package com.example.cs446.soundscope;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.MediaController;
import com.example.cs446.soundscope.Adapter.SongAdapter;
import com.example.cs446.soundscope.data.Song;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
/**
* Created by val on 27/02/15.
*/
public class menu2_Fragment extends Fragment implements MediaController.MediaPlayerControl{
View rootview;
private ArrayList<Song> songList;
private ListView songView;
private MusicService musicSrv;
private Intent playIntent;
private boolean musicBound=false;
private MusicController controller;
private boolean paused=false;
private boolean playbackPaused=false;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
rootview = inflater.inflate(R.layout.activity_main,container, false);
songView = (ListView)rootview.findViewById(R.id.song_list);
songList = new ArrayList<Song>();
getSongList();
//sort all of the songList by title
Collections.sort(songList, new Comparator<Song>() {
//function that does the sorting
#Override
public int compare(Song lhs, Song rhs) {
return lhs.getTitle().compareTo(rhs.getTitle());
}
});
SongAdapter songAdt = new SongAdapter(getActivity(),songList);
songView.setAdapter(songAdt);
setController();
//startActivity(new Intent(this, MainActivity.class));
return rootview;
}
//get the song information for your filesystem
public void getSongList(){
//use the contentResolver to retrieve the uri for the music file
//a cursor instance is created with the contentResolver
ContentResolver musicResolver = this.getActivity().getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
//store the songs into the song list array list
if(musicCursor!=null && musicCursor.moveToFirst()){
//get columns
int titleColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media._ID);
int artistColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.ARTIST);
//add songs to list
do {
long thisId = musicCursor.getLong(idColumn);
String thisTitle = musicCursor.getString(titleColumn);
String thisArtist = musicCursor.getString(artistColumn);
songList.add(new Song(thisId, thisTitle, thisArtist));
}
while (musicCursor.moveToNext());
}
}
public void songPicked(View view){
musicSrv.setSong(Integer.parseInt(view.getTag().toString()));
musicSrv.playSong();
if(playbackPaused){
setController();
playbackPaused=false;
}
controller.show(0);
}
//set the controller up
private void setController(){
controller = new MusicController(getActivity());
controller.setPrevNextListeners(new View.OnClickListener() {
#Override
public void onClick(View v) {
playNext();
}
}, new View.OnClickListener() {
#Override
public void onClick(View v) {
playPrev();
}
});
controller.setMediaPlayer(this);
controller.setAnchorView(getActivity().findViewById(R.id.song_list));
controller.setEnabled(true);
}
#Override
public void onStart() {
super.onStart();
if(playIntent==null){
playIntent = new Intent(getActivity(), MusicService.class);
this.getActivity().bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
this.getActivity().startService(playIntent);
}
}
#Override
public void onPause(){
super.onPause();
paused=true;
}
#Override
public void onResume(){
super.onResume();
if(paused){
setController();
paused=false;
}
}
#Override
public void onStop() {
controller.hide();
super.onStop();
}
//connect to the service
private ServiceConnection musicConnection = new ServiceConnection(){
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicService.MusicBinder binder = (MusicService.MusicBinder)service;
//get service
musicSrv = binder.getService();
//pass list
musicSrv.setList(songList);
musicBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
musicBound = false;
}
};
//play next
private void playNext(){
musicSrv.playNext();
if(playbackPaused){
setController();
playbackPaused=false;
}
controller.show(0);
}
//play previous
private void playPrev(){
musicSrv.playPrev();
if(playbackPaused){
setController();
playbackPaused=false;
}
controller.show(0);
}
#Override
public void onDestroy() {
this.getActivity().stopService(playIntent);
musicSrv=null;
super.onDestroy();
}
#Override
public void start() {
musicSrv.go();
}
#Override
public void pause() {
playbackPaused=true;
musicSrv.pausePlayer();
}
#Override
public int getDuration() {
if(musicSrv!=null && musicBound && musicSrv.isPng())
return musicSrv.getDur();
else return 0;
}
#Override
public int getCurrentPosition() {
if(musicSrv!=null && musicBound && musicSrv.isPng())
return musicSrv.getPosn();
else return 0;
}
#Override
public void seekTo(int pos) {
musicSrv.seek(pos);
}
#Override
public boolean isPlaying() {
if(musicSrv!=null && musicBound)
return musicSrv.isPng();
return false;
}
#Override
public int getBufferPercentage() {
return 0;
}
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getAudioSessionId() {
return 0;
}
}
When I click on an item in the ListView, instead of playing the song my app crashes and I receive the following error message:
03-02 00:46:29.142 6485-6485/com.example.cs446.soundscope E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.cs446.soundscope, PID: 6485
java.lang.IllegalStateException: Could not find a method songPicked(View) in the activity class com.example.cs446.soundscope.ListNearbyUsers for onClick handler on view class android.widget.LinearLayout
at android.view.View$1.onClick(View.java:3994)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
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:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NoSuchMethodException: songPicked [class android.view.View]
at java.lang.Class.getMethod(Class.java:664)
at java.lang.Class.getMethod(Class.java:643)
at android.view.View$1.onClick(View.java:3987)
            at android.view.View.performClick(View.java:4756)
            at android.view.View$PerformClick.run(View.java:19749)
            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:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
The playing music functionality works fine when it's not implemented inside a Fragment, but instead implemented inside an Activity. Has anyone seen an error like this before?
It means that you didn't declare andoid:onClick="songPicked" in your fragment layout.
And I know you are coming from tutsplus :)

"java.lang.NullPointerException" Error when trying to insert data to sqlite (Android)

I face the error :
1566-1566/com.example.rom.romproject E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.rom.romproject, PID: 1566
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3823)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3818)
            at android.view.View.performClick(View.java:4438)
            at android.view.View$PerformClick.run(View.java:18422)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5017)
            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:779)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
            at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.rom.romproject.ContactView.contactFavorite(ContactView.java:37)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at android.view.View$1.onClick(View.java:3818)
            at android.view.View.performClick(View.java:4438)
            at android.view.View$PerformClick.run(View.java:18422)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5017)
            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:779)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
            at dalvik.system.NativeStart.main(Native Method)
This happens when im clicking on a button i created.
The button purpose is to insert Data into my sql table.
The SQL class :
public class sqlDatabaseAdapter
{
sqlHelper helper;
public sqlDatabaseAdapter(Context context)
{
helper = new sqlHelper(context);
}
public long insertData(String name, String phone)
{
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues content = new ContentValues();
content.put(sqlHelper.NAME, name);
content.put(sqlHelper.PHONE, phone);
return db.insert(helper.TABLE_NAME, null, content);
}
static class sqlHelper extends SQLiteOpenHelper
{
static final String DATABASE_NAME = "ContactDB";
static final String TABLE_NAME = "Favorites";
static final int DB_VERSION = 1;
static final String UID = "_id";
static final String NAME = "Name";
static final String PHONE = "Phone";
static final String CREATE_TABLE = "CREATE TABLE "+ TABLE_NAME +" ("+UID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+NAME+" VARCHAR(255), "+PHONE+" VARCHAR(255));";
static final String DROP_TABLE = "DROP TABLE IF EXISTS"+TABLE_NAME;
private Context context;
public sqlHelper(Context context)
{
super(context, DATABASE_NAME, null, DB_VERSION);
this.context = context;
Message.Message(context, "Constructor Called");
}
#Override
public void onCreate(SQLiteDatabase db)
{
try {
db.execSQL(CREATE_TABLE);
Message.Message(context, "onCreate Called");
} catch( SQLException e)
{
Message.Message(context, "" + e);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
try {
db.execSQL(DROP_TABLE);
onCreate(db);
Message.Message(context, "OnUpgrade Called");
} catch(SQLException e)
{
Message.Message(context, "" + e);
}
}
}
}
Now, im not rly sure at the source of the problem , so i will post both of my activites.
Btw : the info im trying to insert to the SQL is a contact name and phone
(that i get from the main activity list view).
Main Activity ( List view of phone contacts ) :
public class MainActivity extends ListActivity {
ListView l;
Cursor cursor;
SimpleCursorAdapter listAdapter;
sqlDatabaseAdapter helper;
#Override
public int getSelectedItemPosition()
{
return super.getSelectedItemPosition();
}
#Override
public long getSelectedItemId()
{
return super.getSelectedItemId();
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
startManagingCursor(cursor);
String[] from = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone._ID};
int[] to = {android.R.id.text1,android.R.id.text2};
listAdapter = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_2,cursor,from,to);
setListAdapter(listAdapter);
l = getListView();
l.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
helper = new sqlDatabaseAdapter(this);
helper.helper.getWritableDatabase();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
TextView _tempName= (TextView)v.findViewById(android.R.id.text1);
String _temp = _tempName.getText().toString();
TextView _tempPhone = (TextView)v.findViewById(android.R.id.text2);
String _temp2 = _tempPhone.getText().toString();
Intent intent = new Intent(this, ContactView.class);
intent.putExtra("contactName", _temp);
intent.putExtra("contactPhone", _temp2);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
The second activity (where the button is ) :
public class ContactView extends ActionBarActivity {
Button _Call;
Button _Favorite;
FavoriteContact contact = new FavoriteContact();
sqlDatabaseAdapter helper;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_view);
_Call = (Button)findViewById(R.id.bCall);
_Favorite = (Button)findViewById(R.id.bFavorite);
contact.setName(getIntent().getExtras().getString("contactName"));
contact.setPhone(getIntent().getExtras().getString("contactPhone"));
setTitle(contact.getName());
}
public void contactFavorite(View view)
{
long id = 0L;
id = helper.insertData(contact.getName(), contact.getPhone());
/*
if( id < 0)
{
Message.Message(this, "Unsuccessful");
}
else
{
Message.Message(this, "Successfully inserted to favorite contacts ");
}
*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_contact_view, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Contact class i created and FavoriteContact class :
(favoritecontact extends Contact)
public class Contact
{
private String Name = null;
private String Phone = null;
public String getPhone() {
return Phone;
}
public void setPhone(String phone) {
Phone = phone;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
}
public class FavoriteContact extends Contact
{
private Boolean isFavorite;
public Boolean getIsFavorite() {
return isFavorite;
}
public void setIsFavorite(Boolean isFavorite) {
this.isFavorite = isFavorite;
}
}
i think i gave everything i need...
sorry for my bad english and its my first time posting here so i dont rly know how it works :D
thanks for every bit of help .
The variable helper is never initialized in ContactView.