Android app force closing with arduino - java

I'm developing an app with eclipse and arduino which connects to a bluetooth module. I can then control the LEDS on the board. However my code shows no errors but the app force closes everytime I hit a button. Here is my code:
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Button;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class BluetoothTest extends Activity
{
TextView labelConnect;
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
OutputStream mmOutputStream;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button openButton = (Button)findViewById(R.id.open);
Button closeButton = (Button)findViewById(R.id.close);
Button onButton = (Button)findViewById(R.id.onButton);
Button offButton = (Button)findViewById(R.id.offButton);
Button redButton = (Button)findViewById(R.id.redButton);
Button greenButton = (Button)findViewById(R.id.greenButton);
Button blueButton = (Button)findViewById(R.id.blueButton);
labelConnect = (TextView)findViewById(R.id.mylabel);
//Open Bluetooth
openButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
findBT();
openBT();
}
catch (IOException ex) { }
}
});
//Close Bluetooth
closeButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
closeBT();
}
catch (IOException ex) { }
}
});
//Red Button
redButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
redButton();
}
catch (IOException ex) { }
}
});
//Green Button
greenButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
greenButton();
}
catch (IOException ex) { }
}
});
//Blue Button
blueButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
blueButton();
}
catch (IOException ex) { }
}
});
//On Button - set strip to white
onButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
onButton();
} catch (Exception e) {
// TODO: handle exception
}
}
});
//Off Button - set strip to all OFF
offButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
offButton();
} catch (Exception e) {
// TODO: handle exception
}
}
});
} // end onCreate
void findBT()
{
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter == null)
{
labelConnect.setText("No bluetooth adapter available");
}
if(!mBluetoothAdapter.isEnabled())
{
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if(pairedDevices.size() > 0)
{
for(BluetoothDevice device : pairedDevices)
{
if(device.getName().equals("BTNode0")) // Change to match RN42 - node name
{
mmDevice = device;
Log.i("ArduinoBT", "findBT found device named " + mmDevice.getName());
Log.i("ArduinoBT", "device address is " + mmDevice.getAddress());
break;
}
}
}
labelConnect.setText("Bluetooth Device Found");
}
void openBT() throws IOException
{
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Standard SerialPortService ID
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
mmOutputStream = mmSocket.getOutputStream();
labelConnect.setText("BT << " + mmDevice.getName() + " >> is now open ");
}
void closeBT() throws IOException
{
mmOutputStream.close();
mmSocket.close();
labelConnect.setText("Bluetooth Closed");
}
void offButton() throws IOException
{
mmOutputStream.write("0".getBytes());
}
void redButton() throws IOException
{
mmOutputStream.write("1".getBytes());
}
void greenButton() throws IOException
{
mmOutputStream.write("2".getBytes());
}
void blueButton() throws IOException
{
mmOutputStream.write("3".getBytes());
}
void onButton() throws IOException
{
mmOutputStream.write("4".getBytes());
}
}
And here is my log for what happens when I hit the connect button
04-25 12:15:10.771: W/asset(22604): Copying FileAsset 0x74c0a9d8 (zip:/data/app/Android.Arduino.Bluetooth-2.apk:/resources.arsc) to buffer size 1912 to make it aligned.
04-25 12:15:10.821: D/RenderPolicy(22604): ViewRootImpl.enableHardwareAcceleration -> enableRenderPolicy
04-25 12:15:10.881: I/Adreno-EGL(22604): <qeglDrvAPI_eglInitialize:316>: EGL 1.4 QUALCOMM build: (CL4169980)
04-25 12:15:10.881: I/Adreno-EGL(22604): OpenGL ES Shader Compiler Version: 17.01.10.SPL
04-25 12:15:10.881: I/Adreno-EGL(22604): Build Date: 02/04/14 Tue
04-25 12:15:10.881: I/Adreno-EGL(22604): Local Branch:
04-25 12:15:10.881: I/Adreno-EGL(22604): Remote Branch:
04-25 12:15:10.881: I/Adreno-EGL(22604): Local Patches:
04-25 12:15:10.881: I/Adreno-EGL(22604): Reconstruct Branch:
04-25 12:15:12.363: W/dalvikvm(22604): threadid=1: thread exiting with uncaught exception (group=0x41625e18)
04-25 12:15:12.373: E/AndroidRuntime(22604): FATAL EXCEPTION: main
04-25 12:15:12.373: E/AndroidRuntime(22604): Process: Android.Arduino.Bluetooth, PID: 22604
04-25 12:15:12.373: E/AndroidRuntime(22604): java.lang.NullPointerException
04-25 12:15:12.373: E/AndroidRuntime(22604): at Android.Arduino.Bluetooth.BluetoothTest.openBT(BluetoothTest.java:185)
04-25 12:15:12.373: E/AndroidRuntime(22604): at Android.Arduino.Bluetooth.BluetoothTest$1.onClick(BluetoothTest.java:53)
04-25 12:15:12.373: E/AndroidRuntime(22604): at android.view.View.performClick(View.java:4480)
04-25 12:15:12.373: E/AndroidRuntime(22604): at android.view.View$PerformClick.run(View.java:18673)
04-25 12:15:12.373: E/AndroidRuntime(22604): at android.os.Handler.handleCallback(Handler.java:733)
04-25 12:15:12.373: E/AndroidRuntime(22604): at android.os.Handler.dispatchMessage(Handler.java:95)
04-25 12:15:12.373: E/AndroidRuntime(22604): at android.os.Looper.loop(Looper.java:157)
04-25 12:15:12.373: E/AndroidRuntime(22604): at android.app.ActivityThread.main(ActivityThread.java:5872)
04-25 12:15:12.373: E/AndroidRuntime(22604): at java.lang.reflect.Method.invokeNative(Native Method)
04-25 12:15:12.373: E/AndroidRuntime(22604): at java.lang.reflect.Method.invoke(Method.java:515)
04-25 12:15:12.373: E/AndroidRuntime(22604): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1069)
04-25 12:15:12.373: E/AndroidRuntime(22604): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:885)
04-25 12:15:12.373: E/AndroidRuntime(22604): at dalvik.system.NativeStart.main(Native Method)

