Perform an Action when phone is shaked - java

I'm using shake-detector-librart to detect whether my phone is being shared or not. It is working fine, gives the exact results as needed in the background as well as while the application is opened. I need to perform any action when the phone is being shaken, but it isn't working for that.
Here's my code:
ShakeOptions options = new ShakeOptions()
.background(true)
.interval(1000)
.shakeCount(2)
.sensibility(3.0f);
this.shakeDetector = new ShakeDetector(options);
shakeDetector.start(this, new ShakeCallback() {
#Override
public void onShake() {
Toast.makeText(getApplicationContext(), "locationDetails", Toast.LENGTH_SHORT).show();
String msg_txt = "THis is a sammple sms";
String phoneNo = "03036018110";
System.out.println("jamoodgreat");
//sendSMS(phoneNo,msg_txt);
Log.d("event", "onShake");//this is not being printed
Toast.makeText(getApplicationContext(), "Jamshaid", Toast.LENGTH_LONG).show();//this toast is not being displayed as well.
}
});
}

I tested the following and it works fine (The Toast gets called/displayed).
public class MainActivity extends AppCompatActivity {
private ShakeDetector shakeDetector;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ShakeOptions options = new ShakeOptions()
.background(true)
.interval(1000)
.shakeCount(2)
.sensibility(2.0f);
shakeDetector = new ShakeDetector(options).start(this, new ShakeCallback() {
#Override
public void onShake() {
Toast.makeText(MainActivity.this, "onShake", Toast.LENGTH_SHORT).show();
}
});
}
}
Even though it worked, I had to shake the device vigorously before it was picked up.

Related

setOnClickListener not responding when button is clicked

I am fairly new to java but in this case, the button is not responding at all when it is clicked, no errors in the logcat are showing up, the ID of the button is correct and no other posts on here helped solve the issue, this is not all the code but hopefully, this will be enough.
public class activity_main extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_layout);
getSupportActionBar().hide();
}
int error_count;
public void on_click() {
Button page_2 = findViewById(R.id.page_2);
page_2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
int mother_edu_input = Integer.parseInt(((EditText) findViewById(R.id.mother_edu_input)).getText().toString());
error_writer("Text_View_Warning_1", mother_edu_input, 4);
if (error_count > 0) {
throw new NullPointerException();
} else {
Intent page_1_button = new Intent(activity_main.this, revision_time.class);
startActivity(page_1_button);
}
} catch (NullPointerException npe) {
}
}
});
}
You set your listener inside a method called on_click() and it doesn't appear like you call this method anywhere.
You should probably call on_click() inside your onCreate() to set the listener when creating your activity.

How to avoid android application crash, when setOwnerActivity(Activity activity) in custom DialogFragment causes nullpointerException?

