App crashes when trying to connect to bluetooth android - java

I am trying to establish a bluetooth connection between my phone and a bluetooth device, but the app keeps crashing. By commenting, i have found out that the error is in the openBT() function. Can anyone help me out please?
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class PageOne extends Activity {
TextView myLabel;
TextView deviceFound;
Button openButton,closeButton;
BluetoothAdapter mBluetoothAdapter;
BluetoothDevice mmDevice;
BluetoothSocket mmSocket;
OutputStream mmOutputStream;
InputStream mmInputStream;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pageone);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
setUp();
openButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (openButton.getText().equals("Enable")) {
findBT();
}
if(openButton.getText().equals("Start Connection")){
System.out.println("here");
try{
openBT();
}catch (IOException e){e.printStackTrace();};
}
}
});
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
closeBT();
System.out.println("here too");
}
});
}
private void setUp() {
openButton = (Button) findViewById(R.id.button1);
myLabel = (TextView) findViewById(R.id.textView1);
closeButton = (Button) findViewById(R.id.button2);
deviceFound = (TextView) findViewById(R.id.textView2);
setButtonText();
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
setButtonText();
}
};
IntentFilter filter = new IntentFilter (BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver (receiver, filter);
}
private void setButtonText() {
closeButton.setText("Disable bluetooth");
if (mBluetoothAdapter.isEnabled()) {
openButton.setText("Start Connection");
myLabel.setText("Bluetooth is enabled");
} else {
openButton.setText("Enable");
myLabel.setText("Bluetooth is disabled");
}
}
private void findBT(){
if(mBluetoothAdapter == null)
{
myLabel.setText("No bluetooth adapter available");
}
if (!mBluetoothAdapter.isEnabled()) {
Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if(pairedDevices.size() > 0)
{
for(BluetoothDevice device : pairedDevices)
{
if(device.getName().equals("Hauwa"))
{
mmDevice = device;
break;
}
}
}
deviceFound.setText("Bluetooth Device Found");
}
private void closeBT(){
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
deviceFound.setText("bvnbvnvb");
}
}
void openBT() throws IOException{
final UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
mmOutputStream = mmSocket.getOutputStream();
mmInputStream = mmSocket.getInputStream();
}
}
and here is the logcat error
01-07 02:55:23.189: W/dalvikvm(11382): threadid=1: thread exiting with uncaught exception (group=0x401f0560)
01-07 02:55:23.189: E/AndroidRuntime(11382): FATAL EXCEPTION: main
01-07 02:55:23.189: E/AndroidRuntime(11382): java.lang.NullPointerException
01-07 02:55:23.189: E/AndroidRuntime(11382): at com.example.BluetoothExample.PageOne.openBT(PageOne.java:147)
01-07 02:55:23.189: E/AndroidRuntime(11382): at com.example.BluetoothExample.PageOne$1.onClick(PageOne.java:51)
01-07 02:55:23.189: E/AndroidRuntime(11382): at android.view.View.performClick(View.java:2579)
01-07 02:55:23.189: E/AndroidRuntime(11382): at android.view.View$PerformClick.run(View.java:9246)
01-07 02:55:23.189: E/AndroidRuntime(11382): at android.os.Handler.handleCallback(Handler.java:587)
01-07 02:55:23.189: E/AndroidRuntime(11382): at android.os.Handler.dispatchMessage(Handler.java:92)
01-07 02:55:23.189: E/AndroidRuntime(11382): at android.os.Looper.loop(Looper.java:130)
01-07 02:55:23.189: E/AndroidRuntime(11382): at android.app.ActivityThread.main(ActivityThread.java:3735)
01-07 02:55:23.189: E/AndroidRuntime(11382): at java.lang.reflect.Method.invokeNative(Native Method)
01-07 02:55:23.189: E/AndroidRuntime(11382): at java.lang.reflect.Method.invoke(Method.java:507)
01-07 02:55:23.189: E/AndroidRuntime(11382): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
01-07 02:55:23.189: E/AndroidRuntime(11382): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:662)
01-07 02:55:23.189: E/AndroidRuntime(11382): at dalvik.system.NativeStart.main(Native Method)
01-07 02:55:23.199: E/AndroidRuntime(11382): [Blue Error Handler] Make Debugging Report file for main
01-07 02:55:23.199: E/AndroidRuntime(11382): java.lang.NullPointerException
01-07 02:55:23.199: E/AndroidRuntime(11382): at com.example.BluetoothExample.PageOne.openBT(PageOne.java:147)
01-07 02:55:23.199: E/AndroidRuntime(11382): at com.example.BluetoothExample.PageOne$1.onClick(PageOne.java:51)
01-07 02:55:23.199: E/AndroidRuntime(11382): at android.view.View.performClick(View.java:2579)
01-07 02:55:23.199: E/AndroidRuntime(11382): at android.view.View$PerformClick.run(View.java:9246)
01-07 02:55:23.199: E/AndroidRuntime(11382): at android.os.Handler.handleCallback(Handler.java:587)
01-07 02:55:23.199: E/AndroidRuntime(11382): at android.os.Handler.dispatchMessage(Handler.java:92)
01-07 02:55:23.199: E/AndroidRuntime(11382): at android.os.Looper.loop(Looper.java:130)
01-07 02:55:23.199: E/AndroidRuntime(11382): at android.app.ActivityThread.main(ActivityThread.java:3735)
01-07 02:55:23.199: E/AndroidRuntime(11382): at java.lang.reflect.Method.invokeNative(Native Method)
01-07 02:55:23.199: E/AndroidRuntime(11382): at java.lang.reflect.Method.invoke(Method.java:507)
01-07 02:55:23.199: E/AndroidRuntime(11382): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
01-07 02:55:23.199: E/AndroidRuntime(11382): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:662)
01-07 02:55:23.199: E/AndroidRuntime(11382): at dalvik.system.NativeStart.main(Native Method)

