Location returning null for longitude and latitude - nullpointerexception

I am trying to get the latitude and longitude of the current online user and store it in a firebase database but it keeps returning null. I tried to log the longitude and latitude in logcat, it's not showing anything because I applied a null check to it but if I removed the null check, it returns an error that I am referencing a double location.getLatitude in a null object reference. I don't know what I did wrong. Here is the code
public class VendorMapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
com.google.android.gms.location.LocationListener {
private GoogleMap mMap;
private GoogleApiClient googleApiClient;
private Location lastLocation;
private LocationRequest locationRequest;
public static final int PERMISSION_FINE_LOCATION = 99;
private LatLng vendorLocationLatLng;
Marker customerDeliveredLocationMarker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
setContentView(R.layout.activity_vendor_maps);
mAuth = FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
vendorId = mAuth.getCurrentUser().getUid();
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
checkLocationPermission();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
buildGoogleApiClient();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
}
#Override
public void onConnected(#Nullable Bundle bundle) {
//update the location after one one second
locationRequest = new LocationRequest();
locationRequest.setInterval(1000);
locationRequest.setFastestInterval(1000);
locationRequest.setPriority(locationRequest.PRIORITY_HIGH_ACCURACY);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
if (lastLocation !=null){
lastLocation = location;
Log.d("TAG","latitude is "+lastLocation.getLatitude());
Log.d("TAG","longitude is "+lastLocation.getLongitude());
if (getApplicationContext() !=null){
try {
lastLocation = location;
LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(18));
//store the location of the current online vendor by using geofire to get the longitude and latitude of the vendor
String onlineVendorId = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference vendorAvailabilityRef = FirebaseDatabase.getInstance().getReference().child("Vendors Available");
GeoFire geoFireVendorAvailable = new GeoFire(vendorAvailabilityRef);
vendorWorkingRef = FirebaseDatabase.getInstance().getReference().child("Vendors Working");
GeoFire geoFireVendorWorking = new GeoFire(vendorWorkingRef);
switch (customerId){
case "":
geoFireVendorWorking.removeLocation(onlineVendorId, new GeoFire.CompletionListener() {
#Override
public void onComplete(String key, DatabaseError error) {
}
});
geoFireVendorAvailable.setLocation(vendorId, new GeoLocation(location.getLatitude(), location.getLongitude()), new GeoFire.CompletionListener() {
#Override
public void onComplete(String key, DatabaseError error) {
}
});
break;
default:
geoFireVendorAvailable.removeLocation(onlineVendorId, new GeoFire.CompletionListener() {
#Override
public void onComplete(String key, DatabaseError error) {
}
});
geoFireVendorWorking.setLocation(onlineVendorId, new GeoLocation(location.getLatitude(), location.getLongitude()), new GeoFire.CompletionListener() {
#Override
public void onComplete(String key, DatabaseError error) {
}
});
}
}catch (Exception ignored){}
}
}
}
protected synchronized void buildGoogleApiClient(){
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
if (!currentVendorLogoutStatus){
disconnectTheVendor();
}
}

Related

Set RecyclerView itemTextView programmatically to BOLD based on Volley JSON response?