As they have already said in the comments, the mmDevice you are trying to use in the openBT method is null, because no device was found in the findBT method and the variable was not initialized. You need to fix your code so that you don't try to open the connection if the device was not found.
The other main issue in your code, once you solve this, is the SocketConnection you are trying to open in the Main Thread. Button handlers and GUI events are executed in the main thread, so your openBT should be moved to a separate thread (or better, a Service).

Related

GCM Android App Fatal 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.

Android custom Camera application crashes as it starts "unfortuantely stopped"

I am trying to build my own custom camera application I have learn through the Android developers Group about how to code the whole application but as soon as I launch the camera it crashes I don't know what is the problem here is my code:
package com.example.tapeit;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore.Files.FileColumns;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
public class CameraActivity extends Activity implements Camera.PictureCallback {
private Camera mCamera;
private CameraPreview mPreview;
String TAG = "TapeIt";
public static final int MEDIA_TYPE_IMAGE = 1;
Button captureButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.preview_layout);
mCamera = getCameraInstance();
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(preview);
captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
mCamera.takePicture(null, null, mPicture);
}
});
}
private boolean checkCameraHardware(Context context){
if(context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
return true;
}else{
return false;
}
}
public static Camera getCameraInstance() {
// TODO Auto-generated method stub
Camera c = null;
try {
c = Camera.open();
} catch (Exception e) {
}
return c;
}
private PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
// TODO Auto-generated method stub
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
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());
}
}
};
private static File getOutputMediaFile(int mediaTypeImage) {
// TODO Auto-generated method stub
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "CameraApp");
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 = new File(mediaStorageDir.getPath() + File.separator +"IMG_"+ timeStamp + ".jpg");
return mediaFile;
}
#Override
public void onPictureTaken(byte[] data, Camera camera) {
// TODO Auto-generated method stub
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
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());
}
}
private void releaseCamera(){
if (mCamera != null){
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
}
And here is my preview Class:
package com.example.tapeit;
import java.io.IOException;
import android.content.Context;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.hardware.Camera;
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback{
private Camera mCamera;
private SurfaceHolder mHolder;
String TAG = "TapeIt";
public CameraPreview (Context context, Camera camera){
super(context);
mCamera = camera;
mHolder = getHolder();
mHolder.addCallback(this);
}
public void surfaceCreated(SurfaceHolder holder){
try{
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
}catch(IOException e){
Log.d(TAG, "Error setting camera preview" + e.getMessage());
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// TODO Auto-generated method stub
if(mHolder.getSurface() == null){
return;
}
try{
mCamera.stopPreview();
}catch(Exception e){
}
//You should make here changes when the device is rotated or when any other change
// set preview size and make any resize, rotate or
// reformatting changes here
//mCamera.getParameters().getSupportedPreviewSizes();
try{
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
}catch(IOException e){
Log.d(TAG, "Error setting camera preview" + e.getMessage());
}
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
// TODO Auto-generated method stub
}
}
My manifest uses all the permision here they are:
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-feature android:name="android.hardware.camera" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.tapeit.CameraActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
My logcat in the console is posted here:
04-04 11:19:32.010: D/AndroidRuntime(21270): Shutting down VM
04-04 11:19:32.010: W/dalvikvm(21270): threadid=1: thread exiting with uncaught exception (group=0x40eb72a0)
04-04 11:19:32.010: E/AndroidRuntime(21270): FATAL EXCEPTION: main
04-04 11:19:32.010: E/AndroidRuntime(21270): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tapeit/com.example.tapeit.CameraActivity}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2092)
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2117)
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.app.ActivityThread.access$700(ActivityThread.java:134)
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1218)
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.os.Handler.dispatchMessage(Handler.java:99)
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.os.Looper.loop(Looper.java:137)
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.app.ActivityThread.main(ActivityThread.java:4867)
04-04 11:19:32.010: E/AndroidRuntime(21270): at java.lang.reflect.Method.invokeNative(Native Method)
04-04 11:19:32.010: E/AndroidRuntime(21270): at java.lang.reflect.Method.invoke(Method.java:511)
04-04 11:19:32.010: E/AndroidRuntime(21270): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
04-04 11:19:32.010: E/AndroidRuntime(21270): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
04-04 11:19:32.010: E/AndroidRuntime(21270): at dalvik.system.NativeStart.main(Native Method)
04-04 11:19:32.010: E/AndroidRuntime(21270): Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.view.ViewGroup.addViewInner(ViewGroup.java:3439)
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.view.ViewGroup.addView(ViewGroup.java:3310)
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.view.ViewGroup.addView(ViewGroup.java:3255)
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.view.ViewGroup.addView(ViewGroup.java:3231)
04-04 11:19:32.010: E/AndroidRuntime(21270): at com.example.tapeit.CameraActivity.onCreate(CameraActivity.java:39)
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.app.Activity.performCreate(Activity.java:5047)
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2056)
04-04 11:19:32.010: E/AndroidRuntime(21270): ... 11 more
preview.addView(preview);
You are attempting to add the FrameLayout to itself. This will not work.
Presumably, the parameter should be mPreview.
You may wish to use more distinctive names for variables, such as not having both preview and mPreview.