are you sure that you have mmDevice not null? Are you sure you set mmDevice in findBT()?
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if(pairedDevices.size() > 0)
{
for(BluetoothDevice device : pairedDevices)
{
if(device.getName().equals("Hauwa"))
{
mmDevice = device;
break;
}
}
}

Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
String tmpS;
String targetS = "Hauwa";
if(pairedDevices.size() > 0)
{
for(BluetoothDevice device : pairedDevices)
{
tmpS = device.getName() + " ";
tmpS = tmpS.substring(0,targetS.length());
if(tmpS.equals(targetS))
{
mmDevice = device;
break;
}
}
you need to prevent the device name to be null. Even if your own device has name that is not null, the code could read other BLE device nearby that is null. You also need to prevent overflow at substring and equals functions,

Related

Android - Programmatically Screenshot and Share to Facebook

I have button which function is to take screenshot and share it to Facebook. when i try it in my Samsung with JellyBean OS device its working perfectly, but when i try it to BlueStack with JellyBean OS and CheeryMobile with Lollipop OS things are not working, i check the Logcat and i see some error.
my code
onClick of Button call takeScreenshot();
private void takeScreenshot() {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
sharePhotoToFacebook(imageFile);
} catch (Throwable
e.printStackTrace();
}
}
private void sharePhotoToFacebook(File imageFile){
Uri imageUri = Uri.fromFile(imageFile);
try {
image = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
} catch (IOException e) {
e.printStackTrace();
}
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
List<String> permissionNeeds = Arrays.asList("publish_actions");
//this loginManager helps you eliminate adding a LoginButton to your UI
loginManager = LoginManager.getInstance();
loginManager.logInWithPublishPermissions(this, permissionNeeds);
loginManager.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
try{
SharePhoto photo = new SharePhoto.Builder()
.setBitmap(image)
.setCaption(scoreFinal)
.build();
SharePhotoContent content = new SharePhotoContent.Builder()
.addPhoto(photo)
.build();
ShareApi.share(content, null);
final Dialog dialog = new Dialog(ActivityShare.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.sucess_shared);
dialog.show();
Button btnOk = (Button) dialog.findViewById(R.id.btnOk);
btnOk.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}catch (Exception e){
Log.e("Error on share", String.valueOf(e));
}
}
#Override
public void onCancel() {
Log.w("OnCancel", "Canceled by user");
// System.out.println("onCancel");
}
#Override
public void onError(FacebookException exception) {
final Dialog dialog = new Dialog(ActivityShare.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.sucess_shared);
TextView title = (TextView)dialog.findViewById(R.id.titleSuccess);
TextView desc = (TextView)dialog.findViewById(R.id.descriptionHere);
title.setText("Unsuccessfull");
desc.setText("Something's wrong, Please check your internet connection and try again.");
dialog.show();
Button btnOk = (Button) dialog.findViewById(R.id.btnOk);
btnOk.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
Log.e("OnError", String.valueOf(exception));
// System.out.println("onError");
}
});
}
LogCat Error
01-07 23:34:36.767 2024-2024/com.sample.app W/System.err: java.io.FileNotFoundException: /mnt/sdcard/Thu Jan 07 23:34:36 SGT 2016.jpg: open failed: EINVAL (Invalid argument)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: at libcore.io.IoBridge.open(IoBridge.java:406)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: at java.io.FileOutputStream.<init>(FileOutputStream.java:88)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: at java.io.FileOutputStream.<init>(FileOutputStream.java:73)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: at com.sample.app.ActivityShare.takeScreenshot(ActivityShare.java:225)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: at com.sample.app.ActivityShare.access$000(ActivityShare.java:42)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: at com.sample.app.ActivityShare$1.onClick(ActivityShare.java:103)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: at android.view.View.performClick(View.java:3511)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: at android.view.View$PerformClick.run(View.java:14105)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: at android.os.Handler.handleCallback(Handler.java:605)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: at android.os.Handler.dispatchMessage(Handler.java:92)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: at android.os.Looper.loop(Looper.java:137)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: at android.app.ActivityThread.main(ActivityThread.java:4424)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: at java.lang.reflect.Method.invokeNative(Native Method)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: at java.lang.reflect.Method.invoke(Method.java:511)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:592)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: at dalvik.system.NativeStart.main(Native Method)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: Caused by: libcore.io.ErrnoException: open failed: EINVAL (Invalid argument)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: at libcore.io.Posix.open(Native Method)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: at libcore.io.IoBridge.open(IoBridge.java:390)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: ... 16 more
i have no idea about the problem.
Please help me. Thank you!!!

