Chat application online status - java

I'm trying to make a chat app. Everything is working except one thing. So I want the users to see if the person they chat whit is online. I made that work but now every time the person is going in on an other chat the online status blink. I have found where the problem is but I dont know how to fix it.
So when a person1 is in the chat it can see a green box where it says online if person2 is online. But if person2 is going in to a chat the green box will blink for person1.
The problem is in onResume and onPause. So when person2 is going from mainActivity to chatActivity it will do onPause() on mainActivity and set online to 0 and the do onResume() on chatActivity where it sets it to 1.
I know that the order is ActivityA.onPause, ActivityB.onCreate, ActivityB.onStart, ActivityB.onResume, ActivityA.onStop. So I dont want it to do onPause() when it going from one Activity to another Activity but still do it when you tab down or close the app. is that possible?
public class BaseActivity extends AppCompatActivity {
private DocumentReference documentReference;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PreferenceManager preferenceManager = new
PreferenceManager(getApplicationContext());
FirebaseFirestore database = FirebaseFirestore.getInstance();
documentReference = database.collection(Constants.KEY_COLLECTION_USERS)
.document(preferenceManager.getString(Constants.KEY_USER_ID));
}
#Override
protected void onPause() {
super.onPause();
documentReference.update(Constants.KEY_AVAILABLE, 0);
}
#Override
protected void onResume() {
super.onResume();
documentReference.update(Constants.KEY_AVAILABLE, 1);
}
}
public class MainActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
preferenceManager = new PreferenceManager(getApplicationContext());
init();
loadUserDetails();
getToken();
setListeners();
listenConversations();
}
}
public class ChatActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityChatBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
setListeners();
loadReceiverDetails();
init();
listenMessages();
}
#Override
protected void onResume() {
super.onResume();
listenAvailabilityOfReceiver();
}
}

Did fix it in a ugly way. I made variable that knows if the user is still in the app or not.
#Override
protected void onPause() {
super.onPause();
if (!stillInApp) {
DocumentReference documentReference;
PreferenceManager preferenceManager = new
PreferenceManager(getApplicationContext());
FirebaseFirestore database = FirebaseFirestore.getInstance();
documentReference = database.collection(Constants.KEY_COLLECTION_USERS)
.document(preferenceManager.getString(Constants.KEY_USER_ID));
documentReference.update(Constants.KEY_AVAILABLE, 0);
}
}
#Override
protected void onResume() {
super.onResume();
DocumentReference documentReference;
PreferenceManager preferenceManager = new
PreferenceManager(getApplicationContext());
FirebaseFirestore database = FirebaseFirestore.getInstance();
documentReference = database.collection(Constants.KEY_COLLECTION_USERS)
.document(preferenceManager.getString(Constants.KEY_USER_ID));
documentReference.update(Constants.KEY_AVAILABLE, 1);
stillInApp = false;
listenAvailabilityOfReceiver();
}

Related

Add Save Option to QR Code Scanner using Android Studio 3.0.1

Please help me out... I am using Android Studio 3.0.1 and I have a code that scan the QR code and now I want to save the scanned data. My code just scan the code and display it in a text format with options share via SMS,Email and history and No save option. I need to save this text document. How can I add save option?
Below is my code.
MainActivity.java
public class MainActivity extends AppCompatActivity {
public static TextView tvresult;
private Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvresult = (TextView) findViewById(R.id.tvresult);
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ScanActivity.class);
startActivity(intent);
}
});
}
ScanActivity.java
public class ScanActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler{
private ZXingScannerView mScannerView;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
mScannerView = new ZXingScannerView(this); // Programmatically initialize the scanner view
setContentView(mScannerView); // Set the scanner view as the content view
}
#Override
public void onResume() {
super.onResume();
mScannerView.setResultHandler(this); // Register ourselves as a handler for scan results.
mScannerView.startCamera(); // Start camera on resume
}
#Override
public void onPause() {
super.onPause();
mScannerView.stopCamera(); // Stop camera on pause
}
#Override
public void handleResult(Result rawResult) {
// Do something with the result here
// Log.v("tag", rawResult.getText()); // Prints scan results
// Log.v("tag", rawResult.getBarcodeFormat().toString()); // Prints the scan format (qrcode, pdf417 etc.)
MainActivity.tvresult.setText(rawResult.getText());
onBackPressed();
// If you would like to resume scanning, call this method below:
//mScannerView.resumeCameraPreview(this);
}
}
How could I achieve that??
Just save the result of the rawResult.getText() method to preferences or SQLite Database