I got a very strange exception while using Sharedpreferences and DialogFragment:
Unable to start activity ComponentInfo{com.example.barta1.site_patrol/com.example.barta1.site_patrol.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method
'void android.app.Dialog.setOwnerActivity(android.app.Activity)'
on a null object reference -
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2679)
I really do not have a clue what causes this error, but after this happened, I never be able to start
my application again, it continuosly crashed with the same exception above. The MainActivity is my launching activity in my application with a DialogFragment attached which I use to login users. I show this dialogfragment if the users not logged in (the "logged in" status saved in a sharedpreference object).
My MainActivity is like this:
public class MainActivity extends AppCompatActivity implements LoginDialogFragment.NoticeDialogListener {
//...
private LoginDialogFragment dialogFragment;
SharedPreferences pref;
SharedPreferences.Editor edit;
//...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pref = getSharedPreferences("Globals", MODE_PRIVATE);
edit = pref.edit();
boolean isloggedin = pref.getBoolean("Loggedin", false);
if (!isloggedin) {
//if not logged in show the login dialog
showLoginDialog();
}
else {
//... doing some network calls...
}
}
public void showLoginDialog() {
dialogFragment = new LoginDialogFragment();
dialogFragment.show(getFragmentManager(), "LoginDialogFragment");
}
/***
* Network calls if dialog dismissed
* Login dialog can only be closed if logging in is successful
* (if loginname and password matches).
*/
#Override
public void onDismiss() {
//... some network related jobs
}
}
And here is the fragment class:
public class LoginDialogFragment extends DialogFragment {
public interface NoticeDialogListener{
void onDismiss();
}
NoticeDialogListener mListener;
Activity activity;
AlertDialog dialog;
SharedPreferences pref;
SharedPreferences.Editor edit;
#Override
public void onAttach(Context context) {
super.onAttach(context);
try{
activity = (Activity) context;
mListener = (NoticeDialogListener) activity;
pref = activity.getSharedPreferences("Globals", MODE_PRIVATE);
edit = pref.edit();
} catch (ClassCastException e){
throw new ClassCastException(activity.toString() + "must implement NoticeDialogListener");
}
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
String username = pref.getString("Username", null);
if(username==null) {
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_signin, null);
final AutoCompleteTextView actv_username = view.findViewById(R.id.username);
final EditText password = view.findViewById(R.id.password);
dialog = new AlertDialog.Builder(new ContextThemeWrapper(getContext(), R.style.AlertDialogCustom))
.setView(view)
.setTitle("Bejelentkezés")
.setPositiveButton("OK", null)
.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialogInterface) {
final Button button = ( dialog).getButton(AlertDialog.BUTTON_POSITIVE);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String passw = password.getText().toString();
String user = actv_username.getText().toString();
try {
if (user.length() < 4 || passw.length() < 4) {
Toast.makeText(getContext(), "Too short user/pass.", Toast.LENGTH_SHORT).show();
dialog.show();
} else {
//login to account, if success dismiss.
login(user, passw, dialog);
}
} catch (Exception e) {
e.printStackTrace();
}
// dialog.dismiss();
}
});
}
});
dialog.setCanceledOnTouchOutside(false);
// set the DialogFragment to make the dialog unable to dismiss with back button
// (because not working if called on the dialog directly)
this.setCancelable(false);
return dialog;
} // end of - if username == null.
return null;
}
public void login(final String username, String password, final AlertDialog dialog){
//... some network call
//... if successful:
// edit.putString("Username", username);
// edit.commit();
// edit.putBoolean("Loggedin", true);
// edit.commit();
// dialog.dismiss();
// dialog.setOnShowListener(null);
//
// else
// Toast.makeText(getContext(),"Wrong login credentials",
// Toast.LENGTH_SHORT).show();
}
#Override
public void onDismiss(DialogInterface dialog) {
mListener.onDismiss();
dismissAllowingStateLoss();
}
After reinstalling the package, I could not recreate this exception (even when I killed app process, and start it from the recent apps), end users somehow managed to do this and that time, restarting the application was an instant crash (see the exception above.). It looks like parent activity becomes null somehow ( possible after saving the state and after cannot recover).
How to avoid this in the future? Is there a simple way to deal with this situation?
It would be also a great help if someone can explain to me when this "setOwnerActivity(Activity activity)" from the android library called, that way maybe I can identify what went wrong.
Thanks for any help.
As Mike M. stated out,
You cannot return null from onCreateDialog(). That's too late to be canceling or aborting the Dialog showing.
And the username check before creating the fragment will obviously solve the problem. Also, the LoggedIn field looks redundant now.

Using an intent to send email outside of an activity