Android - ContentProvider.rawQuery throws NullPointerException

I'm getting familiar with programming Android and ContectProviders. I have created the code (in testing purposes) to check reading/writing to database
This is the code TestProvider.java
package com.example.testapp;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
public class TestProvider extends ContentProvider
{
private static final String DBNAME = "testdb";
private static final String SQL_CREATE_MAIN = "CREATE TABLE if not exists test(id INTEGER PRIMARY KEY, word TEXT)";
private MainDatabaseHelper helper;
#Override
public int delete(Uri uri, String selection, String[] selectionArgs)
{
return 0;
}
#Override
public String getType(Uri uri)
{
return null;
}
#Override
public Uri insert(Uri uri, ContentValues values)
{
return null;
}
#Override
public boolean onCreate()
{
helper = new MainDatabaseHelper(getContext());
return false;
}
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
{
return helper.getReadableDatabase().rawQuery("SELECT * FROM test", null);
}
#Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs)
{
return 0;
}
protected static final class MainDatabaseHelper extends SQLiteOpenHelper
{
MainDatabaseHelper(Context context)
{
super(context, DBNAME, null, 1);
}
public void onCreate(SQLiteDatabase db)
{
db.execSQL(SQL_CREATE_MAIN);
db.execSQL("INSERT INTO test (word) VALUES ('AAA')");
db.execSQL("INSERT INTO test (word) VALUES ('BBB')");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
}
}
}
And this is MainActivity.java
package com.example.testapp;
import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TestProvider provider = new TestProvider();
Cursor c = provider.query(Uri.parse("content://com.example.testapp.provider/test"), null, null, null, null);
do
{
Log.d("MainActivity", String.format("ID:%s / Word:%s", c.getInt(c.getColumnIndex("id")), c.getString(c.getColumnIndex("word"))));
}
while(c.moveToNext());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Stacktrace from logcat:
07-30 15:38:25.695: E/Trace(3533): error opening trace file: No such file or directory (2)
07-30 15:38:26.255: D/AndroidRuntime(3533): Shutting down VM
07-30 15:38:26.305: W/dalvikvm(3533): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
07-30 15:38:26.345: E/AndroidRuntime(3533): FATAL EXCEPTION: main
07-30 15:38:26.345: E/AndroidRuntime(3533): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.testapp/com.example.testapp.MainActivity}: java.lang.NullPointerException
07-30 15:38:26.345: E/AndroidRuntime(3533): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
07-30 15:38:26.345: E/AndroidRuntime(3533): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
07-30 15:38:26.345: E/AndroidRuntime(3533): at android.app.ActivityThread.access$600(ActivityThread.java:141)
07-30 15:38:26.345: E/AndroidRuntime(3533): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
07-30 15:38:26.345: E/AndroidRuntime(3533): at android.os.Handler.dispatchMessage(Handler.java:99)
07-30 15:38:26.345: E/AndroidRuntime(3533): at android.os.Looper.loop(Looper.java:137)
07-30 15:38:26.345: E/AndroidRuntime(3533): at android.app.ActivityThread.main(ActivityThread.java:5041)
07-30 15:38:26.345: E/AndroidRuntime(3533): at java.lang.reflect.Method.invokeNative(Native Method)
07-30 15:38:26.345: E/AndroidRuntime(3533): at java.lang.reflect.Method.invoke(Method.java:511)
07-30 15:38:26.345: E/AndroidRuntime(3533): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-30 15:38:26.345: E/AndroidRuntime(3533): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-30 15:38:26.345: E/AndroidRuntime(3533): at dalvik.system.NativeStart.main(Native Method)
07-30 15:38:26.345: E/AndroidRuntime(3533): Caused by: java.lang.NullPointerException
07-30 15:38:26.345: E/AndroidRuntime(3533): at com.example.testapp.TestProvider.query(TestProvider.java:45)
07-30 15:38:26.345: E/AndroidRuntime(3533): at com.example.testapp.MainActivity.onCreate(MainActivity.java:19)
07-30 15:38:26.345: E/AndroidRuntime(3533): at android.app.Activity.performCreate(Activity.java:5104)
07-30 15:38:26.345: E/AndroidRuntime(3533): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
07-30 15:38:26.345: E/AndroidRuntime(3533): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
07-30 15:38:26.345: E/AndroidRuntime(3533): ... 11 more
AndroidManifest.xml (the part with the provider)
<provider android:name="com.example.testapp.TestProvider" android:authorities="com.example.testapp.provider" android:exported="false">
</provider>
Where is the problem? Thanks
the problem is this line. TestProvider provider = new TestProvider(); You should not instantiate the ContentProvider directly but use getContentResolver() from your Activity. Android instantiates it for it.