Using NumberPicker to change TextView on a different activity [android]

I'm trying to change a textview value on one activity by using a numberpicker on the previous activity. Any help would be appreciated.
Here's the relevant part of my Java from activity1
public class activity_game extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
final NumberPicker fizzNumberPkr = (NumberPicker)findViewById(fizzNumberPicker);
fizzNumberPkr.setValue(3);
fizzNumberPkr.setMinValue(1);
fizzNumberPkr.setMaxValue(20);
fizzNumberPkr.setWrapSelectorWheel(true);
final NumberPicker buzzNumberPkr = (NumberPicker)findViewById(buzzNumberPicker);
buzzNumberPkr.setValue(5);
buzzNumberPkr.setMinValue(1);
buzzNumberPkr.setMaxValue(20);
buzzNumberPkr.setWrapSelectorWheel(true);
}
public void toActivityPlay (View view) {
Intent toActivityPlay = new Intent(this, activity_play.class);
toActivityPlay.putExtra("fizzNumber", fizzNumber);
toActivityPlay.putExtra("buzzNumber", buzzNumber);
startActivity(toActivityPlay);
}
And my relevant java from activity2
public class activity_play extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
TextView fizzNumberText = (TextView)findViewById(R.id.fizzNumber);
fizzNumberText.setText(getIntent().getExtras().getString("fizzNumber"));
if(getIntent().hasExtra("fizzNumber")) {
fizzNumber = getIntent().getIntArrayExtra();
} else {
throw new IllegalArgumentException("Error: Fizz number not found");
}
If there's any relevant code that I may not have posted please let me know and i'll edit my post.
Some ideas come to me now to communicate two activities..
You can create a method setValuePicker()/getValueFromPicker() in the first Activity, and call getValue() in the other activity.
public void setValuePicker(Parameter value){
number = value;
}
public Parameter getValuePicker(){
return value;
}
If you variable have been set global only need implement getValue() method.
If you someday want use fragments need implement callback.
EDIT:
Using your code is something like this:
- FirstActivity
public class MainActivity extends AppCompatActivity {
private int number;
public static final String FIZZ_TAG = "fizz_numer";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final NumberPicker picker = (NumberPicker) findViewById(R.id.numberPicker);
picker.setMinValue(0);
picker.setMaxValue(10);
picker.setValue(5);
picker.setWrapSelectorWheel(true);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
number = picker.getValue();
Intent intent = new Intent(getApplicationContext(), Main2Activity.class)
.putExtra(FIZZ_TAG,number);
startActivity(intent);
}
});
}
}
Second Activity need be something like this.
.
.
.
.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
int s = getIntent().getIntExtra(MainActivity.FIZZ_TAG,0);
TextView textView = (TextView) findViewById(R.id.text_test);
textView.setText(String.format("%s = %d","number ",s));
}

App crashes when using Shared Preferences