I populate a RecyclerView from JSON data pulled from a webserver using Volley. I have two columns called user1Read and user2Read that is yes or no. I would like to know how I can modify my Adapter to set the TypeFace to bold if the message is considered "unread"? I am unsure of how to access the TextView from within my onResponse logic. Should I create a member variable in my Messages model class? Should I create it in my Adapter? Where would be the best place to put this? In my JSON onResponse, it would be great if I could just say
onResponseMethod {
if(!hasRead) {
//set TypeFace BOLD here
//But how to access TextView???
}
}
My custom Adapter:
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import de.hdodenhof.circleimageview.CircleImageView;
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.ViewHolder> implements Filterable {
private ArrayList<Message> messages;
private OnItemClickListener mListener;
#Override
public Filter getFilter() {
return null;
}
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
public MessageAdapter(ArrayList<Message> messages) {
this.messages = messages;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.message_list_item, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Message message = messages.get(position);
holder.username.setText(message.getUsername());
holder.messageSnippet.setText(message.getMessageSnippet());
holder.singleMessageTimestamp.setText(message.getTimestamp());
Picasso.get().load(message.getAvatarUrl()).into(holder.avatarCircleImageView);
}
#Override
public int getItemCount() {
if (messages != null) {
return messages.size();
} else {
return 0;
}
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View view;
public final TextView username;
public final TextView messageSnippet;
public final TextView singleMessageTimestamp;
public final CircleImageView avatarCircleImageView;
public ViewHolder(View view) {
super(view);
this.view = view;
username = view.findViewById(R.id.message_item_username_textview);
messageSnippet = view.findViewById(R.id.message_item_message_snippet_textview);
singleMessageTimestamp = view.findViewById(R.id.message_item_timestamp);
avatarCircleImageView = view.findViewById(R.id.message_item_circle_avatar);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
});
}
}
}
My Message Model:
import android.widget.ImageView;
public class Message {
private String username;
private String messageSnippet;
private String avatarUrl;
private String timestamp;
private ImageView dot;
public Message(String username, String message, String avatar, String timestamp) {
this.username = username;
this.messageSnippet = message;
this.avatarUrl = avatar;
this.timestamp = timestamp;
}
public Message(String username, String avatar) {
this.username = username;
this.avatarUrl = avatar;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getMessageSnippet() {
return messageSnippet;
}
public void setMessageSnippet(String messageSnippet) {
this.messageSnippet = messageSnippet;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public String getAvatarUrl() {
return avatarUrl;
}
public void setAvatarUrl(String avatarUrl) {
this.avatarUrl = avatarUrl;
}
}
My main Activity (MessagesActivity).
public class MessagesActivity extends AppCompatActivity implements MessageAdapter.OnItemClickListener {
private RecyclerView messages;
private MessageAdapter adapter;
private ImageView circle_avatar;
private TextView header_username_text;
private ImageView avatar;
private TextView username_heading;
private static JSONArray profile_array;
private static final String TAG = "MessagesActivity";
private static final String getMessagesUrl = "https://myURL.com/get_messages.php";
private static String username;
private static ProgressDialog messagesProgressDialog;
private static ArrayList<Message> list = new ArrayList<>();
private static JSONObject jsonObject;
private static Timer updateTimer;
private static String hasRead;
private static RecyclerView.LayoutManager mLayoutManager;
private DrawerLayout mDrawerLayout;
private ImageButton composeImageButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_messages);
configureNavigationDrawer();
configureToolbar();
if(list != null) {
list.clear();
}
avatar = findViewById(R.id.profile_avatar);
username_heading = findViewById(R.id.username_text);
updateTimer = new Timer();
TimerTask updateTimerTask = new TimerTask() {
public void run() {
refreshMessages();
}
};
updateTimer.scheduleAtFixedRate(updateTimerTask, 3000, 3000);
messagesProgressDialog = new ProgressDialog(MessagesActivity.this, R.style.Custom_Progress_Dialog);
messagesProgressDialog.setIndeterminate(true);
messagesProgressDialog.setMessage("Fetching Messages...");
messagesProgressDialog.show();
SharedPreferences sharedPreferences = this.getSharedPreferences("MyPref", MODE_PRIVATE);
username = sharedPreferences.getString("username", null);
getProfile(username);
messages = findViewById(R.id.messages);
messages.addItemDecoration(new DividerItemDecoration(this, LinearLayout.VERTICAL));
ArrayList<Message> messages = initMessages();
mLayoutManager = new LinearLayoutManager(this);
this.messages.setLayoutManager(mLayoutManager);
adapter = new MessageAdapter(messages);
this.messages.setAdapter(adapter);
adapter.setOnItemClickListener(this);
getProfile(username);
composeImageButton = findViewById(R.id.custom_toolbar_image_button);
composeImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "Clicked compose Image Button");
Intent composeIntent = new Intent(MessagesActivity.this, ComposeActivity.class);
startActivity(composeIntent);
updateTimer.cancel();
updateTimer.purge();
}
});
}
private ArrayList<Message> initMessages() {
RequestQueue messagesQueue = Volley.newRequestQueue(this);
StringRequest messagesRequest = new StringRequest(Request.Method.POST, getMessagesUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
messagesProgressDialog.dismiss();
try {
String baseUrl = "https://myURL.com";
String defaultbaseUrl = "https://myURL.com/css/images/user_default/default_avatar.png";
JSONObject responseObject = new JSONObject(response);
JSONArray responseArray = responseObject.getJSONArray("data");
for(int i = 0; i < responseArray.length(); i++) {
jsonObject = responseArray.getJSONObject(i);
hasRead = jsonObject.getString("has_read");
String avatar = jsonObject.getString("avatar");
String message = jsonObject.getString("message");
String sender = jsonObject.getString("sender");
String timestamp = jsonObject.getString("timestamp");
Log.d(TAG, "sender: "+sender+", hasRead: "+hasRead);
if(avatar.contains("../users")) {
String substring = avatar.substring(avatar.indexOf(".") + 2);
avatar = baseUrl+substring;
Log.d(TAG, "if(avatar.contains('../users'): "+avatar);
} else {
avatar = defaultbaseUrl;
}
list.add(new Message(sender, message, avatar, timestamp));
}
updateData();
} catch(Exception e) {
Log.d(TAG, "EXCEPTION: "+e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "VolleyError: "+error.getMessage());
messagesProgressDialog.dismiss();
}
}) {
#Override
public Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("username", username);
return params;
}
};
messagesQueue.add(messagesRequest);
return list;
}
/*
Called with TimerTask
*/
private void refreshMessages() {
RequestQueue updateQueue = Volley.newRequestQueue(this);
StringRequest updateRequest = new StringRequest(Request.Method.POST, getMessagesUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
list.clear();
try {
String baseUrl = "https://myURL.com";
String defaultbaseUrl = "https://myURL.com/css/images/user_default/default_avatar.png";
JSONObject updateObject = new JSONObject(response);
JSONArray updateResponseArray = updateObject.getJSONArray("data");
for (int i = 0; i < updateResponseArray.length(); i++) {
updateObject = updateResponseArray.getJSONObject(i);
hasRead = updateObject.getString("has_read");
String avatar = updateObject.getString("avatar");
String message = updateObject.getString("message");
String sender = updateObject.getString("sender");
String timestamp = updateObject.getString("timestamp");
if (avatar.contains("../users")) {
String substring = avatar.substring(avatar.indexOf(".") + 2);
avatar = baseUrl + substring;
} else {
avatar = defaultbaseUrl;
}
if(hasRead.equals("no")) {
}
list.add(new Message(sender, message, avatar, timestamp));
}
updateData();
adapter.notifyDataSetChanged();
} catch(Exception e) {
Log.d(TAG, "EXCEPTION: "+e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "VolleyError: "+error.getMessage());
}
}) {
#Override
public Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("username", username);
return params;
}
};
updateQueue.add(updateRequest);
}
#Override
public void onBackPressed() {
super.onBackPressed();
list.clear();
updateTimer.cancel();
updateTimer.purge();
SharedPreferences prefs = MessagesActivity.this.getSharedPreferences("MyPref", MODE_PRIVATE);
prefs.edit().putBoolean("is_logged_in", false).apply();
finish();
}
#Override
protected void onResume() {
super.onResume();
}
public void updateData() {
ArrayList<Message> strs = new ArrayList<>();
for(int i = 0; i < list.size(); i++) {
strs.add(list.get(i));
MessageAdapter updateAdapter = new MessageAdapter(list);
messages = findViewById(R.id.messages);
messages.setAdapter(updateAdapter);
updateAdapter.setOnItemClickListener(this);
}
}
#Override
public void onItemClick(int position) {
Log.d(TAG, "onItemClick Called");
Intent conversationIntent = new Intent(MessagesActivity.this, ConversationActivity.class);
String recipient = ((TextView) Objects.requireNonNull(messages.findViewHolderForAdapterPosition(position)).itemView.findViewById(R.id.message_item_username_textview)).getText().toString();
conversationIntent.putExtra("recipient", recipient);
conversationIntent.putExtra("username", username);
updateTimer.cancel();
updateTimer.purge();
startActivity(conversationIntent);
list.clear();
finish();
}
public void getProfile(final String username) {
final String username_url = "https://myURL.com/get_profile.php?username=" + username;
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest postRequest = new StringRequest(Request.Method.GET, username_url,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
String baseUrl = "https://myURL.com";
String defaultbaseUrl = "https://myURL.com/css/images/user_default/default_avatar.png";
try {
profile_array = new JSONArray(response);
for(int i = 0; i < profile_array.length(); i++) {
Log.d(TAG, "getProfile inside for loop");
JSONObject jsonObject = profile_array.getJSONObject(i);
String name = jsonObject.getString("name");
String avatarString = jsonObject.getString("avatar");
Log.d(TAG, "getProfile avatarString: "+avatarString);
if(avatarString.contains("../users")) {
String substring = avatarString.substring(avatarString.indexOf(".") + 2);
Log.d(TAG, "substring: "+substring);
String urlString = baseUrl +substring;
Picasso.get().load(urlString).into(circle_avatar);
Log.d(TAG, "urlString: "+urlString);
//Log.d(TAG, "CircleImageView getDrawable(): "+avatar.getDrawable());
header_username_text.setText(name);
} else {
Picasso.get().load(defaultbaseUrl).into(circle_avatar);
header_username_text.setText(name);
}
}
} catch (JSONException e) {
ToastMaker.createLongToast(getApplicationContext(), "JSONException getProfile: "+ e.getMessage());
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d(TAG, "VolleyError: "+error.getMessage());
//Toast.makeText(getApplicationContext(), TAG + " " + error, Toast.LENGTH_LONG).show();
}
}
) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
return params;
}
};
queue.add(postRequest);
}
public void showLogoutDialog() {
AlertDialog.Builder logoutBuilder = new AlertDialog.Builder(this, R.style.Custom_Alert_Dialog);
logoutBuilder.setIcon(R.mipmap.ic_launcher_foreground);
logoutBuilder.setTitle("Confirm Logout");
logoutBuilder.setMessage("You are about to logout.\nAre you sure?")
.setCancelable(true)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
SharedPreferences prefs = MessagesActivity.this.getSharedPreferences("MyPref", MODE_PRIVATE);
prefs.edit().putBoolean("is_logged_in", false).apply();
Intent logoutIntent = new Intent(MessagesActivity.this, LoginActivity.class);
startActivity(logoutIntent);
finish();
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alertDialog = logoutBuilder.create();
alertDialog.show();
}
private void configureNavigationDrawer() {
mDrawerLayout = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.navigation_view);
circle_avatar = navigationView.getHeaderView(0).findViewById(R.id.profile_circle_avatar);
header_username_text = navigationView.getHeaderView(0).findViewById(R.id.header_username_text);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.edit_profile:
//String name = username_heading.getText().toString();
//String pic = avatar.getDrawable().toString();
//String location = location_heading.getText().toString();
//String interests = interests_heading.getText().toString();
//editProfile(name, pic, location, interests);
Log.d(TAG, "Clicked Edit Profile");
break;
case R.id.messages:
Log.d(TAG, "Clicked Messages");
mDrawerLayout.closeDrawers();
break;
case R.id.privacy:
Intent privacyIntent = new Intent(MessagesActivity.this, PrivacyActivity.class);
startActivity(privacyIntent);
Log.d(TAG, "Clicked Privacy");
break;
case R.id.logout:
showLogoutDialog();
Log.d(TAG, "Clicked Logout Button");
break;
}
mDrawerLayout.closeDrawers();
return false;
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
switch(itemId) {
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
}
return true;
}
private void configureToolbar() {
Toolbar toolbar = findViewById(R.id.custom_toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
assert actionBar != null : Log.d(TAG, "actionBar is NULL");
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setHomeAsUpIndicator(R.drawable.ic_action_menu_24dp);
actionBar.setDisplayHomeAsUpEnabled(true);
}
#Override
protected void onRestart() {
super.onRestart();
updateTimer = new Timer();
TimerTask updateTimerTask = new TimerTask() {
public void run() {
refreshMessages();
}
};
updateTimer.scheduleAtFixedRate(updateTimerTask, 3000, 3000);
}
}
Here is the array that is being sent from the webserver:
$data[] = array('has_read' => 'no', 'avatar' => $avatar, 'sender' => $sender, 'recipient' => $recipient, 'message' => $message, 'timestamp' => $time);
$response = array('data'=>$data, 'count'=>$count);
echo json_encode($response);
If you need only one Boolean throughout your app, here is a way to access the Boolean value:
Create a separate file named ext for example and inside, make this interface:
public interface ext {
Boolean hasRead = false;
}
This variable is made when the app runs and lives for as long as the app does. so you can change it whenever you want.
If you want to have 2 separate Booleans for the two users chatting you can use a Hashmap like so:
HashMap <String, Boolean> readStatus = new HashMap<>();
Update 2
Guess what? It was a typo in another php function not mentioned in my question called getConversation(). I stopped working on the file a while back to perfect my MessagesActivity. I logged any Exceptions on the Activity, and noticed Exception in getMessages(): No value for timestamp.
I had misspelled my timestamp variable. Lol. So, I have a fully functioning messaging system now! :-) Now to work on some notification bells and whistles. Have a great weekend.
Update: This is not completely solved. It's
bold when it's initially received on the MessagesActivity screen, but it goes back to regular Typeface once they refresh (via the TimerTask). Will debug for a while and come back, unless one of you discovers it first. :)
I think I figured it out!
My table is like so:
user1, user1ID, user2, user2ID, message, timestamp, user1read, user2read
When I make my request for a message, I receive these items via the php script:
if($sender === $username) {
$data[] = array('has_read'=>$user1read, 'avatar'=>$avatar, 'sender'=>$recipient, 'message'=>'You: '.$message, 'timestamp'=>$time);
} else {
$data[] = array('has_read' => $user2read, 'avatar' => $avatar, 'sender' => $sender, 'recipient' => $recipient, 'message' => $message, 'timestamp' => $time);
}
This was my original loop to get all the messages from my JSONObject:
for (int i = 0; i < updateResponseArray.length(); i++) {
updateObject = updateResponseArray.getJSONObject(i);
String hasRead = updateObject.getString("has_read");
String avatar = updateObject.getString("avatar");
String message = updateObject.getString("message");
String sender = updateObject.getString("sender");
String timestamp = updateObject.getString("timestamp");
if (avatar.contains("../users")) {
String substring = avatar.substring(avatar.indexOf(".") + 2);
avatar = baseUrl + substring;
} else {
avatar = defaultbaseUrl;
}
list.add(new Message(sender, message, avatar, timestamp));
So, I thought, "why don't I just create another member variable for my Messages model, and call it "hasRead"? So I did just that:
public class Message {
private String username;
private String messageSnippet;
private String avatarUrl;
private String timestamp;
private String hasRead; //<--- here we go
Then I make my getters and setters (leaving out for the sake of brevity).
#J7bits suggested I access the onBindViewHolder() in my custom Adapter class. So I did that, but I included logic to check the status of the new member variable "hasRead":
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Message message = messages.get(position);
holder.username.setText(message.getUsername());
holder.messageSnippet.setText(message.getMessageSnippet());
holder.singleMessageTimestamp.setText(message.getTimestamp());
Picasso.get().load(message.getAvatarUrl()).into(holder.avatarCircleImageView);
if(message.getHasRead().equals("no")) {
holder.messageSnippet.setTypeface(null, Typeface.BOLD_ITALIC);
}
}
Then, finally, I changed my JSON onResponse method to include the has_read variable sent from php:
String hasRead = jsonObject.getString("has_read");
And I added it to my ArrayList<Message> list:
list.add(new Message(sender, message, avatar, timestamp, **hasRead**);
I entered a new message manually into the database, and set my status to "no" for user2read. And would you just look at it?!?! :D

Signing in an account to use google play leaderboard

The following sign in code causes my game to flicker then crash after printing "bad stuff". What am I doing wrong? I tried to implement the code shown here. I attempt a silent sign in, then if that does not work I attempt an interactive sign in. I am testing an a physical Nexus 5 with the latest version of Android 8.1.0.
public class MainActivity extends Activity {
private GLSurfaceView mGLView;
private GoogleSignInAccount account;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create a GLSurfaceView instance and set it
// as the ContentView for this Activity.
mGLView = new MyGLSurfaceView(this, this);
setContentView(mGLView);
hideStatusBar();
getAccount();
}
public void hideStatusBar() {
View decorView = getWindow().getDecorView();
// Hide the status bar.
int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
// Remember that you should never show the action bar if the
// status bar is hidden, so hide that too if necessary.
//ActionBar actionBar = getActionBar();
//actionBar.hide();
}
private void getAccount() {
account = GoogleSignIn.getLastSignedInAccount(this);
if (account == null) {
signInSilently();
}
}
public void submitScore(int score) {
if (account == null) {
getAccount();
} else {
Games.getLeaderboardsClient(this, account)
.submitScore("leaderboardID", score);
}
}
private static final int leaderboardRequestCode = 9004;
private static final int signInRequestCode = 101;
public void showLeaderboard() {
if (account == null) {
getAccount();
} else {
Games.getLeaderboardsClient(this, account)
.getLeaderboardIntent("leaderboardID")
.addOnSuccessListener(new OnSuccessListener<Intent>() {
#Override
public void onSuccess(Intent intent) {
startActivityForResult(intent, leaderboardRequestCode);
}
});
}
}
//interactive sign in
private void startSignInIntent() {
GoogleSignInClient signInClient = GoogleSignIn.getClient(this,
GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN);
Intent intent = signInClient.getSignInIntent();
startActivityForResult(intent, signInRequestCode);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == signInRequestCode) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
account = result.getSignInAccount();
} else {
String message = result.getStatus().getStatusMessage();
if (message == null || message.isEmpty()) {
message = "bad stuff";
}
new AlertDialog.Builder(this).setMessage(message)
.setNeutralButton(android.R.string.ok, null).show();
}
}
}
//silent sign in
private void signInSilently() {
GoogleSignInClient signInClient = GoogleSignIn.getClient(this,
GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN);
signInClient.silentSignIn().addOnCompleteListener(this,
new OnCompleteListener<GoogleSignInAccount>() {
#Override
public void onComplete(#NonNull Task<GoogleSignInAccount> task) {
if (task.isSuccessful()) {
account = task.getResult();
} else {
startSignInIntent();
}
}
});
}
#Override
protected void onResume() {
super.onResume();
signInSilently();
}
}