LibGDX: Activity has leaked window when trying to post to Facebook

Context: I created a LibGDX game (extends AndroidApplication) that switches to another activity (extends FragmentActivity) to start a social Facebook sharing activity (extends Fragments). I followed the Tutorial here: https://developers.facebook.com/docs/android/scrumptious/publish-open-graph-story#step6c
However, when I try to run my program, I get a Activity leaked window error. Full error log below:
01-07 00:20:33.160: E/WindowManager(23786): Activity com.pressx.thedevice.SocialActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#41cca0c0 that was originally added here
01-07 00:20:33.160: E/WindowManager(23786): android.view.WindowLeaked: Activity com.pressx.thedevice.SocialActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#41cca0c0 that was originally added here
01-07 00:20:33.160: E/WindowManager(23786): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:374)
01-07 00:20:33.160: E/WindowManager(23786): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:307)
01-07 00:20:33.160: E/WindowManager(23786): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:239)
01-07 00:20:33.160: E/WindowManager(23786): at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:152)
01-07 00:20:33.160: E/WindowManager(23786): at android.view.Window$LocalWindowManager.addView(Window.java:547)
01-07 00:20:33.160: E/WindowManager(23786): at android.app.Dialog.show(Dialog.java:282)
01-07 00:20:33.160: E/WindowManager(23786): at android.app.ProgressDialog.show(ProgressDialog.java:116)
01-07 00:20:33.160: E/WindowManager(23786): at android.app.ProgressDialog.show(ProgressDialog.java:99)
01-07 00:20:33.160: E/WindowManager(23786): at com.pressx.facebook.SelectionFragment.handleAnnounce(SelectionFragment.java:492)
01-07 00:20:33.160: E/WindowManager(23786): at com.pressx.facebook.SelectionFragment.access$2(SelectionFragment.java:480)
01-07 00:20:33.160: E/WindowManager(23786): at com.pressx.facebook.SelectionFragment$2.onClick(SelectionFragment.java:385)
01-07 00:20:33.160: E/WindowManager(23786): at android.view.View.performClick(View.java:4101)
01-07 00:20:33.160: E/WindowManager(23786): at android.view.View$PerformClick.run(View.java:17087)
01-07 00:20:33.160: E/WindowManager(23786): at android.os.Handler.handleCallback(Handler.java:615)
01-07 00:20:33.160: E/WindowManager(23786): at android.os.Handler.dispatchMessage(Handler.java:92)
01-07 00:20:33.160: E/WindowManager(23786): at android.os.Looper.loop(Looper.java:137)
01-07 00:20:33.160: E/WindowManager(23786): at android.app.ActivityThread.main(ActivityThread.java:4849)
01-07 00:20:33.160: E/WindowManager(23786): at java.lang.reflect.Method.invokeNative(Native Method)
01-07 00:20:33.160: E/WindowManager(23786): at java.lang.reflect.Method.invoke(Method.java:511)
01-07 00:20:33.160: E/WindowManager(23786): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
01-07 00:20:33.160: E/WindowManager(23786): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
01-07 00:20:33.160: E/WindowManager(23786): at dalvik.system.NativeStart.main(Native Method)
Reading around got me that maybe a ProgressDialog issue occurred. However, I followed the Facebook tutorial and ran the sample app that it created, no such error occurred.
Following are all locations of ProgressDialog and their contexts:
Private Variable
private ProgressDialog progressDialog;
in
public class SelectionFragment extends Fragment {
...
private ProgressDialog progressDialog;
...
}
ProgressDialog.show()
progressDialog = ProgressDialog.show(getActivity(), "", getActivity().getResources().getString(R.string.progress_dialog_text), true);
in
private void handleAnnounce() {
pendingAnnounce = false;
Session session = Session.getActiveSession();
if(session == null || !session.isOpened())
return;
List<String> permissions = session.getPermissions();
if(!permissions.containsAll(PERMISSIONS)) {
pendingAnnounce = true;
requestPublishPermissions(session);
return;
}
progressDialog = ProgressDialog.show(getActivity(), "", getActivity().getResources().getString(R.string.progress_dialog_text), true);
AsyncTask<Void, Void, Response> task = new AsyncTask<Void, Void, Response>() {
#Override
protected Response doInBackground(Void... voids) {
HitAction hitAction = GraphObject.Factory.create(HitAction.class);
for(BaseListElement element : listElements) {
element.populateOGAction(hitAction);
}
Request request = new Request(Session.getActiveSession(), POST_ACTION_PATH, null, HttpMethod.POST);
request.setGraphObject(hitAction);
return request.executeAndWait();
}
#Override
protected void onPostExecute(Response response) {
onPostActionResponse(response);
}
};
task.execute();
}
if() condition
if(progressDialog != null) {
progressDialog.dismiss();
progressDialog = null;
}
in
private void onPostActionResponse(Response response) {
if(progressDialog != null) {
progressDialog.dismiss();
progressDialog = null;
}
if(getActivity() == null)
return;
PostResponse postResponse = response.getGraphObjectAs(PostResponse.class);
if(postResponse != null && postResponse.getId() != null) {
String dialogBody = String.format(getString(R.string.result_dialog_text), postResponse.getId());
new AlertDialog.Builder(getActivity()).setPositiveButton(R.string.result_dialog_button_text, null).setTitle(R.string.result_dialog_title).setMessage(dialogBody).show();
init(null);
}
else
handleError(response.getError());
}
Full Code Here: https://github.com/putty174/TheDevice/blob/Max/TheDevice-android/src/com/pressx/facebook/SelectionFragment.java