Im making a simple app, which counts the clicks of a button and saves the integer with a Shared Preferences. I tried it with the following code, but the app crashes all the time, if I try to open "Singleplayer"
public class Singleplayer extends AppCompatActivity {
private int sp1;
private int record;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_singleplayer);
final Button button1 = (Button) findViewById(R.id.buttonspieler1);
final TextView lbl1 = (TextView)findViewById(R.id.lblspieler1);
final TextView lbl2 = (TextView)findViewById(R.id.lblrekord);
SharedPreferences data_record = getSharedPreferences("savegame", 0);
record = data_record.getInt("myKey1", 0);
lbl2.setText(String.valueOf(record));
button1.setOnClickListener(new View.OnClickListener()
{
public void onClick(final View v)
{
if(sp1< record) {
sp1++;
lbl1.setText(String.valueOf(sp1));
}
else if(sp1>= record)
{
sp1++;
record++;
lbl1.setText(String.valueOf(sp1));
lbl2.setText(String.valueOf(record));
}
}
});
}
#Override
protected void onStop() {
super.onStop();
SharedPreferences data_record = getSharedPreferences("savegame", 0);
SharedPreferences.Editor editor = data_record.edit();
editor.putString("myKey1", String.valueOf(record));
editor.commit();
}
}
you are using sharedPrefrence in your onStop() so you will face many issue here, i suggest to use it at the end of click method
button1.setOnClickListener(new View.OnClickListener()
{
public void onClick(final View v)
{
if(sp1< record) {
sp1++;
lbl1.setText(String.valueOf(sp1));
}
else if(sp1>= record)
{
sp1++;
record++;
lbl1.setText(String.valueOf(sp1));
lbl2.setText(String.valueOf(record));
}
SharedPreferences data_record = getSharedPreferences("savegame", 0);
SharedPreferences.Editor editor = data_record.edit();
editor.putString("myKey1", String.valueOf(record));
editor.commit();
}
});
so why the app crash, because the sharedPref dosen't carry any value it's null
please check this

How to stop PhoneStateListener when I change the activity

I define a PhoneStateListener in an activity and I want to stop the listener when a I change the activity. I have tried to do it with this code, but it doesn't work.
public class OriginActivity extends AppCompatActivity{
private TelephonyManager tManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_origin);
tManager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
tManager.listen(new CustomPhoneStateListener(this), PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
}
protected void onPause() {
super.onPause();
// Logs 'app deactivate' App Event.
AppEventsLogger.deactivateApp(this);
tManager.listen(new CustomPhoneStateListener(this), PhoneStateListener.LISTEN_NONE);
}
}
What am I doing wrong?
I have found a solution!!!
public class OriginActivity extends AppCompatActivity{
CustomPhoneStateListener customPhoneStateListener;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_origin);
/**** Other Code ****/
}
protected void onResume() {
super.onResume();
//Here, we start the listener!!!
TelephonyManager tManager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
customPhoneStateListener = new CustomPhoneStateListener(this);
tManager.listen(customPhoneStateListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
Log.d(TAG, "onResume");
}
protected void onPause() {
super.onPause();
//Here, we stop the listener!!!
TelephonyManager tManager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
tManager.listen(customPhoneStateListener, PhoneStateListener.LISTEN_NONE);
customPhoneStateListener = null;
}
}
Therefore, when we access to the Activity for the first time or back from another activity we call onResume() and we start the listener. And, when we exit the Activity with onPause() we stop the listener.
Can be done when the service is stopped for some reason (say user click a stop button)
#Override
public void onDestroy() {
super.onDestroy();
telephonyManager.listen(listener, PhoneStateListener.LISTEN_NONE);
listener = null;
}

listener sharedpreferences

I've a problem with this code. I want keep preferences values in my app but I've problem with the listener. Does not work, its does not save new values. Any idea about error(s)?
EDIT: onResume() works because when I open an activity on my app and close it, the value of sharepreferences is correct. Dialogs and activities does not keep values.
public void onCreate(){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String listpref) {
if(!preferencesChanged)preferenze();
}
};
sp.registerOnSharedPreferenceChangeListener(listener);
There are some buttons and other info activities called by intents.
A TextView that show a value from array and nothing.
public void onPause() {
super.onPause();
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
sp.unregisterOnSharedPreferenceChangeListener(listener);
protected void onResume() {
super.onResume();
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String listpref) {
preferencesChanged = true;
}
};
sp.registerOnSharedPreferenceChangeListener(listener);
protected void onStop(){
super.onStop();
if(preferencesChanged){
//Update the app
preferenze();
}
public void preferenze()
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
CheckboxPreference = prefs.getBoolean("checkboxPref", true);
ListPreference = prefs.getString("listpref", "");
Others variables and most if/else.
Preferences.xml:
public class Preferences extends PreferenceActivity implements OnSharedPreferenceChangeListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.preferences);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences prefs, String listpref) {
protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.settings); SharedPreferences sp = PreferenceManager .getDefaultSharedPreferences(this); sp.registerOnSharedPreferenceChangeListener(this); }
I think, you are missing registerOnSharedPreferenceChangeListener

Categories

Resources