I am developing an app with slide fragments. Everything works fine, app starts without problems. Problem happens in View.onClickListener. Here is a code of my single fragment section:
public static class ReceiveSectionFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.receive, container, false);
rootView.findViewById(R.id.bt_server_start)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), Receive.class);
startActivity(intent);
}
});
return rootView;
}
}
Sliding to target layout - R.layout.receive works well. So no problem here. On R.id.bt_server_start button click class below is started:
package com.receive.bluereceive;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.CountDownTimer;
import android.os.Vibrator;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
public class Receive extends Activity {
/**
* Default Serial-Port UUID
*/
private String myUUID = "00001101-0000-1000-8000-00805F9B34FB";
/**
* Default Bluetooth adapter on the device.
*/
private final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
/**
* Magic number used in the Bluetooth enabling request.
*/
public final int REQUEST_ENABLE_BT = 2;
/**
* The Server thread.
*/
private AcceptThread DeviceServer;
private NotificationCenter mNotificationCenter;
public final static String EXTRA_MESSAGE = "com.receive.intent.MESSAGE";
public final int BT_ENABLE_TIME = 35;
public final int BT_TIME_BTTIME = 1000 * BT_ENABLE_TIME;
public CountDownTimer BTCountDown;
public CountDownTimer MoveHistoryCountDown;
#Override
protected void onStart() {
super.onStart();
mNotificationCenter = new NotificationCenter();
/*
* Code responsible for calling method NotificationCenter() to print the incoming text to TextView field
*/
registerReceiver(mNotificationCenter, new IntentFilter(EXTRA_MESSAGE));
/*
* Start server on device
*/
ServerThread();
((Button) findViewById(R.id.bt_server_start)).setEnabled(false);
((Button) findViewById(R.id.bt_server_stop)).setEnabled(true);
}
public void ServerThread() {
DeviceServer = new AcceptThread();
DeviceServer.start();
}
private class AcceptThread extends Thread {
/*
* That TAG will appear in the log in Eclipse
*/
private final String ACC_TAG = AcceptThread.class.getName();
/*
* Bluetooth server socket
*/
private final BluetoothServerSocket mServerSocket;
public AcceptThread() {
/*
* Use a temporary object that is later assigned to mServerSocket, because mServerSocket is final
*/
BluetoothServerSocket tmp = null;
try {
/*
* MY_UUID is the app's UUID string, also used by the client code
*/
tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(ACC_TAG, UUID.fromString(myUUID));
} catch (IOException e) { }
mServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
/*
* Keep listening until exception occurs or a socket is returned
*/
while (true) {
try {
Log.i(ACC_TAG,"Listening for a connection nearby...");
socket = mServerSocket.accept();
Log.i(ACC_TAG, "Connected to " + socket.getRemoteDevice().getName());
} catch (IOException e) {
break;
}
/*
* If connection was accepted then proceed with code below
* If Bluetooth socket does not equal null proceed with string reading as know script knows that device is connected
* And if it is first ServerThread start,
*/
if (socket != null) {
try {
String message;
DataInputStream incoming = new DataInputStream(socket.getInputStream());
message = incoming.readUTF();
Intent actual = new Intent(EXTRA_MESSAGE);
actual.putExtra("Message", String.format("%s",message));
getBaseContext().sendBroadcast(actual);
} catch (IOException e) {
Log.e(ACC_TAG, "Error obtaining InputStream from socket");
e.printStackTrace();
}
try {
mServerSocket.close();
} catch (IOException e) { }
break;
}
}
}
/*
* Will cancel the listening socket, and cause the thread to finish
*/
public void cancel() {
try {
mServerSocket.close();
} catch (IOException e) { }
}
}
private Vibrator getVibrator() {
return (Vibrator) getSystemService(VIBRATOR_SERVICE);
}
/*
* NOTIFICATION CLASS, PRINTS THE RECEIVED MESSAGE
*/
public class NotificationCenter extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(EXTRA_MESSAGE)) {
int counter = 0;
ArrayList<String> historiaAL = new ArrayList<String>();
historiaAL.add(intent.getExtras().getString("Message"));
TextView actual = (TextView)findViewById(R.id.received_string);
actual.setText(historiaAL.get(counter));
TextView history = (TextView)findViewById(R.id.history_string);
String[] historiaA = historiaAL.toArray(new String[historiaAL.size()]);
for(int i = 0; i < historiaAL.size(); i++)
{
history.append(historiaA[i]);
history.append(" \n ");
}
getVibrator().vibrate(500);
MoveHistoryCountDown = new HistoryMove(5000,5);
MoveHistoryCountDown.start();
counter++;
}
}
}
public class HistoryMove extends CountDownTimer {
public HistoryMove (long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
TextView recent = (TextView)findViewById(R.id.received_string);
recent.setText(" ");
}
#Override
public void onTick(long millisUntilFinished) {
}
}
}
Everything is included in Manifest.xml. What I get from LogCat is this:
12-18 00:36:14.136: E/AndroidRuntime(29672): FATAL EXCEPTION: main
12-18 00:36:14.136: E/AndroidRuntime(29672): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.receive.bluereceive/com.receive.bluereceive.Receive}: java.lang.NullPointerException
12-18 00:36:14.136: E/AndroidRuntime(29672): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2308)
12-18 00:36:14.136: E/AndroidRuntime(29672): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358)
12-18 00:36:14.136: E/AndroidRuntime(29672): at android.app.ActivityThread.access$600(ActivityThread.java:153)
12-18 00:36:14.136: E/AndroidRuntime(29672): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1247)
12-18 00:36:14.136: E/AndroidRuntime(29672): at android.os.Handler.dispatchMessage(Handler.java:99)
12-18 00:36:14.136: E/AndroidRuntime(29672): at android.os.Looper.loop(Looper.java:137)
12-18 00:36:14.136: E/AndroidRuntime(29672): at android.app.ActivityThread.main(ActivityThread.java:5227)
12-18 00:36:14.136: E/AndroidRuntime(29672): at java.lang.reflect.Method.invokeNative(Native Method)
12-18 00:36:14.136: E/AndroidRuntime(29672): at java.lang.reflect.Method.invoke(Method.java:511)
12-18 00:36:14.136: E/AndroidRuntime(29672): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
12-18 00:36:14.136: E/AndroidRuntime(29672): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
12-18 00:36:14.136: E/AndroidRuntime(29672): at dalvik.system.NativeStart.main(Native Method)
12-18 00:36:14.136: E/AndroidRuntime(29672): Caused by: java.lang.NullPointerException
12-18 00:36:14.136: E/AndroidRuntime(29672): at com.receive.bluereceive.Receive.onStart(Receive.java:68)
12-18 00:36:14.136: E/AndroidRuntime(29672): at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1164)
12-18 00:36:14.136: E/AndroidRuntime(29672): at android.app.Activity.performStart(Activity.java:5114)
12-18 00:36:14.136: E/AndroidRuntime(29672): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2271)
12-18 00:36:14.136: E/AndroidRuntime(29672): ... 11 more
Probably this is some rookie mistake but still, it has been an hour and I still can not crack that out.
Please no downgrade reputation, I really can not have it working even tho it might seems trivial.
EDIT: Full main code - http://pastebin.com/e4dyW8Th
I don't see setContentView called anywhere in your activity which would mean that findViewById returns null.
Add onCreate method to your activity and call setContentView to set your layout.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity);
}
Related
I have been stuck on this for way too long (4 hours yesterday, 3 hours today!) now. In my main menu screen, I have a mute button. I want it to call a method in my background service, which mutes all of the MediaPlayer audio that would be played in the background of my game.
Full code here
Here is something that might be causing the issue:
I am getting the error whenever the audio plays (which plays fine):
QCMediaPlayer mediaplayer NOT present
E/MediaPlayer﹕ Should have subtitle controller already set
package com.example.USERNAME.buttonsmasher;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
public class TwentySeconds extends Service {
static MediaPlayer ten;
static MediaPlayer three;
final String TAG = "MyCountdown";
static CountDownTimer cdt;
double millisUntilFinishedRounded;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Context context = this;
three = MediaPlayer.create(TwentySeconds.this, R.raw.threetwoone);
ten = MediaPlayer.create(TwentySeconds.this, R.raw.tenmoreseconds);
// ten = MediaPlayer.create(TwentySeconds.this, R.raw.tenmoreseconds);
// three = MediaPlayer.create(TwentySeconds.this, R.raw.threetwoone);
Log.v(TAG, "In start command");
cdt = new CountDownTimer(20000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
Log.v(TAG, millisUntilFinished + "left");
millisUntilFinishedRounded = (millisUntilFinished / 1000) * 1000;
if (millisUntilFinishedRounded == 10000) { //TEN SECONDS
// ten = MediaPlayer.create(TwentySeconds.this, R.raw.tenmoreseconds);
// while(ten == null){
ten = MediaPlayer.create(TwentySeconds.this, R.raw.tenmoreseconds);
// }
ten.start();
}
if (millisUntilFinishedRounded == 3000) {
/* Context context = this;
three = MediaPlayer.create(TwentySeconds.this, R.raw.threetwoone);
*/
// while(three == null){
three = MediaPlayer.create(TwentySeconds.this, R.raw.tenmoreseconds);
//}
three.start();
}
}
#Override
public void onFinish() {
Log.v(TAG, "Finished");
Intent intent = new Intent(TwentySeconds.this, GameOver.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Log.v(TAG, "About to start activity");
startActivity(intent);
}
};
cdt.start();
return START_STICKY;
}
public static void stopTimer() {
cdt.cancel();
}
public static void myMute() {
ten.setVolume(0, 0);
three.setVolume(0, 0);
}
public static void unMute() {
ten.setVolume(1, 1);
three.setVolume(1, 1);
}
#Override
public void onDestroy() {
stopSelf();
super.onDestroy();
}
}
_______________________________________________________________________________________________________________________________
Here is the method in Main_Menu (x starts as zero)
if ((x%2) == 0) { //If it's even
TwentySeconds.unMute();
Toast.makeText(Main_Menu.this, "UNMUTED", Toast.LENGTH_SHORT).show();
x++;
} else { //If its odd
TwentySeconds.myMute();
Toast.makeText(Main_Menu.this, "MUTED", Toast.LENGTH_SHORT).show();
x++;
}
__________________________________________________________________
Here is the stack trace:
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3842)
at android.view.View.performClick(View.java:4457)
at android.view.View$PerformClick.run(View.java:18491)
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:5272)
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:883)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
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:3837)
at android.view.View.performClick(View.java:4457)
at android.view.View$PerformClick.run(View.java:18491)
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:5272)
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:883)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.USERNAME.buttonsmasher.TwentySeconds.myMute(TwentySeconds.java:106)
at com.example.USERNAME.buttonsmasher.Main_Menu.mute(Main_Menu.java:103)
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:3837)
at android.view.View.performClick(View.java:4457)
at android.view.View$PerformClick.run(View.java:18491)
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:5272)
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:883)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
at dalvik.system.NativeStart.main(Native Method)
I would really appreciate any feedback (positive or negative)!
Let me know if you need any thing else. Thanks so much for everything, I hope I can solve this issue... :)
I have this interface on my Android project:
package com.kkoci.shairlook;
/**
* Created by kristian on 07/07/2015.
*/
public interface OnTaskFinishListener{
void onFinish();
}
I'm using this, to call a onPostExecute on my AsyncTask class:
package com.kkoci.shairlook;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import com.appspot.shairlook1.userEndpoint.UserEndpoint;
import com.appspot.shairlook1.userEndpoint.model.User;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.extensions.android.json.AndroidJsonFactory;
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest;
import com.google.api.client.googleapis.services.GoogleClientRequestInitializer;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
/**
* Created by kristian on 04/07/2015.
*/
public class EndpointsAsyncTaskInsert extends AsyncTask<String, Void, User> implements GoogleClientRequestInitializer {
private static UserEndpoint myApiService = null;
private Context context;
private OnTaskFinishListener listener;
EndpointsAsyncTaskInsert(Context context) {
this.context = context;
}
public EndpointsAsyncTaskInsert(OnTaskFinishListener listener){
this.listener = listener;
}
#Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
// put it here no in MyClass
abstractGoogleClientRequest.setDisableGZipContent(true);
}
#Override
protected User doInBackground(String... params) {
User response = null;
if (myApiService == null) { // Only do this once
UserEndpoint.Builder builder = new UserEndpoint.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
// options for running against local devappserver
// - 10.0.2.2 is localhost's IP address in Android emulator
// - turn off compression when running against local devappserver
.setRootUrl("https://shairlook1.appspot.com/_ah/api/")
.setGoogleClientRequestInitializer(this);
// end options for devappserver
myApiService = builder.build();
}
try {
User users = new User();
users.setEmail(params[0]);
users.setPassword(params[1]);
users.setName(params[2]);
response = myApiService.insertUser(users).execute();
} catch (Exception e) {
Log.d("Could not Add User", e.getMessage(), e);
}
return response;
}
protected void onPostExecute(User user){
listener.onFinish();
}
}
But this is giving me java.lang.NoCalssDefFound error, I'm initializing it in my Activity like this:
public class LoginMember extends Activity implements OnTaskFinishListener {
public void onFinish(){
Intent intent = new Intent(LoginMember.this, WelcomeScreen.class);
startActivity(intent);
}
Then execute:
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(txtEmail.getWindowToken(), 0);
imm.hideSoftInputFromWindow(txtPassword.getWindowToken(), 0);
String password = txtPassword.getText().toString();
String email = txtEmail.getText().toString();
if ((txtEmail.length() == 0) || (txtPassword.length() == 0)) {
Toast.makeText(LoginMember.this, "You need to provide values for Email and Password", Toast.LENGTH_SHORT).show();
return;
}
//Go ahead and perform the transaction
String[] params = {email, password};
new EndpointsAsyncTaskInsert(currentActivity.getApplicationContext()).execute(params);
}
});
So, the problem arises when executing EndpointAsyncTaskInsert method listener.OnFinish();
This is the complete logcat:
7752-7752/com.kkoci.shairlook E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.kkoci.shairlook.EndpointsAsyncTaskInsert.onPostExecute(EndpointsAsyncTaskInsert.java:74)
at com.kkoci.shairlook.EndpointsAsyncTaskInsert.onPostExecute(EndpointsAsyncTaskInsert.java:24)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:175)
at android.app.ActivityThread.main(ActivityThread.java:5279)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
I've seen this question here, seems to be the same kind of problem, but I'm not really sure about that solution.
Any ideas, please?
Thanks in advance!
The logs say the error is java.lang.NullPointerException... and it's because you're creating a EndpointsAsyncTaskInsert using the Context constructor, thus listener inside of it null... and you dereference it without checking for null in onPostExecute
This is the error message which shows up when I run the apk on my virtual device.
05-03 13:00:03.652 2354-2354/de.hochrad.hochradapp I/art﹕ Not late-enabling -Xcheck:jni (already on)
05-03 13:00:05.966 2354-2354/de.hochrad.hochradapp D/AndroidRuntime﹕ Shutting down VM
05-03 13:00:05.970 2354-2354/de.hochrad.hochradapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: de.hochrad.hochradapp, PID: 2354
java.lang.RuntimeException: Unable to start activity ComponentInfo{de.hochrad.hochradapp/de.hochrad.hochradapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
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.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.widget.Toast.<init>(Toast.java:101)
at android.widget.Toast.makeText(Toast.java:250)
at de.hochrad.hochradapp.MainActivity.onCreate(MainActivity.java:26)
at android.app.Activity.performCreate(Activity.java:5937)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
05-03 13:00:08.238 2354-2354/de.hochrad.hochradapp I/Process﹕ Sending signal. PID: 2354 SIG: 9
Somehow it cannot find the required Resources.
I hope you can help me!!!
Thx for all answers!!!
package de.hochrad.hochradapp;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
ArrayAdapter<String> klassen_adapter;
Vertretungsplan vertretungsplan;
Spinner klassen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(null, "Laden...", Toast.LENGTH_SHORT).show();
klassen_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
klassen = (Spinner) findViewById(R.id.klassenspinner);
Thread downloadThread = new Thread() {
public void run() {
vertretungsplan = new Vertretungsplan("1");
runOnUiThread(new Runnable() {
#Override
public void run() {
if (vertretungsplan.Ex != null) {
klassen_adapter.add("Fehler!");
} else {
klassen_adapter.add("Wähle deine Klasse!");
for (Klassenvertretung s : vertretungsplan.Klassen) {
klassen_adapter.add(s.Bezeichnung);
}
}
}
});
}
};
downloadThread.start();
klassen.setAdapter(klassen_adapter);
klassen.setSelection(0);
klassen.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(parent.getContext(),
"Deine Auswahl ist:" + parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
#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);
}
}
package de.hochrad.hochradapp;
import java.util.ArrayList;
import java.util.List;
public class Klassenvertretung {
public String Bezeichnung;
public List<Vertretung> Vertretungen = new ArrayList<Vertretung>();
public void Hinzufügen(Vertretung neuesElement) {
Vertretungen.add(neuesElement);
}
}
package de.hochrad.hochradapp;
public class Vertretung {
public String Klasse;
public String Stunde;
public String Art;
public String Fach;
public String Raum;
public String stattFach;
public String stattRaum;
public String Informationen;
}
package de.hochrad.hochradapp;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Vertretungsplan {
public Vertretungsplan(String woche) {
Woche = woche;
Einlesen(woche);
}
public String Woche;
public Exception Ex;
public List<Klassenvertretung> Klassen = new ArrayList<Klassenvertretung>();
private void Hinzufügen(Klassenvertretung neuesElement) {
Klassen.add(neuesElement);
}
private void Einlesen(String woche) {
try {
for (int webseite = 1; webseite < 10000; webseite++) {
Klassenvertretung klassenvertretung = new Klassenvertretung();
String teilseite = "0000";
if (webseite < 10)
teilseite = teilseite + "0";
teilseite = teilseite + webseite;
Connection connection = Jsoup
.connect("www.gymnasium-hochrad.de/Vertretungsplan/Vertretungsplan_Internet/"
+ woche + "/w/w" + teilseite + ".htm");
Document doc = connection.get();
Element h2 = doc.select("h2").get(0);
klassenvertretung.Bezeichnung = h2.text();
Element table = doc.select("table").get(1);
Element[] elemente = table.select("tr").toArray(new Element[0]);
for (int i = 1; i < elemente.length; i++) {
Element[] tds = elemente[i].select("td").toArray(
new Element[0]);
Vertretung vertretung = new Vertretung();
vertretung.Klasse = tds[0].text();
vertretung.Stunde = tds[1].text();
vertretung.Art = tds[2].text();
vertretung.Fach = tds[3].text();
vertretung.Raum = tds[4].text();
vertretung.stattFach = tds[5].text();
vertretung.stattRaum = tds[6].text();
vertretung.Informationen = tds[7].text();
klassenvertretung.Hinzufügen(vertretung);
}
Hinzufügen(klassenvertretung);
}
} catch (IOException io) {
if (Klassen.size() == 0) {
Ex = io;
}
} finally {
}
}
}
okay here is my code. I am form germany and so lots of Names are german (i hope thats not a problem.
Maybe it helps.
I guess the error must be in the main activity in one of the toasts. But dont hesitate to look at the other lines.
A/c to logcat error your are getting null reference error. try to update this line
Toast.makeText(parent.getContext(),
"Deine Auswahl ist:" + parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
with the following code
Toast.makeText(MainActivity.this,
"Deine Auswahl ist:" + parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
You have not initialised your adapter namely "klassen_adapter" in your main activity. It's null and invoking any method on it will be null pointer exception
I have been trying to learn how Google Cloud Messaging works in Android apps, specifically multicast messaging, so I found a tutorial with source code. Unfortunately I can get the program to compile without error but when it runs, I get a fatal exception. Anyone know what is wrong?
Here is the main activity:
package com.ganyo.pushtest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gcm.GCMRegistrar;
import static com.ganyo.pushtest.Util.*;
import static com.ganyo.pushtest.Util.TAG;
public class PushMainActivity extends Activity {
private TextView messageTextView;
private Button sendButton;
private AlertDialogManager alert = new AlertDialogManager();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// this is a hack to force AsyncTask to be initialized on main thread. Without this things
// won't work correctly on older versions of Android (2.2, apilevel=8)
try {
Class.forName("android.os.AsyncTask");
} catch (Exception ignored) {}
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
initUI();
AppServices.loginAndRegisterForPush(this);
}
private void initUI() {
setContentView(R.layout.main);
messageTextView = (TextView)findViewById(R.id.lblMessage);
sendButton = (Button)findViewById(R.id.sendButton);
sendButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AppServices.sendMyselfANotification(v.getContext());
}
});
registerReceiver(notificationReceiver, new IntentFilter(DISPLAY_MESSAGE_ACTION));
}
/**
* Receives push Notifications
* */
private final BroadcastReceiver notificationReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Waking up mobile if it is sleeping
WakeLocker.acquire(getApplicationContext());
/**
* Take some action upon receiving a push notification here!
**/
String message = intent.getExtras().getString(EXTRA_MESSAGE);
if (message == null) { message = "Empty Message"; }
Log.i(TAG, message);
messageTextView.append("\n" + message);
alert.showAlertDialog(context, getString(R.string.gcm_alert_title), message);
Toast.makeText(getApplicationContext(), getString(R.string.gcm_message, message), Toast.LENGTH_LONG).show();
WakeLocker.release();
}
};
// this will be called when the screen rotates instead of onCreate()
// due to manifest setting, see: android:configChanges
#Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
initUI();
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(notificationReceiver);
}
}
Here is the manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ganyo.pushtest"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="16"/>
<permission android:name="com.ganyo.pushtest.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="com.ganyo.pushtest.permission.C2D_MESSAGE" />
<!-- App receives GCM messages. -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<!-- GCM connects to Google Services. -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- GCM requires a Google account. -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<!-- Keeps the processor from sleeping when a message is received. -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<application android:label="#string/app_name" android:icon="#drawable/ic_launcher">
<activity android:name="com.ganyo.pushtest.PushMainActivity"
android:label="#string/app_name"
android:configChanges="keyboardHidden|orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<receiver android:name="com.google.android.gcm.GCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.ganyo.pushtest" />
</intent-filter>
</receiver>
<service android:name="GCMIntentService" />
</application>
</manifest>
Here is Appservices:
package com.ganyo.pushtest;
import android.content.Context;
import android.util.Log;
import com.apigee.sdk.ApigeeClient;
import com.apigee.sdk.data.client.DataClient;
import com.apigee.sdk.data.client.callbacks.ApiResponseCallback;
import com.apigee.sdk.data.client.callbacks.DeviceRegistrationCallback;
import com.apigee.sdk.data.client.entities.Device;
import com.apigee.sdk.data.client.entities.Entity;
import com.apigee.sdk.data.client.response.ApiResponse;
import com.apigee.sdk.data.client.utils.JsonUtils;
import com.google.android.gcm.GCMRegistrar;
import com.apigee.sdk.data.client.push.GCMPayload;
import com.apigee.sdk.data.client.push.GCMDestination;
import java.util.HashMap;
import static com.ganyo.pushtest.Util.*;
import static com.ganyo.pushtest.Settings.*;
public final class AppServices {
private static DataClient client;
private static Device device;
static synchronized DataClient getClient(Context context) {
if (client == null) {
if (ORG.equals("<<your org name here>>")) {
Log.e(TAG, "ORG value has not been set.");
} else {
ApigeeClient apigeeClient = new ApigeeClient(ORG,APP,API_URL,context);
client = apigeeClient.getDataClient();
}
}
return client;
}
static void loginAndRegisterForPush(final Context context) {
if ((USER != null) && (USER.length() > 0)) {
DataClient dataClient = getClient(context);
if (dataClient != null) {
dataClient.authorizeAppUserAsync(USER, PASSWORD, new ApiResponseCallback() {
#Override
public void onResponse(ApiResponse apiResponse) {
Log.i(TAG, "login response: " + apiResponse);
registerPush(context);
}
#Override
public void onException(Exception e) {
displayMessage(context, "Login Exception: " + e);
Log.i(TAG, "login exception: " + e);
}
});
} else {
Log.e(TAG,"Data client is null, did you set ORG value in Settings.java?");
}
} else {
registerPush(context);
}
}
static void registerPush(Context context) {
final String regId = GCMRegistrar.getRegistrationId(context);
if ("".equals(regId)) {
GCMRegistrar.register(context, Settings.GCM_SENDER_ID);
} else {
if (GCMRegistrar.isRegisteredOnServer(context)) {
Log.i(TAG, "Already registered with GCM");
} else {
AppServices.register(context, regId);
}
}
}
/**
* Register this user/device pair on App Services.
*/
static void register(final Context context, final String regId) {
Log.i(TAG, "registering device: " + regId);
DataClient dataClient = getClient(context);
if (dataClient != null) {
dataClient.registerDeviceForPushAsync(dataClient.getUniqueDeviceID(), NOTIFIER, regId, null, new DeviceRegistrationCallback() {
#Override
public void onResponse(Device device) {
Log.i(TAG, "register response: " + device);
AppServices.device = device;
displayMessage(context, "Device registered as: " + regId);
DataClient dataClient = getClient(context);
if (dataClient != null) {
// connect Device to current User - if there is one
if (dataClient.getLoggedInUser() != null) {
dataClient.connectEntitiesAsync("users", dataClient.getLoggedInUser().getUuid().toString(),
"devices", device.getUuid().toString(),
new ApiResponseCallback() {
#Override
public void onResponse(ApiResponse apiResponse) {
Log.i(TAG, "connect response: " + apiResponse);
}
#Override
public void onException(Exception e) {
displayMessage(context, "Connect Exception: " + e);
Log.i(TAG, "connect exception: " + e);
}
});
}
} else {
Log.e(TAG,"data client is null, did you set ORG value in Settings.java?");
}
}
#Override
public void onException(Exception e) {
displayMessage(context, "Register Exception: " + e);
Log.i(TAG, "register exception: " + e);
}
#Override
public void onDeviceRegistration(Device device) { /* this won't ever be called */ }
});
} else {
Log.e(TAG, "Data client is null, did you set ORG value in Settings.java?");
}
}
static void sendMyselfANotification(final Context context) {
if (device == null) {
displayMessage(context, "Device not registered. ORG value set in Settings.java?");
} else {
DataClient dataClient = getClient(context);
if (dataClient != null) {
GCMDestination destination = GCMDestination.destinationSingleDevice(device.getUuid());
GCMPayload payload = new GCMPayload();
payload.setAlertText("Hi there!");
dataClient.pushNotificationAsync(payload, destination, "google", new ApiResponseCallback() {
#Override
public void onResponse(ApiResponse apiResponse) {
Log.i(TAG, "send response: " + apiResponse);
}
#Override
public void onException(Exception e) {
displayMessage(context, "Send Exception: " + e);
Log.i(TAG, "send exception: " + e);
}
});
} else {
Log.e(TAG, "data client is null, did you set ORG value in Settings.java?");
}
}
}
/**
* Unregister this device within the server.
*/
static void unregister(final Context context, final String regId) {
Log.i(TAG, "unregistering device: " + regId);
register(context, "");
}
}
Gmcintentservices:
package com.ganyo.pushtest;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.Builder;
import com.google.android.gcm.GCMBaseIntentService;
import static com.ganyo.pushtest.Settings.GCM_SENDER_ID;
import static com.ganyo.pushtest.Util.displayMessage;
public class GCMIntentService extends GCMBaseIntentService {
public GCMIntentService() {
super(GCM_SENDER_ID);
}
/**
* Method called on device registered
**/
#Override
protected void onRegistered(Context context, String registrationId) {
Log.i(TAG, "Device registered: " + registrationId);
displayMessage(context, getString(R.string.gcm_registered, registrationId));
AppServices.register(context, registrationId);
}
/**
* Method called on device unregistered
* */
#Override
protected void onUnregistered(Context context, String registrationId) {
Log.i(TAG, "Device unregistered");
displayMessage(context, getString(R.string.gcm_unregistered, registrationId));
AppServices.unregister(context, registrationId);
}
/**
* Method called on receiving a new message
* */
#Override
protected void onMessage(Context context, Intent intent) {
String message = intent.getExtras().getString("data");
Log.i(TAG, "Received message: " + message);
displayMessage(context, message);
generateNotification(context, message);
}
/**
* Method called on receiving a deleted message
* */
#Override
protected void onDeletedMessages(Context context, int total) {
Log.i(TAG, "Received deleted messages notification");
String message = getString(R.string.gcm_deleted, total);
displayMessage(context, message);
generateNotification(context, message);
}
/**
* Method called on Error
* */
#Override
public void onError(Context context, String errorId) {
Log.i(TAG, "Received error: " + errorId);
displayMessage(context, getString(R.string.gcm_error, errorId));
}
#Override
protected boolean onRecoverableError(Context context, String errorId) {
Log.i(TAG, "Received recoverable error: " + errorId);
displayMessage(context, getString(R.string.gcm_recoverable_error, errorId));
return super.onRecoverableError(context, errorId);
}
/**
* Issues a Notification to inform the user that server has sent a message.
*/
private static void generateNotification(Context context, String message) {
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, PushMainActivity.class);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(context)
.setContentText(message)
.setContentTitle(context.getString(R.string.app_name))
.setSmallIcon(icon)
.setWhen(when)
.setContentIntent(intent)
.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
// Play default notification sound
notification.defaults |= Notification.DEFAULT_SOUND;
// Vibrate if vibrate is enabled
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, notification);
}
}
Alertdialoguemanager:
package com.ganyo.pushtest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
public class AlertDialogManager {
public void showAlertDialog(Context context, String title, String message) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
}
Util:
package com.ganyo.pushtest;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.google.android.gcm.GCMRegistrar;
public final class Util {
static final String TAG = "com.ganyo.pushtest";
static final String DISPLAY_MESSAGE_ACTION = "com.ganyo.pushtest.DISPLAY_MESSAGE";
static final String EXTRA_MESSAGE = "message";
static void displayMessage(Context context, String message) {
Intent intent = new Intent(DISPLAY_MESSAGE_ACTION);
intent.putExtra(EXTRA_MESSAGE, message);
context.sendBroadcast(intent);
}
}
Wakelocker:
package com.ganyo.pushtest;
import android.content.Context;
import android.os.PowerManager;
public abstract class WakeLocker {
private static PowerManager.WakeLock wakeLock;
public static void acquire(Context context) {
if (wakeLock != null) wakeLock.release();
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.ON_AFTER_RELEASE |
PowerManager.ACQUIRE_CAUSES_WAKEUP |
PowerManager.ON_AFTER_RELEASE |
PowerManager.SCREEN_DIM_WAKE_LOCK, "WakeLock");
wakeLock.acquire();
}
public static void release() {
if (wakeLock != null) wakeLock.release(); wakeLock = null;
}
}
Here is the logcat area of the fatal exception:
05-01 00:26:52.757: D/AndroidRuntime(166): Shutting down VM
05-01 00:26:52.777: D/jdwp(166): adbd disconnected
05-01 00:26:52.817: I/AndroidRuntime(166): NOTE: attach of thread 'Binder Thread #3' failed
05-01 00:26:53.050: I/ActivityThread(258): Publishing provider com.svox.pico.providers.SettingsProvider: com.svox.pico.providers.SettingsProvider
05-01 00:26:53.627: I/ActivityManager(58): Start proc com.ganyo.pushtest for activity com.ganyo.pushtest/.PushMainActivity: pid=267 uid=10036 gids={3003}
05-01 00:26:54.687: W/WindowManager(58): No window to dispatch pointer action 0
05-01 00:26:54.707: W/WindowManager(58): No window to dispatch pointer action 1
05-01 00:26:55.467: D/AndroidRuntime(267): Shutting down VM
05-01 00:26:55.467: W/dalvikvm(267): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
05-01 00:26:55.537: E/AndroidRuntime(267): FATAL EXCEPTION: main
05-01 00:26:55.537: E/AndroidRuntime(267): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.ganyo.pushtest/com.ganyo.pushtest.PushMainActivity}: java.lang.ClassNotFoundException: com.ganyo.pushtest.PushMainActivity in loader dalvik.system.PathClassLoader[/data/app/com.ganyo.pushtest-2.apk]
05-01 00:26:55.537: E/AndroidRuntime(267): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
05-01 00:26:55.537: E/AndroidRuntime(267): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
05-01 00:26:55.537: E/AndroidRuntime(267): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
05-01 00:26:55.537: E/AndroidRuntime(267): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
05-01 00:26:55.537: E/AndroidRuntime(267): at android.os.Handler.dispatchMessage(Handler.java:99)
05-01 00:26:55.537: E/AndroidRuntime(267): at android.os.Looper.loop(Looper.java:123)
05-01 00:26:55.537: E/AndroidRuntime(267): at android.app.ActivityThread.main(ActivityThread.java:4627)
05-01 00:26:55.537: E/AndroidRuntime(267): at java.lang.reflect.Method.invokeNative(Native Method)
05-01 00:26:55.537: E/AndroidRuntime(267): at java.lang.reflect.Method.invoke(Method.java:521)
05-01 00:26:55.537: E/AndroidRuntime(267): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
05-01 00:26:55.537: E/AndroidRuntime(267): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
05-01 00:26:55.537: E/AndroidRuntime(267): at dalvik.system.NativeStart.main(Native Method)
05-01 00:26:55.537: E/AndroidRuntime(267): Caused by: java.lang.ClassNotFoundException: com.ganyo.pushtest.PushMainActivity in loader dalvik.system.PathClassLoader[/data/app/com.ganyo.pushtest-2.apk]
05-01 00:26:55.537: E/AndroidRuntime(267): at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:243)
05-01 00:26:55.537: E/AndroidRuntime(267): at java.lang.ClassLoader.loadClass(ClassLoader.java:573)
05-01 00:26:55.537: E/AndroidRuntime(267): at java.lang.ClassLoader.loadClass(ClassLoader.java:532)
05-01 00:26:55.537: E/AndroidRuntime(267): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
05-01 00:26:55.537: E/AndroidRuntime(267): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2577)
05-01 00:26:55.537: E/AndroidRuntime(267): ... 11 more
05-01 00:26:55.617: W/ActivityManager(58): Force finishing activity com.ganyo.pushtest/.PushMainActivity
05-01 00:26:56.499: W/ActivityManager(58): Activity pause timeout for HistoryRecord{460133f8 com.ganyo.pushtest/.PushMainActivity}
05-01 00:26:56.687: I/ARMAssembler(58): generated scanline__00000077:03515104_00000000_00000000 [ 33 ipp] (47 ins) at [0x3261a0:0x32625c] in 1336038 ns
05-01 00:26:56.777: I/ARMAssembler(58): generated scanline__00000177:03515104_00001001_00000000 [ 91 ipp] (114 ins) at [0x3265b8:0x326780] in 1506105 ns
05-01 00:26:57.337: I/ARMAssembler(58): generated scanline__00000077:03545404_00000004_00000000 [ 47 ipp] (67 ins) at [0x326788:0x326894] in 951792 ns
05-01 00:26:57.967: D/AndroidRuntime(271): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<<
05-01 00:26:58.009: D/AndroidRuntime(271): CheckJNI is ON
05-01 00:27:00.377: D/AndroidRuntime(271): --- registering native functions ---
Thanks for the help!
It turned out to be all the .java files in the java folder. Once I redid them in the src path, the program worked correctly.
Pretty new on this android stuff and gets a NullPointException that I can't seem to figure out. I am trying to implement an onResume() method in my CameraActivity and have moved almost all of the orginal code in onCreate() to onResume() and then call onResume() in onCreate(). The activity worked fine when the code was in onCreate(), but when placed in onResume() the exception arsises. What is causing it?
package com.example.tensioncamapp_project;
import java.io.IOException;
import android.content.Context;
import android.hardware.Camera;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
/** A basic Camera preview class */
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private static final String TAG = "PreviewAactivity";
private SurfaceHolder mHolder;
private Camera mCamera;
public CameraPreview(Context context, Camera camera) {
super(context);
this.mCamera = camera;
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
this.mHolder = getHolder();
this.mHolder.addCallback(this);
}
/**Displays the picture on the camera */
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the preview.
try {
this.mCamera.setPreviewDisplay(holder);
this.mCamera.startPreview();
} catch (IOException e) {
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
this.mCamera.release();
this.mCamera = null;
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
//add things here
}
}
and my CameraActivityClass
package com.example.tensioncamapp_project;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import android.content.Intent;
import android.app.Activity;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
public class CameraActivity extends Activity {
private ImageButton captureButton;
private Camera mCamera;
private CameraPreview mPreview;
private PictureCallback mPicture;
private ImageView imageView;
private static final int STD_DELAY = 400;
private static final int MEDIA_TYPE_IMAGE = 1;
protected static final String TAG = "CameraActivity";
/**Starts up the camera */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
onResume();
}
/**Connects the capture button on the view to a listener
* and redirects the client to a preview of the captures image*/
private void addListenerOnButton() {
this.captureButton = (ImageButton) findViewById(R.id.button_capture_symbol);
this.captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View capturebutton) {
mCamera.takePicture(null, null, mPicture);
delay();
Intent viewPic = new Intent(CameraActivity.this, ViewPicActivity.class);
startActivity(viewPic);
}
});
}
/** A safe way to get an instance of the Camera object. Code collected from elsewhere */
public static Camera getCameraInstance(){
Camera c = null;
try {
// attempt to get a Camera instance
c = Camera.open();
//getting current parameters
Camera.Parameters params = c.getParameters();
//setting new parameters with flash
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
c.setParameters(params);
}
catch (Exception e){
// camera is not available (in use or does not exist)
}
// returns null if camera is unavailable
return c;
}
/**Generates a delay needed for application to save new pictures */
private void delay(){
try {
//Makes the program inactive for a specific amout of time
Thread.sleep(STD_DELAY);
} catch (Exception e) {
e.getStackTrace();
}
}
/**Method for releasing the camera immediately on pause event*/
#Override
protected void onPause() {
super.onPause();
//Shuts down the preview shown on the screen
mCamera.stopPreview();
//Calls an internal help method to restore the camera
releaseCamera();
}
/**Help method to release the camera */
private void releaseCamera(){
//Checks if there is a camera object active
if (this.mCamera != null){
//Releases the camera
this.mCamera.release();
//Restore the camera object to its initial state
this.mCamera = null;
}
}
/**Activates the camera and makes it appear on the screen */
protected void onResume() {
// TODO Auto-generated method stub
// deleting image from external storage
FileHandler.deleteFromExternalStorage();
// Create an instance of Camera.
this.mCamera = getCameraInstance();
// Create our Preview view and set it as the content of our activity.
this.mPreview = new CameraPreview(this, this.mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(this.mPreview);
//add the capture button
addListenerOnButton();
// In order to receive data in JPEG format
this.mPicture = new PictureCallback() {
/**Creates a file when a image is taken, if the file doesn't already exists*/
#Override
public void onPictureTaken(byte[] data, Camera mCamera) {
File pictureFile = FileHandler.getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null){
Log.d(TAG, "Error creating media file, check storage permissions");
return;
}
try {
//Writes the image to the disc
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());
}
}
};
super.onResume();
}
}
Log cat:
05-21 14:32:05.424: D/OpenGLRenderer(1030): Enabling debug mode 0
05-21 14:32:10.986: E/CameraActivity(1030): camera not availableFail to connect to camera service
05-21 14:32:11.033: I/Choreographer(1030): Skipped 66 frames! The application may be doing too much work on its main thread.
05-21 14:32:11.203: W/EGL_emulation(1030): eglSurfaceAttrib not implemented
05-21 14:32:13.013: D/AndroidRuntime(1030): Shutting down VM
05-21 14:32:13.013: W/dalvikvm(1030): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
05-21 14:32:13.083: E/AndroidRuntime(1030): FATAL EXCEPTION: main
05-21 14:32:13.083: E/AndroidRuntime(1030): java.lang.NullPointerException
05-21 14:32:13.083: E/AndroidRuntime(1030): at com.example.tensioncamapp_project.CameraPreview.surfaceCreated(CameraPreview.java:33)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.SurfaceView.updateWindow(SurfaceView.java:569)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.SurfaceView.access$000(SurfaceView.java:86)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.SurfaceView$3.onPreDraw(SurfaceView.java:174)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:680)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1842)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.Choreographer.doCallbacks(Choreographer.java:562)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.Choreographer.doFrame(Choreographer.java:532)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.os.Handler.handleCallback(Handler.java:725)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.os.Handler.dispatchMessage(Handler.java:92)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.os.Looper.loop(Looper.java:137)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.app.ActivityThread.main(ActivityThread.java:5041)
05-21 14:32:13.083: E/AndroidRuntime(1030): at java.lang.reflect.Method.invokeNative(Native Method)
05-21 14:32:13.083: E/AndroidRuntime(1030): at java.lang.reflect.Method.invoke(Method.java:511)
05-21 14:32:13.083: E/AndroidRuntime(1030): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-21 14:32:13.083: E/AndroidRuntime(1030): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-21 14:32:13.083: E/AndroidRuntime(1030): at dalvik.system.NativeStart.main(Native Method)
The solution was to call the getCameraInstancemethod() in onResume() in an if-statement
protected void onResume() {
// TODO Auto-generated method stub
// deleting image from external storage
FileHandler.deleteFromExternalStorage();
// Create an instance of Camera.
if (this.mCamera == null){
this.mCamera = getCameraInstance();}
I think your problem is here
this.mPreview = new CameraPreview(this, this.mCamera);
this.mCamera seems to be null, it's not be set a new instance of the class, this needs to be done in the getCameraInstance() method.
getCameraInstance() returns null if an exception was thrown.
This cause the NPE as this.mCamera is null.
You should check if an exception was thrown in getCameraInstance and handle it correctly. The most basic thing is to log it and try to understand the reason.