I have an activity "Results" which does some calculations, and a button for the user to send an email containing those results. I have made a class called "Sender" to accomplish this, but startActivity isn't working in my Sender class. I know the actual intent works, because I could get it to work inside of my Results activity, just not in the Sender class.
public class Results extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button sendEmail = (Button) findViewById(R.id.resultsEMAIL);
sendEmail.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Sender sender = new Sender();
sender.sendEmail();
}
});
///////
public class Sender{
public void sendEmail(){
Intent sendEmail = new
Intent(Intent.ACTION_SEND_MULTIPLE);
ArrayList<Uri>uris = new ArrayList<Uri>();
uri.add(someUri);
uri.add(otherUri);
sendEmail.setType("message/rfc822");
sendEmail.putExtra(Intent.EXTRA_EMAIL, allEmails);
sendEmail.putExtra(Intent.EXTRA_SUBJECT, "Subject");
sendEmail.putExtra(Intent.EXTRA_TEXT, results);
sendEmail.putParcelableArrayListExtra(Intent.EXTRA_STREAM,uris);
try {
startActivity(Intent.createChooser(sendEmail, "Send")); }
catch
(android.content.ActivityNotFoundException ex)
{ Toast.makeText(context, "There are no email clients installed.", Toast.LENGTH_SHORT).show(); }
}
I have tried passing the context from Results
Results.context.startActivity(Intent.createChooser(SendEmail,"Send"));
And I have also tried
sendEmail.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Regardless of what I do, I get the exception
android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
Should I just abandon trying to do this in a separate class?? I wanted to make a Sender class to clean up Results.
You need to pass Context of the activity to sendMail() method.
public class Results extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button sendEmail = (Button) findViewById(R.id.resultsEMAIL);
sendEmail.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Sender sender = new Sender();
sender.sendEmail(Results.this);
}
});
And in your sendMail() method use context to start activity.
public void sendEmail(Context context){
Intent sendEmail = new Intent(Intent.ACTION_SEND_MULTIPLE);
//set data to intent
context.startActivity(Intent.createChooser(sendEmail, "Send"));
}

How initialize correctly static variable in PreferenceActivity

I have Preference class extent PreferenceActivity.
I create public static String quality; in Preference.class i add in onCreate
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref);
quality = "QUALITY_HIGH";//initialize
}
and add in Preference.class this method
public void getQuality() {
if (keyquality.equals("480p")) {
quality = "QUALITY_LOW";
//
}
if (keyquality.equals("720p")) {
//
quality = "QUALITY_720P";
}
if (keyquality.equals("1080p")) {
//
quality = "QUALITY_HIGH";
}
}
in another class i create method to get my variable and set settings
private void getqualityvideo() {
/*if (Prefernce.quality == null) {
preferencecamrecoder = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
} else {*/
if (Prefernce.quality.equals("QUALITY_LOW")) {
preferencecamrecoder = CamcorderProfile.get(CamcorderProfile.QUALITY_LOW);
}
if (Prefernce.quality.equals("QUALITY_720P")) {
preferencecamrecoder = CamcorderProfile.get(CamcorderProfile.QUALITY_720P);
}
if (Prefernce.quality.equals("QUALITY_HIGH")) {
preferencecamrecoder = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
}
// }
}
Problem:
when start application
private void startServes() {
btnStart = (ImageView) findViewById(R.id.StartService);
btnStart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
v.startAnimation(mAnimationImage);
Intent intent = new Intent(MainActivity.this, RecorderService.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startService(intent);
changeCamera
.setEnabled(false);
btnStart.setEnabled(false);
setings.setEnabled(false);
moveTaskToBack(false);
}
});
}
in another class in method
getqualityvideo() error NullPointerException
error in this first line
if (Prefernce.quality.equals("QUALITY_LOW"))
why the quality variable is empty?
The reason is that you're setting Preference.quality in the onCreate method in your Preference class. So what's probably happening is that when you start your application in your other class, Preference.quality is going to be null because it was never initialized to anything. The reason is that the other class has no way to access the onCreate method in your Preference class as of now. onCreate is executed when an activity starts, but that doesn't seem to happen anywhere in your code. A solution could be to initialize public static String quality outside of your onCreate method but still within the Preference class,
public static String quality = "QUALITY_HIGH";
#Override
public void onCreate(Bundle savedInstanceState) {
//insert code here
}
The problem was merely a scope issue.

Access from AsyncTask to Application Class or any other Global variables from any Classes

