The below flashlight code used to work properly earlier. but when I started the android IDE for next time. it shows NullPointerException Error in the specific line consist of Camera Parameters. I have tried every other conditions to trace the stack still I cant find any relevant solutions. Any help is appreciated.
I have also visited some of the related queries in the forum. one of which queries I have found useful but still It didn't work.
Google results
Flashlight.java
public void connectCameraService() {
if (camera == null) {
camera = android.hardware.Camera.open();
params = camera.getParameters(); //specific line shows NullPointerException Error.
}
}
The above method also creates Error in Override methods.
#Override
protected void onStart() {
super.onStart();
connectCameraService();
}
Related
I'm sorry for this basic question I'm new to this android thing...and gotta start struggling somewhere...(Please be gentle)
Have a basic sketch in processing that shows the computer's camera view in a window. Works fine on the computer. It doesn't load on my android. Just hangs and pretends to be building forever. Not sure if it has to do with camera permissions and I'm a nubbie at this so have no idea how to find out.
Any help would be greatly appreciated.
Thank you!
The code:
import processing.video.*;
Capture video;
void setup() {
size(320, 240);
video = new Capture(this, 320, 240);
video.start();
}
void captureEvent(Capture video) {
video.read();
}
void draw() {
image(video, 0, 0);
}
As it compiles this is the only apparent 'problem' but it doesn't come back as an error.
**Exception in thread "Thread-203" java.lang.NullPointerException: Cannot read the array length because "list" is null
**
I am trying to develop an app that would take picture when you light the screen.
I created different method to do so, and different logs. When I call the method supposed to take the picture : this is in a Service
public void photo() {
try {
cam.setPreviewDisplay(new SurfaceView(this).getHolder());
cam.startPreview();
cam.takePicture(null,null,new PhotoHandler());
Log.i("photo","end");
}catch(IOException e) {e.printStackTrace();}
}
In the logs, the "photo","end" is displayed but the logs I put in PhotoHandler are not.
I also have the "Camera" "app passed NULL Surface" log.
So I am asking you guys why is the picture not taken ? The PhotoHandler works fine, I tested it in a basic app.
Hope you'll help me !
EDIT : The camera is selected in the onCreate method of the service and gives no error.
EDIT : The problem was that my PhotoHandler wasn't called so camera.release() too. My photo() method looks like this now
public void photo() {
Camera cam=null;
try {
cam=Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
cam.setPreviewTexture(new SurfaceTexture(0));
cam.startPreview();
cam.takePicture(null,null,new PhotoHandler());
cam.stopPreview();
cam.release();
Log.i("photo","end");
}catch(IOException e) {e.printStackTrace();stopSelf();}
catch(RuntimeException re {e.printStackTrace();stopSelf();}
Now, the problem is that the takePicture method is called when the service end, must be a thread problem I assume. But what is more bothering is that the takePicture method is not always called after the service end. And when the method is called, it's called once, whereas I light the screen more than one time during the life of the service.
I have spent days trying to work out the cause of this crash in the Google Play Services Saved Game code from a tester's device and have no idea what else to try as it works on all three of my devices. The crash that occurs is:
java.lang.NullPointerException: Must provide a previously opened Snapshot
when I try and call
snapshot.readFully();
even though the snapshot has been opened and return code checked, and checked to see if it is null. Here is the code path leading up to the crash, with non-executed sections removed for brevity:
public void LoadSnapshot()
{
AsyncTask<Void, Void, SNAPSHOT_ASYNC_RESULT> task = new AsyncTask<Void, Void, SNAPSHOT_ASYNC_RESULT>()
{
#Override
protected SNAPSHOT_ASYNC_RESULT doInBackground(Void... params)
{
if (isSignedIn())
{
Snapshots.OpenSnapshotResult result = Games.Snapshots.open(getApiClient(), "MySnapshot", true).await();
int status = result.getStatus().getStatusCode();
DebugLog("Snapshot Load Open result code: " + status);
if (status == GamesStatusCodes.STATUS_SNAPSHOT_CONFLICT)
{
Snapshot snapshot = result.getSnapshot();
Snapshot conflictSnapshot = result.getConflictingSnapshot();
//write both conflicted files so we can merge them
if (snapshot != null && conflictSnapshot != null)
{
byte[] ssdata = snapshot.readFully(); //CRASH HERE!
...
}
...
}
}
}
}
task.execute();
}
I get similar crashes from the same device when simply saving sometimes with .open() followed by .writebytes().
It is making the entire game unstable and I need to get this fixed somehow. Any help or ideas would be much appreciated.
All I can think is that because it's running on a background thread in an AsyncTask something bad has happened in between opening the snapshot and trying to read/write it on this device. According to the tester is crashes 'most' of the time.
I solved this eventually by only allowing one Async operation at a time, as I was previously allowing a concurrent save and load of the same snapshot.
I also wrapped the readFully() inside a try/catch for safety.
I'm working on this as well. I'm looking at the documentation now, and it has this to say about the function: readFully()
Read the contents of a snapshot.
If this snapshot was not opened via open(GoogleApiClient, SnapshotMetadata), or if the contents have already been committed via commitAndClose(GoogleApiClient, Snapshot, SnapshotMetadataChange) this method will throw an exception.
Returns
The bytes of the snapshot contents.
Throws
IOException if reading the snapshot failed.
Are you sure that the snapshot has been opened and committed correctly?
I would like some help regarding Java - Android MultiThreading
While learning to develop my app in a multi-threading way in order to take advantage of the ever-growing multi-core devices market share (most devices are quad core now, some even octo-core), I ran in a situation where my threads are either being calling twice or running twice.
I just don't why and how.
[EDIT 3]
Alright, I narrowed down the issue : I called the AsyncTask from the onResume() method. Although my app did not lost focus (which would mean a call to onPause() then back to onResume() upon return of focus in which case my threads would be run twice) during the tests, I solved the issue by moving away the call to FetchFriendsList to another place.
So far so good, but since in my tests the app did not loose focus or perhaps it did but I could not witness it (!), I think there is another reason behind so I'd say my problem is not entirely solved ... at least for the moment. It does work though. Perhaps I did solve the issue but I do not know how :(
[end of EDIT 3]
I am implementing last Facebook SDK and I am using it to fetch the end-user friends list, which seems to do the work.
Since I am running this operation in an AsyncTask, I am not using request.executeAsync().
Instead I am using request.executeAndWait(). Facebook JavaDoc does state that this method must only be used if I am not in a the Main UI Thread which is my case otherwise I would get a NetworkOnMainThreadException.
Anyway, this is where the weird behavior is happening.
private final ArrayList<GraphUser> userFriendsList = new ArrayList<GraphUser>();
public final void fetchFriendsList() {
if (this.session != null && this.session.isOpened()) {
final Request requestUserFriendsList = Request.newMyFriendsRequest(
this.session, new Request.GraphUserListCallback()
public final void onCompleted(final List<GraphUser> users, final Response response) {
if (users != null && users.size() > 0) {
Log.v("Retrieved Friends List -> ", String.valueOf(users.size()));
userFriendsList.addAll(users);
}
}
}
);
if (this.asyncFlag)
requestUserFriendsList.executeAsync();
else
requestUserFriendsList.executeAndWait();
}
}
In my case, asyncFlag is set to false because I need to do stuff synchronously in that specific order :
Fetch User Friends List (not on the Main (UI) Thread)
Save friends list on device (separate new thread)
Save friends list on a server (separate new thread)
Following this pattern, the line userFriendsList.addAll(users); is called twice.
In the logcat, the Log.vis showed twice as well, and finally looking with the debugger, the content of the user friends list is made of duplicates.
But that's not all ... step 2 and 3 are indeed two separate threads which are both created and spawned within the same method : public final void asyncSaveFacebookFriendsList().
And guess what, this method is even called twice !
just why ?
At the beginning I was calling the method for step 2 and 3 like this :
[...]
userFriendsList.addAll(users);
asyncSaveFacebookFriendsList(); // it was private before
[...]
This is where the issue started as both line were running twice.
So I thought, alright, I'll call it later like this :
[...]
fetchFriendsList();
asyncSaveFacebookFriendsList(); // it is now public
[...]
But the issue remains still.
If I don't call public final void asyncSaveFacebookFriendsList(), then nothing is run twice.
Why does this issue happen ? Is there something I did not get in Java Threads ?
I do not think this is somehow related to the Facebook SDK because following the same pattern (and doing it also at the same time), I have the same issues when fetching and storing the end-user Twitter friends list.
So I do believe I am doing something wrong. Does someone have any idea in what possible case a thread is called twice ?
Note : all threads are started this way : thread.start(). I am not using any ThreadPool nor the ExecutorService.
In case you need more background context :
Content of AsyncTask : (no need to wonder why Void and Long, I remove the irrelevant code related to it)
private final class FetchFriendsLists extends AsyncTask<Long, Integer, Void> {
protected final Void doInBackground(final Long... params) {
if (params[0] != Long.valueOf(-1)) {
[...]
twitterAPI.fetchUserFriendsList();
publishProgress(1, -1);
}
if (params[1] == Long.valueOf(0)) {
[...]
facebookAPI.fetchFriendsList();
publishProgress(-1, 0);
}
return null;
}
protected final void onProgressUpdate(Integer... flags) {
super.onProgressUpdate(flags);
if (flags[0] != -1)
twitterAPI.asyncSaveFacebookFriendsList();
if (flags[1] == 0)
facebookAPI.asyncSaveFacebookFriendsList();
}
}
As you can see, I start step 2 and 3 in onPublishProgress() which runs on the Main UI Thread. Brefore it was in the doInBackground() method : the issue happens in both cases!
[EDIT]
After further test, it would seem any kind of code is in fact running twice.
I created a simple method called test in which in print a counter. The counter incremente twice as well !
Why you use onProgressUpdate?¿?
onProgressUpdate(Progress...), [...]. This method is used to display any form of progress in the
user interface while the background computation is still executing.
For instance, it can be used to animate a progress bar or show logs in
a text field.
This is used not at the finish of the petition, but when progress increased.
Read this:
http://developer.android.com/reference/android/os/AsyncTask.html
You need to use:
protected void onPostExecute(Long result) {
I am using pretty much the same code as the Camera app code from Google but am getting really weird results. Inside my application and the Camera app from Google the preview gets stuck or is overlid with weird lines. The preview is usually the last thing which I see in the phone's own Camera app.
The Samsung model is I9003. The same code ran fine on I9000 which Samsung just discontinued. The code also works fine on an HTC Wildfire.
Any resolution for this?
Just noticed that after taking a photo inside my application the camera preview becomes normal. Same thing is happening in the Google camera application.
Couldn't post the answer earlier. Wasn't sure if it was the right thing to do, but now with the app running properly on around 150 devices I guess this works.
So the Android camera app in its onCreate function had the following code:
/*
* To reduce startup time, we start the preview in another thread.
* We make sure the preview is started at the end of onCreate.
*/
Thread startPreviewThread = new Thread(new Runnable() {
public void run() {
try {
mStartPreviewFail = false;
startPreview();
} catch (CameraHardwareException e) {
// In eng build, we throw the exception so that test tool
// can detect it and report it
if ("eng".equals(Build.TYPE)) {
throw new RuntimeException(e);
}
mStartPreviewFail = true;
}
}
});
startPreviewThread.start();
For some reason this did not work on GT-I9003. What I noticed was that after taking a photo the preview would come properly so there was nothing wrong with the hardware as such. I tried to retrace what was happening after a photo was taken and then compare it with the code with which the camera was first initialized. I commented out this code from onCreate. The onResume from the camera app looked like this:
if (mSurfaceHolder != null) {
// If first time initialization is not finished, put it in the
// message queue.
if (!mFirstTimeInitialized) {
mHandler.sendEmptyMessage(FIRST_TIME_INIT);
} else {
initializeSecondTime();
}
}
I changed this to:
if (!mFirstTimeInitialized) {
initializeFirstTime();
} else {
initializeSecondTime();
}
There were some other changes too, will put it up on GitHub as a separate app soon.