Restore scroll position

I have a simple fragment which retrieve data from Firebase database.
I use firebase recycler view to display retrieving data. And after scrolling or screen rotation I can't force recycler view (or linear layout manager) restore scroll position.
I found here some answers but they don't work.
My code is:
public class NewsListFragment extends ParentNewsFragment {
static int color_naval, color_black;
private boolean mProcessLikes = false;
private DatabaseReference mDatabaseLikes;
private DatabaseReference mDatabaseViews;
private FirebaseAuth mAuth;
private int position = 0;
public static NewsListFragment getInstance() {
return new NewsListFragment();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDatabaseReference = FirebaseDatabase.getInstance().getReference()
.child("App_news");
mDatabaseLikes = FirebaseDatabase.getInstance().getReference().child("news_likes");
mDatabaseViews = FirebaseDatabase.getInstance().getReference().child("news_views");
mAuth = FirebaseAuth.getInstance();
mQuery = mDatabaseReference.orderByChild("pos").startAt("100");
color_naval = getResources().getColor(R.color.colorPrimary);
color_black = getResources().getColor(R.color.colorBlack);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.rv_choose, container, false);
rv = (RecyclerView) rootView.findViewById(R.id.rv_choose);
lm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(lm);
rv.setHasFixedSize(true);
return rootView;
}
#Override
public void onPause() {
super.onPause();
position = lm.findFirstVisibleItemPosition();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("position", position);
}
#Override
public void onViewStateRestored(#Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
if(savedInstanceState != null) {
position = savedInstanceState.getInt("position");
}
}
#Override
public void onResume() {
super.onResume();
if (position != 0) {
lm.scrollToPosition(position);
showToast(position+"");
}
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerAdapter<NewsList, NewsListViewHolder> adapter =
new FirebaseRecyclerAdapter<NewsList, NewsListViewHolder>(
NewsList.class,
R.layout.frag_newslist_card_view,
NewsListViewHolder.class,
mQuery
) {
#Override
protected void populateViewHolder(NewsListViewHolder viewHolder, final NewsList model, int position) {
final String post_key = getRef(position).getKey();
viewHolder.setDate(model.getDate()+",");
viewHolder.setTime(model.getTime());
viewHolder.setTitle(model.getTitle());
viewHolder.setImage(getContext(), model.getImage());
viewHolder.setEye(model.getCode());
viewHolder.setThumb(post_key);
viewHolder.thumb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mProcessLikes = true;
mDatabaseLikes.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (mProcessLikes){
if (dataSnapshot.child(post_key).hasChild(mAuth.getCurrentUser().getUid())){
mDatabaseLikes.child(post_key).child(mAuth.getCurrentUser().getUid())
.removeValue();
mProcessLikes = false;
}
else {
mDatabaseLikes.child(post_key).child(mAuth.getCurrentUser().getUid())
.setValue("like");
mProcessLikes = false;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDatabaseViews.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.child(post_key).hasChild(mAuth.getCurrentUser().getUid())) {
mDatabaseViews.child(post_key).child(mAuth.getCurrentUser().getUid())
.setValue("view");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mChooserListener.chooseNews(model.getCode());
}
});
}
};
rv.setAdapter(adapter);
}
public static class NewsListViewHolder extends RecyclerView.ViewHolder {
//some text here
}
}
method showToast in the end shows real number of position but recyclerview starts from the beginning.
any ideas?
Make sure you are not reloading data from the server or wherever you are retrieving data.
Add is not null check in your fragment's onCreateView or activity's onCreate like:
if(savedInstanceState != null){
...
}else{
loadData();
}
Replace your linear layout manager with something similar to the following. I have used this implementation many times when using RecyclerView in fragments. Let me know how it goes
LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
mLayoutManager.setReverseLayout(true);
mLayoutManager.setStackFromEnd(true);
yourItem.setLayoutManager(mLayoutManager);

