Code crashes every time the helper class is executed - java

Every time i open my app it crashes. I want to call the TTS method from another class so i made TTSHelper named class and added the speak method but its not working
This is main activity:
public class MainActivity extends Activity
{
TTSHelper TTSHelp;
private TextToSpeech myTTS;
// ON CREATE STAGE
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// TO CHECK IF I HAVE TTS INSTALLED OR NOT
initializeTextToSpeech();
}// END ON CREAE ??
// CHECKING TTS IS INSTALLED OR NOT
private void initializeTextToSpeech()
{
myTTS = new TextToSpeech(this, new TextToSpeech.OnInitListener(){
#Override
public void onInit(int i){
if(myTTS.getEngines().size() == 0) {
Toast.makeText(MainActivity.this, "No tts engine found"
, Toast.LENGTH_LONG).show();
finish();
} else {
//Toast.makeText(MainActivity.this,"Hi..! i'm i.Vert, here to assist you."
// , Toast.LENGTH_SHORT).show();
myTTS.setLanguage(Locale.US);
TTSHelp.speak("Hello Sir");
}
}
});
}
And this is the helper class that I made:
(Updated) added the oninit method
public class TTSHelper
{
TextToSpeech myTTS;
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
Toast.makeText(TTSHelper.this,
"Text-To-Speech engine is initialized", Toast.LENGTH_LONG).show();
}
else if (status == TextToSpeech.ERROR) {
Toast.makeText(TTSHelper.this,
"Error occurred while initializing Text-To-Speech engine", Toast.LENGTH_LONG).show();
}
}
// ANSWER OR SPEAK FUNCTION
public void speak( String message)
{
if(Build.VERSION.SDK_INT >= 21) {
myTTS.speak(message, TextToSpeech.QUEUE_FLUSH, null, null);
} else {
myTTS.speak(message, TextToSpeech.QUEUE_FLUSH, null);
}
}
}
And the log is:
Late-enabling -Xcheck:jni
01-07 00:44:34.901 31803 31803 E libc Access denied finding property "persist.vendor.sys.activitylog"
01-07 00:44:34.885 31803 31803 W re-initialized> type=1400 audit(0.0:60604): avc: denied { read } for name="u:object_r:mtk_amslog_prop:s0" dev="tmpfs" ino=7624 scontext=u:r:untrusted_app_25:s0:c512,c768 tcontext=u:object_r:mtk_amslog_prop:s0 tclass=file permissive=0
01-07 00:44:35.222 31803 31803 I e.martin.satya The ClassLoaderContext is a special shared library.
01-07 00:44:35.520 31803 31803 E BoostFramework BoostFramework() : Exception_1 = java.lang.ClassNotFoundException: com.qualcomm.qti.Performance
01-07 00:44:35.521 31803 31803 E BoostFramework BoostFramework() Ux Perf: Exception = java.lang.ClassNotFoundException: com.qualcomm.qti.UxPerformance
01-07 00:44:35.522 31803 31803 E BoostFramework BoostFramework() : Exception_1 = java.lang.ClassNotFoundException: com.qualcomm.qti.Performance
01-07 00:44:35.523 31803 31803 E BoostFramework BoostFramework() Ux Perf: Exception = java.lang.ClassNotFoundException: com.qualcomm.qti.UxPerformance
01-07 00:44:35.803 31803 31803 E BoostFramework BoostFramework() : Exception_1 = java.lang.ClassNotFoundException: com.qualcomm.qti.Performance
01-07 00:44:35.804 31803 31803 E BoostFramework BoostFramework() Ux Perf: Exception = java.lang.ClassNotFoundException: com.qualcomm.qti.UxPerformance
01-07 00:44:35.805 31803 31803 E BoostFramework BoostFramework() : Exception_1 = java.lang.ClassNotFoundException: com.qualcomm.qti.Performance
01-07 00:44:35.806 31803 31803 E BoostFramework BoostFramework() Ux Perf: Exception = java.lang.ClassNotFoundException: com.qualcomm.qti.UxPerformance
01-07 00:44:35.964 31803 31803 I TextToSpeech Sucessfully bound to com.google.android.tts
01-07 00:44:36.444 31803 31803 W Activity Slow Operation: Activity com.voice.martin.satyam/.MainActivity onCreate took 991ms
01-07 00:44:36.549 31803 31803 I SurfaceFactory [static] sSurfaceFactory = com.mediatek.view.impl.SurfaceFactoryImpl#b63ff83
01-07 00:44:36.587 31803 31803 D ViewRootImpl[MainActivity] hardware acceleration = true , fakeHwAccelerated = false, sRendererDisabled = false, forceHwAccelerated = false, sSystemRendererDisabled = false
01-07 00:44:36.598 31803 31803 V PhoneWindow DecorView setVisiblity: visibility = 0, Parent = android.view.ViewRootImpl#753037e, this = DecorView#add10df[MainActivity]
01-07 00:44:36.603 31803 31803 I TextToSpeech Connected to ComponentInfo{com.google.android.tts/com.google.android.tts.service.GoogleTTSService}
01-07 00:44:36.630 31803 31834 I TextToSpeech Set up connection to ComponentInfo{com.google.android.tts/com.google.android.tts.service.GoogleTTSService}
01-07 00:44:36.733 31803 31803 D Surface Surface::allocateBuffers(this=0xa2ffe800)
01-07 00:44:36.815 31803 31803 W RenderThread type=1400 audit(0.0:60605): avc: denied { search } for name="clients" dev="debugfs" ino=7474 scontext=u:r:untrusted_app_25:s0:c512,c768 tcontext=u:object_r:debugfs_ion:s0 tclass=dir permissive=0
01-07 00:44:36.859 31803 31833 I ConfigStore android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0
01-07 00:44:36.859 31803 31833 I ConfigStore android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasHDRDisplay retrieved: 0
01-07 00:44:36.859 31803 31833 I OpenGLRenderer Initialized EGL, version 1.4
01-07 00:44:36.859 31803 31833 D OpenGLRenderer Swap behavior 2
01-07 00:44:36.879 31803 31833 D Surface Surface::connect(this=0xa2ffe800,api=1)
01-07 00:44:36.881 31803 31833 I libEGL [MTK Game SDK] low_latency_mode(0) pid(-1) property(-1)
01-07 00:44:36.933 31803 31833 E ion ioctl c0044901 failed with code -1: Invalid argument
01-07 00:44:37.962 31803 31803 D AndroidRuntime Shutting down VM
01-07 00:44:37.965 31803 31803 E AndroidRuntime FATAL EXCEPTION: main
01-07 00:44:37.965 31803 31803 E AndroidRuntime Process: com.voice.martin.satyam, PID: 31803
01-07 00:44:37.965 31803 31803 E AndroidRuntime java.lang.NullPointerException: Attempt to invoke virtual method 'void com.voice.martin.satyam.TTSHelper.speak(java.lang.String)' on a null object reference
01-07 00:44:37.965 31803 31803 E AndroidRuntime at com.voice.martin.satyam.MainActivity$100000000.onInit(MainActivity.java:170)
01-07 00:44:37.965 31803 31803 E AndroidRuntime at android.speech.tts.TextToSpeech.dispatchOnInit(TextToSpeech.java:831)
How can I fix this?
After adding oninit method i still can't fix the problem.