null pointer reference android java

Hey guys i have funny little bug that i have been trying to figure now keep in mind i am student. Would like to know why it is happening ill display the class and where the error is occuring. Thankyou in advanced.
package com.example.assignment;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class ViewRate extends Activity implements OnClickListener {
private int rowID;
private TextView codetv;
private TextView signtv;
private TextView ratetv;
private final String dbName="CurrencyDB";
private final String tableName="Rates";
SQLiteDatabase sampleDB=null;
//
EditText torate, fromrate;
Button convertto,convertfrom;
TextView conRate;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.viewrate);
setViews();
Bundle extra=getIntent().getExtras();
rowID=extra.getInt(MainActivity.ROW_ID);
fillViews();
convertto = (Button)findViewById(R.id.convertto);
convertfrom =(Button)findViewById(R.id.convertfrom);
convertfrom.setOnClickListener(from);
convertto.setOnClickListener(to);}
private OnClickListener to = new OnClickListener() { <-------ERROR
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//converttocur();
conRate.setText("pressed"); <------testing still wont work
}
};
private OnClickListener from = new OnClickListener() { <--------ERROR
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//convertfromcur();
conRate.setText("pressed"); <--------testing
}
};
private void convertfromcur() {
// TODO Auto-generated method stub
try {
double val = Double.parseDouble(ratetv.getText().toString());
double val2 = Double.parseDouble(fromrate.getText().toString());
double com = (val / val2);
conRate.setText("RATE:" + com);
} catch (Exception e) {
// TODO: handle exception
conRate.setText("Error");
}
}
private void converttocur() {
// TODO Auto-generated method stub
try {
double val = Double.parseDouble(ratetv.getText().toString());
double val2 = Double.parseDouble(torate.getText().toString());
double com = (val * val2);
conRate.setText("RATE:" + com);
} catch (Exception e) {
// TODO: handle exception
conRate.setText("Error");
}
}
private void fillViews() {
// TODO Auto-generated method stub
try{
sampleDB=this.openOrCreateDatabase(dbName, MODE_PRIVATE, null);
Cursor c = sampleDB.rawQuery("Select * from " +tableName+" where id ?", new String[] {String.valueOf(rowID)});
if(c!=null && c.moveToFirst()==true){
String code=c.getString(c.getColumnIndex("Code"));
String sign=c.getString(c.getColumnIndex("Sign"));
String rate=c.getString(c.getColumnIndex("Rate"));
codetv.setText(code);
signtv.setText(sign);
ratetv.setText(rate);
}
}
catch(SQLException e){
Log.e(getClass().getSimpleName(),"Could not open database");
}
finally{
if(sampleDB!=null){
sampleDB.close();
}
}
}
private void setViews() {
// TODO Auto-generated method stub
codetv=(TextView)findViewById(R.id.code);
signtv=(TextView)findViewById(R.id.sign);
ratetv=(TextView)findViewById(R.id.rate);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu);
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.viewtask,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch(item.getItemId()){
case R.id.edit:
getEdit();
return true;
case R.id.delete:
getDelete();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void getDelete() {
//TODO Auto-generated method stub
try{
sampleDB=this.openOrCreateDatabase(dbName, MODE_PRIVATE,null);
sampleDB.delete(tableName, "id= "+rowID,null);
}
catch(SQLException e){
Log.e(getClass().getSimpleName(),"Could not open dB");
}
finally {
if(sampleDB!=null){
sampleDB.close();
}
}
}
private void getEdit(){
//TODO Auto-generated method stub
Intent addEdit=new Intent(this,AddEdit.class);
addEdit.putExtra("ID",rowID);
addEdit.putExtra("code",codetv.getText().toString());
addEdit.putExtra("sign",signtv.getText().toString());
addEdit.putExtra("rate",ratetv.getText().toString());
startActivity(addEdit);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
And so the error is on the button clicks and i getting this error message
E/AndroidRuntime(2524): FATAL EXCEPTION: main
E/AndroidRuntime(2524): java.lang.NullPointerException
E/AndroidRuntime(2524):at .example.assignment.ViewRate.converttocur(ViewRate.java:96)
E/AndroidRuntime(2524):at com.example.assignment.ViewRate.access$0(ViewRate.java:86)
E/AndroidRuntime(2524):at com.example.assignment.ViewRate$1.onClick(ViewRate.java:55)
E/AndroidRuntime(2524): at android.view.View.performClick(View.java:4202)
E/AndroidRuntime(2524): at android.view.View$PerformClick.run(View.java:17340)
E/AndroidRuntime(2524): at android.os.Handler.handleCallback(Handler.java:725)
E/AndroidRuntime(2524): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime(2524): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(2524):at android.app.ActivityThread.main(ActivityThread.java:5039)
E/AndroidRuntime(2524):at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(2524): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(2524):at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
E/AndroidRuntime(2524): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
E/AndroidRuntime(2524): at dalvik.system.NativeStart.main(Native Method)
so here is the other logcat
E/AndroidRuntime(2743): FATAL EXCEPTION: main
E/AndroidRuntime(2743): java.lang.NullPointerException
E/AndroidRuntime(2743): at com.example.assignment.ViewRate$1.onClick(ViewRate.java:56)
E/AndroidRuntime(2743): at android.view.View.performClick(View.java:4202)
E/AndroidRuntime(2743): at android.view.View$PerformClick.run(View.java:17340)
E/AndroidRuntime(2743): at android.os.Handler.handleCallback(Handler.java:725)
E/AndroidRuntime(2743): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime(2743): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(2743): at android.app.ActivityThread.main(ActivityThread.java:5039)
E/AndroidRuntime(2743): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(2743): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(2743): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
E/AndroidRuntime(2743): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
E/AndroidRuntime(2743): at dalvik.system.NativeStart.main(Native Method)
I have seen your code, you missed this line under onCreate method to initialize the Textview conRate so by default it initialize by null and you are referring conRate.setText("") where conRate is null thats why you are getting NullPointerException on OnClick.
conRate =(TextView)findViewById(R.id.conRate);
Hope this will help you...:)
One of these values is null:
ratetv
torate
ratetv.getText()
torate.getText()
You cannot dereference null (essentially, you cannot call methods on a null value), so you get a NullPointerException.
I think you have missed the following in your onCreate()
torate = (EditText) findViewById(R.id.to_rate)
ratetv = (TextView) findViewById(R.id.rate_tv)
Plz first check your all UI components are referenced well in your java file means in activity.
this may be the place where you get NPE.
also you are accessing intent value from other activity in onCreate() method so olz confirm that you will get value in intent or you get null value
Blockquote
just change your code::
Blockquote
you have implemented onClickListener in your activity so definetly you will get it's override method onClick so just in that method write your button click event conditionally like
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId == R.id.convertto)
{
//Here write you code when converTo button Clicked
}
else if(v.getId == R.id.converfrom)
{
//Here write your code when converfrom button clicked
}
}