Not getting callback from google api, android?

I have connected to google api for loaction in android. but i not getting any callback from google api. not getting location.
my code is
public class SplashScreen extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
public static int SPLASH_TIME_OUT = 3000;
private final String LOG_TAG = "logTagMngr";
private TextView loactionout;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private LocationManager locationManager;
SharedPreferences sharedPref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
sharedPref = getApplicationContext().getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
loactionout = (TextView) findViewById(R.id.loactionout);
}
#Override
protected void onResume() {
super.onResume();
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Turn on location?")
.setCancelable(false)
.setPositiveButton("Turn on Location", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
openWifiSettings();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
} else {
googleApiClient.connect();
}
}
#Override
protected void onStop() {
super.onStop();
if (googleApiClient.isConnected()) {
googleApiClient.disconnect();
}
}
public void openWifiSettings() {
Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(500);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
Log.i(LOG_TAG,"Failed");
}
#Override
public void onLocationChanged(Location location) {
Log.i("AAA",location.toString());
loactionout.setText(location.getLatitude()+"");
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("userLongitude",location.getLongitude()+"");
editor.putString("userLatitude",location.getLatitude()+"");
if(editor.commit()){
Intent i = new Intent(SplashScreen.this, MainActivity.class);
startActivity(i);
finish();
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.i(LOG_TAG,"Failed");
}
}
i dont know the problem. not getting connection failed on suspended callbacks also. please help me.