TextToSpeech myTTS is never initialized, therefore it complains:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.voice.martin.satyam.TTSHelper.speak(java.lang.String)' on a null object reference.
You'd need something alike public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener.

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!!!

json volley showing error android

JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Patient patient = new Patient();
patient.setTitle(obj.getString("id"));
patient.setThumbnailUrl(obj.getString("image"));
patientList.add(patient);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
Logcat
01-07 07:27:29.294 7938-7938/info.androidhive.customlistviewvolley D/MainActivity: [{"id":"g"},{"image":"http:\/\/192.168.0.101\/test\/1.png"}]
01-07 07:27:29.312 7938-7938/info.androidhive.customlistviewvolley W/System.err: org.json.JSONException: No value for image
01-07 07:27:29.313 7938-7938/info.androidhive.customlistviewvolley W/System.err: at org.json.JSONObject.get(JSONObject.java:389)
01-07 07:27:29.313 7938-7938/info.androidhive.customlistviewvolley W/System.err: at org.json.JSONObject.getString(JSONObject.java:550)
01-07 07:27:29.313 7938-7938/info.androidhive.customlistviewvolley W/System.err: at info.androidhive.customlistviewvolley.MainActivity$1.onResponse(MainActivity.java:72)
01-07 07:27:29.313 7938-7938/info.androidhive.customlistviewvolley W/System.err: at info.androidhive.customlistviewvolley.MainActivity$1.onResponse(MainActivity.java:59)
01-07 07:27:29.313 7938-7938/info.androidhive.customlistviewvolley W/System.err: at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
01-07 07:27:29.313 7938-7938/info.androidhive.customlistviewvolley W/System.err: at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
01-07 07:27:29.313 7938-7938/info.androidhive.customlistviewvolley W/System.err: at android.os.Handler.handleCallback(Handler.java:739)
01-07 07:27:29.313 7938-7938/info.androidhive.customlistviewvolley W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
01-07 07:27:29.313 7938-7938/info.androidhive.customlistviewvolley W/System.err: at android.os.Looper.loop(Looper.java:135)
01-07 07:27:29.313 7938-7938/info.androidhive.customlistviewvolley W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5254)
01-07 07:27:29.313 7938-7938/info.androidhive.customlistviewvolley W/System.err: at java.lang.reflect.Method.invoke(Native Method)
01-07 07:27:29.313 7938-7938/info.androidhive.customlistviewvolley W/System.err: at java.lang.reflect.Method.invoke(Method.java:372)
01-07 07:27:29.313 7938-7938/info.androidhive.customlistviewvolley W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
01-07 07:27:29.313 7938-7938/info.androidhive.customlistviewvolley W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
01-07 07:27:29.313 7938-7938/info.androidhive.customlistviewvolley W/System.err: org.json.JSONException: No value for id
01-07 07:27:29.313 7938-7938/info.androidhive.customlistviewvolley W/System.err: at org.json.JSONObject.get(JSONObject.java:389)
01-07 07:27:29.313 7938-7938/info.androidhive.customlistviewvolley W/System.err: at org.json.JSONObject.getString(JSONObject.java:550)
01-07 07:27:29.313 7938-7938/info.androidhive.customlistviewvolley W/System.err: at info.androidhive.customlistviewvolley.MainActivity$1.onResponse(MainActivity.java:71)
I can get data from the database but why does it still show that there is no value for the image?
I have checked that the url is right to get the photo. The following things are the error showed in the logcat. Please give me some helps. Thank you.
You get wrong JSONObject , try this
try {
JSONObject objId = response.getJSONObject(0);
JSONObject objImage = response.getJSONObject(1);
Patient patient = new Patient();
patient.setTitle(objId.getString("id"));
patient.setThumbnailUrl(objImage.getString("image"));
patientList.add(patient);
} catch (JSONException e) {
e.printStackTrace();
}
Look at your response and try this
JSONObject obj = response.getJSONObject(0);
JSONObject obj1 = response.getJSONObject(1);
Patient patient = new Patient();
patient.setTitle(obj.getString("id"));
patient.setThumbnailUrl(obj1.getString("image"));

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

App crashes when trying to connect to bluetooth android

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,

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