NullPointerException in setPreviewDisplay(holder)

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.

Exception occurs in Async task

I am getting this exception. When, i'm trying to run my program. In my program i am executing an AsyncTask For each download and upload tasks, I have created new AsyncTask object and tried to run it in background. I tried to find my mistake. But i can't find where i am going wrong. Below are my stack trace and code of my program -
05-07 10:00:44.899: E/AndroidRuntime(367): FATAL EXCEPTION: AsyncTask #1
05-07 10:00:44.899: E/AndroidRuntime(367): java.lang.RuntimeException: An error occured while executing doInBackground()
05-07 10:00:44.899: E/AndroidRuntime(367): at android.os.AsyncTask$3.done(AsyncTask.java:200)
05-07 10:00:44.899: E/AndroidRuntime(367): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
05-07 10:00:44.899: E/AndroidRuntime(367): at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
05-07 10:00:44.899: E/AndroidRuntime(367): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
05-07 10:00:44.899: E/AndroidRuntime(367): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
05-07 10:00:44.899: E/AndroidRuntime(367): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
05-07 10:00:44.899: E/AndroidRuntime(367): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
05-07 10:00:44.899: E/AndroidRuntime(367): at java.lang.Thread.run(Thread.java:1019)
05-07 10:00:44.899: E/AndroidRuntime(367): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
05-07 10:00:44.899: E/AndroidRuntime(367): at android.os.Handler.<init>(Handler.java:121)
05-07 10:00:44.899: E/AndroidRuntime(367): at android.widget.Toast.<init>(Toast.java:68)
05-07 10:00:44.899: E/AndroidRuntime(367): at android.widget.Toast.makeText(Toast.java:231)
05-07 10:00:44.899: E/AndroidRuntime(367): at com.android.test.Helper.downloadTask(t.java:269)
05-07 10:00:44.899: E/AndroidRuntime(367): at com.android.test.Helper.doInBackground(t.java:132)
05-07 10:00:44.899: E/AndroidRuntime(367): at com.android.test.Helper.doInBackground(t.java:1)
05-07 10:00:44.899: E/AndroidRuntime(367): at android.os.AsyncTask$2.call(AsyncTask.java:185)
05-07 10:00:44.899: E/AndroidRuntime(367): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
05-07 10:00:44.899: E/AndroidRuntime(367): ... 4 more
This is my AsynTask Helper
class Helper extends AsyncTask<Integer, Void, Void>
{
private SmbFile dfile;
private String dfilepath;
private SmbFile dfolder;
private String dfolderpath;
private File ufolder;
private SmbFile ufoldersmb;
private NtlmPasswordAuthentication auth;
private int upstate=0;
private int downstate=0;
private Context context;
private ArrayList<SmbFile> smbArray=new ArrayList<SmbFile>();
private String ext;
private int tasknumber;
private String taskname;
public Context getcontext()
{
return context;
}
public int gettasknumber()
{
return tasknumber;
}
public String gettaskname()
{
return taskname;
}
public int getupstate()
{
return upstate;
}
public int getdownstate()
{
return downstate;
}
public void setdfile(SmbFile a)
{
this.dfile = a;
}
public void setdfilepath(String b)
{
this.dfilepath = b;
}
public void setdfolder(SmbFile c)
{
this.dfolder = c;
}
public void setdfolderpath(String d)
{
this.dfolderpath = d;
}
public void setufolder(File g)
{
this.ufolder = g;
}
public void setufoldersmb(SmbFile h)
{
this.ufoldersmb = h;
}
public void setauthentication(NtlmPasswordAuthentication i)
{
this.auth = i;
}
public void setupstate(int j)
{
upstate = j;
}
public void setdownstate(int k)
{
downstate = k;
}
public void setcontext(Context l)
{
context = l;
}
public void setarraysmb(SmbFile m)
{
this.smbArray.add(m);
}
public void setextstorage(String n)
{
this.ext=n;
}
public void settasknumber(int o)
{
this.tasknumber=o;
}
public void settaskname(String p)
{
this.taskname=p;
}
#Override
protected Void doInBackground(Integer... params)
{
//check flag to execute exactly method
switch (params[0])
{
case 0:
downloadTask();
break;
case 1:
Toast.makeText(context, "AccessPC Upload task "+tasknumber+" Started", Toast.LENGTH_LONG).show();
uploadFolder(ufolder,ufoldersmb);
break;
default:break;
}
return null;
}
void downloadFile(SmbFile dfile,String dpath)
{
StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
long blockSize = statFs.getBlockSize();
long freeSize = statFs.getFreeBlocks()*blockSize;
try
{
if(!((freeSize-dfile.length())<0))
{
SmbFileInputStream din=new SmbFileInputStream(dfile);
FileOutputStream dout=new FileOutputStream(dpath);
int c;
while((c=din.read())!=-1)
{
dout.write(c);
}
if (din != null)
{
din.close();
}
if (dout != null)
{
dout.close();
}
}
else
{
Toast.makeText(context, "AccessPC Download Task failed ",Toast.LENGTH_LONG).show();
}
}
catch(Exception e)
{
Toast.makeText(context, "AccessPC Download Task failed "+e,Toast.LENGTH_LONG).show();
}
}
void downloadFolder(SmbFile dfolder,String dfolderpath)
{
try
{
dfolderpath=dfolderpath+dfolder.getName();
if(!(new File(dfolderpath)).exists())
{
(new File(dfolderpath)).mkdir();
}
SmbFile[] temp=dfolder.listFiles();
if(temp.length==0)
{
Toast.makeText(context, "df,downstate="+downstate,Toast.LENGTH_LONG).show();
return;
}
for(SmbFile m:temp)
{
if(m.isFile())
{
downloadFile(m,dfolderpath+m.getName());
}
else
{
downloadFolder(m,dfolderpath);
}
}
}
catch (Exception e)
{
Toast.makeText(context, "AccessPC Download Task failed "+e,Toast.LENGTH_LONG).show();
}
}
void uploadFile(File ufile,SmbFile ufilesmb)
{
try
{
FileInputStream uin=new FileInputStream(ufile);
SmbFile tempSmb=new SmbFile(ufilesmb.getPath()+ufile.getName(),auth);
SmbFileOutputStream uout=new SmbFileOutputStream(tempSmb);
int c;
while((c=uin.read())!=-1)
{
uout.write(c);
}
if (uin != null)
{
uin.close();
}
if (uout != null)
{
uout.close();
}
}
catch(Exception e)
{
Toast.makeText(context, "AccessPC Upload Task failed "+e, Toast.LENGTH_LONG).show();
}
}
void uploadFolder(File ufolder,SmbFile ufoldersmb)
{
try
{
SmbFile tempSmb=new SmbFile(ufoldersmb.getPath()+ufolder.getName()+"/",auth);
if(!tempSmb.exists())
{
tempSmb.mkdir();
}
File[] ftemp=ufolder.listFiles();
if(ftemp.length==0)
{
setupstate(2);
return;
}
for(File m:ftemp)
{
if(m.isFile())
{
uploadFile(m,tempSmb);
}
else
{
uploadFolder(m,tempSmb);
}
}
}
catch (Exception e)
{
Toast.makeText(context, "AccessPC Upload Task failed "+e,Toast.LENGTH_LONG).show();
}
}
void downloadTask()
{
Toast.makeText(context, "AccessPC download task "+tasknumber+" Started", Toast.LENGTH_LONG).show();
try
{
for(SmbFile m:smbArray)
{
if(m.isFile())
{
setdfile(m);
setdfilepath(ext+m.getName());
downloadFile(dfile,dfilepath);
}
else
{
setdfolder(m);
setdfolderpath(ext);
downloadFolder(dfolder,dfolderpath);
}
}
setdownstate(2);
}
catch (Exception e)
{
Toast.makeText(context,"Download error "+e,Toast.LENGTH_LONG).show();
}
}
#Override
protected void onPostExecute(Void result)
{
if(upstate==2)
{
setupstate(0);
Toast.makeText(context, "AccessPC "+taskname+" task "+tasknumber+" Finished", Toast.LENGTH_LONG).show();
}
if(downstate==2)
{
setdownstate(0);
Toast.makeText(context, "AccessPC "+taskname+" task "+tasknumber+" Finished", Toast.LENGTH_LONG).show();
}
}
}
This is my options menu. I ve used this to do my asyn task
variable i have used in my main activity which helps this task:
String extStorage=Environment.getExternalStorageDirectory()+"/t/";
ArrayList<Helper> helpobject=new ArrayList<Helper>();
int uptask=0;
int downtask=0;
public boolean onOptionsItemSelected(MenuItem item)
{
switch(item.getItemId())
{
case DOWNLOAD1:
MENU_STATE=MENU_DOWNLOAD;
map=display_check(current);
return true;
case UPLOAD:
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
{
if(current.getShare()==null)
{
Toast.makeText(this,"UPLOAD FAILED",Toast.LENGTH_LONG).show();
}
else
{
File f=new File(extStorage);
Helper help=new Helper();
help.setufolder(f);
help.setufoldersmb(current);
help.setauthentication(auth);
help.setupstate(1);
help.settasknumber(uptask);
uptask++;
help.settaskname("Upload");
help.setcontext(this.getApplicationContext());
help.execute(1);
}
}
else
{
Toast.makeText(this,"UPLOAD FAILED--NO SD CARD FOUND",Toast.LENGTH_LONG).show();
}
return true;
case DELETE1:
MENU_STATE=MENU_DELETE;
map=display_check(current);
return true;
case QUIT:
int x=0;
for(Helper k:helpobject)
{
if(k.getStatus().equals(AsyncTask.Status.RUNNING)||k.getStatus().equals(AsyncTask.Status.RUNNING))
{
Toast.makeText(k.getcontext(), "AccessPC "+k.gettaskname()+" "+k.gettasknumber()+" Cancelled", Toast.LENGTH_SHORT).show();
k.cancel(true);
}
helpobject.remove(x);
x++;
}
return true;
case DOWNLOAD2:
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
{
int tempcount=0;
for(int i=0;i<object.getCount();i++)
{
if(object.getter(i)==true)
{
tempcount++;
}
}
if(tempcount==0)
{
Toast.makeText(this,"Please choose atleast one item for download!!",Toast.LENGTH_LONG).show();
}
else
{
Helper help=new Helper();
helpobject.add(help);
help.settasknumber(downtask);
downtask++;
help.settaskname("Download");
help.setcontext(this.getApplicationContext());
help.setextstorage(extStorage);
help.setdownstate(1);
for(int i=0;i<object.getCount();i++)
{
if(object.getter(i)==true)
{
help.setarraysmb(map.get(object.getItem(i)));
}
}
help.execute(0);
}
}
else
{
Toast.makeText(this,"DOWNLOAD FAILED--NO SD CARD FOUND",Toast.LENGTH_LONG).show();
}
return true;
case DELETE2:
for(int i=0;i<object.getCount();i++)
{
if(object.getter(i)==true)
{
try
{
map.get(object.getItem(i)).delete();
}
catch (Exception e)
{
Toast.makeText(this,"cannot be deleted "+e,Toast.LENGTH_LONG).show();
}
}
}
return true;
case CANCEL:
MENU_STATE=MENU_GENERAL;
map=display(current);
return true;
case FINISH:
finish();
default:
return super.onOptionsItemSelected(item);
}
}
hi,when i tried to display the toast, as mentioned in one of the below comments, ive got the same exception .please see the code below whih i ve used to dispaly Toast in my async task:
(new Activity()).runOnUiThread(new Runnable(){#Override public void run() {//Your Toast
Toast.makeText(context, "AccessPC Download Task failed ",Toast.LENGTH_LONG).show();
}});
Do i need to make any changes to my async task code or options menu code?
I ve used handler like this:
public Handler handler = new Handler() {
public void handleMessage(Message msg)
{
Bundle b = msg.getData();
String key = b.getString(null);
Toast.makeText(getApplicationContext(),key, Toast.LENGTH_SHORT).show();
}
};
and i am calling handler like this:
Message msg = new Message();
Bundle b = new Bundle();
b.putString(null, "AccessPC "+taskname+" task "+tasknumber+" Finished");
msg.setData(b);
//this is error
t.handler.sendMessage(msg);
But how can i call a non-static method?do i need to create an object for my main class(class t extends list activity)?
Hi, please see another exception that ive got when i select 'QUIT' operation from options menu for the above async task and menu ive posted. how to avoid this exception:
05-07 16:24:07.573: E/AndroidRuntime(13466): FATAL EXCEPTION: main
05-07 16:24:07.573: E/AndroidRuntime(13466): java.util.ConcurrentModificationException
05-07 16:24:07.573: E/AndroidRuntime(13466): at java.util.ArrayList$ArrayListIterator.next(ArrayList.java:576)
05-07 16:24:07.573: E/AndroidRuntime(13466): at com.android.test.t.onOptionsItemSelected(t.java:622)
05-07 16:24:07.573: E/AndroidRuntime(13466): at android.app.Activity.onMenuItemSelected(Activity.java:2205)
05-07 16:24:07.573: E/AndroidRuntime(13466): at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:748)
05-07 16:24:07.573: E/AndroidRuntime(13466): at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:143)
05-07 16:24:07.573: E/AndroidRuntime(13466): at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:855)
05-07 16:24:07.573: E/AndroidRuntime(13466): at com.android.internal.view.menu.IconMenuView.invokeItem(IconMenuView.java:532)
05-07 16:24:07.573: E/AndroidRuntime(13466): at com.android.internal.view.menu.IconMenuItemView.performClick(IconMenuItemView.java:122)
05-07 16:24:07.573: E/AndroidRuntime(13466): at android.view.View$PerformClick.run(View.java:9080)
05-07 16:24:07.573: E/AndroidRuntime(13466): at android.os.Handler.handleCallback(Handler.java:587)
05-07 16:24:07.573: E/AndroidRuntime(13466): at android.os.Handler.dispatchMessage(Handler.java:92)
05-07 16:24:07.573: E/AndroidRuntime(13466): at android.os.Looper.loop(Looper.java:123)
05-07 16:24:07.573: E/AndroidRuntime(13466): at android.app.ActivityThread.main(ActivityThread.java:3683)
05-07 16:24:07.573: E/AndroidRuntime(13466): at java.lang.reflect.Method.invokeNative(Native Method)
05-07 16:24:07.573: E/AndroidRuntime(13466): at java.lang.reflect.Method.invoke(Method.java:507)
05-07 16:24:07.573: E/AndroidRuntime(13466): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
05-07 16:24:07.573: E/AndroidRuntime(13466): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
05-07 16:24:07.573: E/AndroidRuntime(13466): at dalvik.system.NativeStart.main(Native Method)
Can't create handler inside thread that has not called Looper.prepare(), the error message is rather straightforward.
You created a Handler object in your AsyncTask.doInBackground()(a background thread), which requires a message pump in that thread, that's the Looper.prepare() thing.
I think it may be easier to just move the creation of your Handler object out of AysncTask, to the UI thread.
Below is the edit after the OP edited his/her question
Toast.makeText(context, "AccessPC Upload task "+tasknumber+" Started", Toast.LENGTH_LONG).show();
The line above is simply not allowed in a background thread, showing a Toast message is something updating the UI, which must happen in the UI thread.
EDIT again
You can use a Handler, which is created in the UI thread, to send a message, and in the Handler, handle that message by showing your desired Toast message.
EDIT again 2
private final static int TOAST_MSG_ID_1 = 1;
private final static int TOAST_MSG_ID_2 = 2;
private final static int TOAST_MSG_ID_3 = 3;
// declare a Handler as an instance variable
Handler msgHandler = new Handler(){
#Override
public void handleMessage(Message msg) {
switch(msg.what()) {
case TOAST_MSG_ID_1:
Toast.makeText(...msg1...).show();
break;
case TOAST_MSG_ID_2:
Toast.makeText(...msg2...).show();
break;
.... other messages follow....
}
}
};
// and you will use the following to show a Toast message:
msgHandler.sendEmptyMessage(TOAST_MSG_ID_1);
msgHandler.sendEmptyMessage(TOAST_MSG_ID_2);
msgHandler.sendEmptyMessage(TOAST_MSG_ID_3);
...
For more info about Handler, take a look at the javadoc first. and google will bring you more.
write Toast message as below I hope it will work.
getApplicationContext().runOnUiThread(new Runnable() {
#Override
public void run() {
//Your Toast
}
});
Comment your all Toast message which you are showing using with Non-UI thread. I think this the problem..

Categories

Resources