NullPointerException when using EditText

I have the following function that i call from 2 different functions. the first way i call all is correct, the second way i get the following NullPointerException.
any idea why ?
private void doSearch(View v) {
Activity activity = getActivity();
//get the text:
EditText editSearch = (EditText) v.findViewById(R.id.editSearch);
String query = editSearch.getText().toString();
//check if 2 letters were entered for search
if (query.length()>1){
//call service with extra
Intent intent = new Intent(activity, SearchPlacesService.class);
intent.putExtra("query", query);
activity.startService(intent);
}else{
Toast.makeText(getActivity(), "Please enter 2 letters for search", Toast.LENGTH_SHORT).show();
}
}
//good call
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
switch (v.getId()) {
case R.id.editSearch:
doSearch(v);
return true;
}
return false;
}
//unsuccessful call
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSearch:
doSearch((TextView) v);
break;
}
}
the Logcat:
01-07 09:29:08.843: E/AndroidRuntime(1078): FATAL EXCEPTION: main
01-07 09:29:08.843: E/AndroidRuntime(1078): java.lang.NullPointerException
01-07 09:29:08.843: E/AndroidRuntime(1078): at com.lora_solomon.myfavoriteplaces.view.FragmentList.doSearch(FragmentList.java:137)
01-07 09:29:08.843: E/AndroidRuntime(1078): at com.lora_solomon.myfavoriteplaces.view.FragmentList.onClick(FragmentList.java:100)
01-07 09:29:08.843: E/AndroidRuntime(1078): at android.view.View.performClick(View.java:4084)
01-07 09:29:08.843: E/AndroidRuntime(1078): at android.view.View$PerformClick.run(View.java:16966)
01-07 09:29:08.843: E/AndroidRuntime(1078): at android.os.Handler.handleCallback(Handler.java:615)
01-07 09:29:08.843: E/AndroidRuntime(1078): at android.os.Handler.dispatchMessage(Handler.java:92)
01-07 09:29:08.843: E/AndroidRuntime(1078): at android.os.Looper.loop(Looper.java:137)
01-07 09:29:08.843: E/AndroidRuntime(1078): at android.app.ActivityThread.main(ActivityThread.java:4745)
01-07 09:29:08.843: E/AndroidRuntime(1078): at java.lang.reflect.Method.invokeNative(Native Method)
01-07 09:29:08.843: E/AndroidRuntime(1078): at java.lang.reflect.Method.invoke(Method.java:511)
01-07 09:29:08.843: E/AndroidRuntime(1078): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
01-07 09:29:08.843: E/AndroidRuntime(1078): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-07 09:29:08.843: E/AndroidRuntime(1078): at dalvik.system.NativeStart.main(Native Method)
appreciate any help!!
Here you are passing TextView as an arguement for the doSearch method. And you are getting the EditText by using TextView so obviously editText is null
I guess this line is causing NPE
String query = editSearch.getText().toString();
Try this..for fetching the EditText
View parent =(View) v.getParent();
EditText editSearch = (EditText) parent.findViewById(R.id.editSearch);
you are casting the view in your function to an EditText and you are passing TextView in OnClick try this doSearch((EditText)v);
//unsuccessful call
public void onClick(View v)
{
switch (v.getId()) {
case R.id.btnSearch:
doSearch((TextView) v);//changes
break;
}
}
In your above code you are passing view as Textview doSearch((TextView)v) and in your doSearch method implementation inner you are casting TextView to EditText this reason arrising NullpointerException( EditText editSearch = (EditText) v.findViewById(R.id.editSearch);)
Changes
doSearch((TextView) v);
to
doSearch((EditText) v);