I can't access from AsyncTask to Application Class, or issue with SharedPreferences with last updated data, etc..
Basically why I need my Global variable is to keep track currently active activity, and it should be accessable from any type of class, like Activity, AsyncTask, Service, Receiver, Application, Etc...
I know there is lot of questions=answers in here, but none of those helped me.
I tried several ways to do this, but couldn't find any real resolution for this.
With SharedPreferences, I can use it, but after preferences updated and readed, returned previous value, works only after restart app.
With Application Class, no luck, can't access to Application from AsyncTask and service
Service runs AsyncTask on every 5sec, and AsyncTask should know if MainActivity is opened and running, so it can update contents to it.
I got pretty much everything working but, with this, I spend way too many hours on searching.
So please, if anybody can help me with this, it would be nice. :)
Here is little example how I do..
MainActivity.java
public class MainActivity extends Activity {
private boolean active = false;
SharedPreferences prefs;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
this.prefs = context.getSharedPreferences("com.my.app", Context.MODE_PRIVATE);
storeActivity("MainActivity");
this.active = true;
((App) this.getApplication()).setTopActivity("MainActivity");
}
public void storeActivity(String TOP_ACTIVITY) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("TOP_ACTIVITY", TOP_ACTIVITY);
editor.apply();
editor.commit();
}
#Override
public void onResume() {
super.onResume();
((App) this.getApplication()).setTopActivity("MainActivity");
this.active = true;
storeActivity("MainActivity");
}
#Override
public void onPause() {
super.onPause();
((App) this.getApplication()).setTopActivity("");
this.active = false;
storeActivity("");
}
#Override
public void onStart() {
super.onStart();
((App) this.getApplication()).setTopActivity(ACTIVITY_NAME);
this.active = true;
storeActivity("MainActivity");
}
#Override
public void onStop() {
super.onStop();
((App) this.getApplication()).setTopActivity("");
this.active = false;
storeActivity("");
}
}
Here is my Application Object,
App.java
public class App extends Application {
private String TOP_ACTIVITY;
public String getTopActivity() {
return TOP_ACTIVITY;
}
public void setTopActivity(String CURRENT_ACTIVITY) {
this.TOP_ACTIVITY = CURRENT_ACTIVITY;
}
public static Application getApplication() {
return new App();
}
}
And here is some AsyncTask getting information from server
Socket.java
public class SocketUpdater extends AsyncTask<String,Void,String> {
private Context context;
private SharedPreferences prefs;
public SocketUpdater(Context context) {
this.context = context;
this.prefs = context.getSharedPreferences("com.my.app", Context.MODE_PRIVATE);
}
#Override
protected String doInBackground(String... arg0) {
StringBuffer result = new StringBuffer("");
return new String(result);
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(context, "RESULT: " + result, Toast.LENGTH_SHORT).show();
String TOP_ACTIVITY = ((App) this.getApplication()).getTopActivity();
// THIS CANT WORK, NO this.getApplication()!!!
boolean MainActivityActive = MainActivity.active;
// THIS RETURNS ME FALSE ALL THE TIME
SharedPreferences.Editor editor = prefs.edit();
String PREF_TOP_ACTIVITY = prefs.getString("TOP_ACTIVITY", "");
if(MainActivityActive) {
Toast.makeText(context, "NEVER FIRES!", Toast.LENGTH_LONG).show();
}
if(TOP_ACTIVITY.equals("MainActivity")) {
Toast.makeText(context, "NEVER FIRES!", Toast.LENGTH_LONG).show();
}
if(PREF_TOP_ACTIVITY.equals("MainActivity")) {
Toast.makeText(context, "NEVER FIRES!", Toast.LENGTH_LONG).show();
}
}
}
Why not use "Otto" library from Square? You can send objects with ease between activity and service. I'm using it within my application for similar purpose.
I spent days for searching what causes the problem.
I found simple solution for this, and got all methods working like I wanted.
The thing was that I had my service running own separated process like this:
<service android:name="fi.hgs.apps.MyService"
android:process=":myService"
</service>
And just removed android:process=":myService" from AndroidManifest.xml

Categories

Resources