calling alarm from a service

I designed my service as it will make an alarm when user will go to a certain location.
But it crashes when it go to the certain making the alarm.
public class CheckDestinationService extends Service {
Calendar calender;
double late,longe;
int dis;
String loc;
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 0;
private static final float LOCATION_DISTANCE = 0;
private class LocationListener implements android.location.LocationListener {
Location mLastLocation;
public LocationListener(String provider) {
mLastLocation = new Location(provider);
}
public void onLocationChanged(Location location) {
mLastLocation.set(location);
final double currlat;
final double currlong;
float[] DistanceArray = new float[1];
currlat = location.getLatitude();
currlong = location.getLongitude();
android.location.Location.distanceBetween(currlat,currlong,late,longe,DistanceArray);
float Distance = DistanceArray[0];
//Toast.makeText(getApplicationContext(), "asdf "+String.valueOf(Distance), Toast.LENGTH_SHORT).show();
Log.d("asdfasdas", String.valueOf(currlat)+","+String.valueOf(currlong)+" "+String.valueOf(Distance));
if (Distance<=dis && Distance!=0 && dis!=0)
{
dis = 0;
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Toast.makeText(getApplicationContext(), "Reached "+String.valueOf(Distance), Toast.LENGTH_SHORT).show();
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(),0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = (AlarmManager)getSystemService(Activity.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, calender.getTimeInMillis(),pendingIntent);
//stopSelf();
}
/*final Handler handler = new Handler();
Runnable r = new Runnable() {
public void run() {
// TODO Auto-generated method stub
Intent intent = null;
intent.putExtra("lat", currlat);
intent.putExtra("long", currlong);
intent.putExtra("dis", dis);
intent.putExtra("loc", loc);
Toast.makeText(getApplicationContext(), "Sending", Toast.LENGTH_SHORT).show();
sendBroadcast(intent);
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(r, 1000);*/
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
LocationListener[] mLocationListeners = new LocationListener[] {
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
late = intent.getDoubleExtra("lat", 0);
longe = intent.getDoubleExtra("long", 0);
dis = intent.getIntExtra("dis", 0);
loc = intent.getStringExtra("loc");
Toast.makeText(getApplicationContext(), "Destination Set to: "+loc+
" and Minimum Distance: "+
String.valueOf(dis) , Toast.LENGTH_SHORT).show();
return START_STICKY;
}
#Override
public void onCreate() {
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
} catch (IllegalArgumentException ex) {
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
} catch (IllegalArgumentException ex) {
}
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(getApplicationContext(), "Service Destroyed", Toast.LENGTH_SHORT).show();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
}
}
}
}
private void initializeLocationManager() {
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
}
and my AlarmReceiver class is
public class AlarmReceiver extends Activity {
private MediaPlayer mMediaPlayer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.alarmreceiver);
Button stopAlarm = (Button) findViewById(R.id.stopAlarm);
stopAlarm.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View arg0, MotionEvent arg1) {
stopService(new Intent(AlarmReceiver.this, CheckDestinationService.class));
mMediaPlayer.stop();
finish();
return false;
}
});
playSound(this, getAlarmUri());
}
private void playSound(Context context, Uri alert) {
mMediaPlayer = new MediaPlayer();
try {
mMediaPlayer.setDataSource(context, alert);
final AudioManager audioManager = (AudioManager) context
.getSystemService(Context.AUDIO_SERVICE);
if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mMediaPlayer.prepare();
mMediaPlayer.start();
}
} catch (IOException e) {
System.out.println("OOPS");
}
}
//Get an alarm sound. Try for an alarm. If none set, try notification,
//Otherwise, ringtone.
private Uri getAlarmUri() {
Uri alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alert == null) {
alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if (alert == null) {
alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
}
}
return alert;
}
#Override
public void onBackPressed() {
//MainActivity.iMinDistance = 0;
stopService(new Intent(AlarmReceiver.this, CheckDestinationService.class));
mMediaPlayer.stop();
finish();
}
}
I tested AlarmReceiver class from other activites and it worked properly
but it not working from the service.
please help!!
initalize Calendar
calender = Calendar.getInstance()