send email activity in new instance

I'm trying to send an email from my email class but when the program gets to startActivity it crashes I think it might has something to do with the manifest. Below is my main activity
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
public class InvoiceActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void SendMessage(View v)
{
// get email parameters
SMTPmail mail = new SMTPmail();
mail.SendSMTP("body of email","subject of email","recipient#example.com");
}
}
here is the SMTPmail
import android.app.Activity;
import android.content.Intent;
import android.widget.Toast;
public class SMTPmail extends Activity {
public void SendSMTP(String message, String subject, String recipted)
{
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{recipted});
i.putExtra(Intent.EXTRA_CC, "");
i.putExtra(Intent.EXTRA_SUBJECT, subject);
i.putExtra(Intent.EXTRA_TEXT , message);
try {
startActivity(Intent.createChooser(i, "Send mail..."));//crashes here in debug
finish();
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(SMTPmail.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
}
this is the manifest
<?xml version="1.0" encoding="utf-8"?>
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:label="#string/app_name"
android:name=".InvoiceActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SMTPmail"
android:noHistory="true">
</activity>
</application>
logcat below
01-07 00:01:25.199: D/dalvikvm(14198): GC_EXTERNAL_ALLOC freed 43K, 51% free 2687K/5379K, external 0K/0K, paused 54ms
01-07 00:01:30.389: D/AndroidRuntime(14198): Shutting down VM
01-07 00:01:30.389: W/dalvikvm(14198): threadid=1: thread exiting with uncaught exception (group=0x40018560)
01-07 00:01:30.399: E/AndroidRuntime(14198): FATAL EXCEPTION: main
01-07 00:01:30.399: E/AndroidRuntime(14198): java.lang.IllegalStateException: Could not execute method of the activity
01-07 00:01:30.399: E/AndroidRuntime(14198): at android.view.View$1.onClick(View.java:2165)
01-07 00:01:30.399: E/AndroidRuntime(14198): at android.view.View.performClick(View.java:2506)
01-07 00:01:30.399: E/AndroidRuntime(14198): at android.view.View$PerformClick.run(View.java:9112)
01-07 00:01:30.399: E/AndroidRuntime(14198): at android.os.Handler.handleCallback(Handler.java:587)
01-07 00:01:30.399: E/AndroidRuntime(14198): at android.os.Handler.dispatchMessage(Handler.java:92)
01-07 00:01:30.399: E/AndroidRuntime(14198): at android.os.Looper.loop(Looper.java:130)
01-07 00:01:30.399: E/AndroidRuntime(14198): at android.app.ActivityThread.main(ActivityThread.java:3835)
01-07 00:01:30.399: E/AndroidRuntime(14198): at java.lang.reflect.Method.invokeNative(Native Method)
01-07 00:01:30.399: E/AndroidRuntime(14198): at java.lang.reflect.Method.invoke(Method.java:507)
01-07 00:01:30.399: E/AndroidRuntime(14198): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:864)
01-07 00:01:30.399: E/AndroidRuntime(14198): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:622)
01-07 00:01:30.399: E/AndroidRuntime(14198): at dalvik.system.NativeStart.main(Native Method)
01-07 00:01:30.399: E/AndroidRuntime(14198): Caused by: java.lang.reflect.InvocationTargetException
01-07 00:01:30.399: E/AndroidRuntime(14198): at java.lang.reflect.Method.invokeNative(Native Method)
01-07 00:01:30.399: E/AndroidRuntime(14198): at java.lang.reflect.Method.invoke(Method.java:507)
01-07 00:01:30.399: E/AndroidRuntime(14198): at android.view.View$1.onClick(View.java:2160)
01-07 00:01:30.399: E/AndroidRuntime(14198): ... 11 more
01-07 00:01:30.399: E/AndroidRuntime(14198): Caused by: java.lang.NullPointerException
01-07 00:01:30.399: E/AndroidRuntime(14198): at android.app.Activity.startActivityForResult(Activity.java:2827)
01-07 00:01:30.399: E/AndroidRuntime(14198): at android.app.Activity.startActivity(Activity.java:2933)
01-07 00:01:30.399: E/AndroidRuntime(14198): at com.android.EUROPE.Invoice.SMTPmail.SendSMTP(SMTPmail.java:17)
01-07 00:01:30.399: E/AndroidRuntime(14198): at com.android.EUROPE.Invoice.InvoiceActivity.SendMessage(InvoiceActivity.java:19)
01-07 00:01:30.399: E/AndroidRuntime(14198): ... 14 more
As James already said, there is no reason for SMTPmail to extend Activity. A simple implementation could look like this.
SMTPmail:
public class SMTPmail {
public static void sendSMTP(Context context, String message, String subject, String recipted)
{
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{recipted});
i.putExtra(Intent.EXTRA_CC, "");
i.putExtra(Intent.EXTRA_SUBJECT, subject);
i.putExtra(Intent.EXTRA_TEXT , message);
try {
context.startActivity(Intent.createChooser(i, "Send mail..."));//crashes here in debug
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(context, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
}
In InvoiceActivity:
public void SendMessage(View v)
{
SMTPmail.sendSMTP(this, "body of email","subject of email","recipient#example.com");
}
Is there a reason SMTPmail extends Activity? This looks superfluous. Just change STMPmail so that it does not extend any classes and this should work. You will have to pass a Context into that method to get things like startActivity().

Categories