Android-how to send continuous latitude and longitude to the server? - gps

I continuously get the current location, now I want to send this continuous location to the sever every 1 to 5 sec. How do I do this?
Android code:
public class MainActivity extends Activity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
TextView txtOutputLat, txtOutputLon;
Location mLastLocation;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
String lat, lon;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtOutputLat = (TextView) findViewById(R.id.textView);
txtOutputLon = (TextView) findViewById(R.id.textView2);
buildGoogleApiClient();
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(100); // Update location every second
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
lat = String.valueOf(mLastLocation.getLatitude());
lon = String.valueOf(mLastLocation.getLongitude());
}
updateUI();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
lat = String.valueOf(location.getLatitude());
lon = String.valueOf(location.getLongitude());
updateUI();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
buildGoogleApiClient();
}
synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onDestroy() {
super.onDestroy();
mGoogleApiClient.disconnect();
}
void updateUI() {
txtOutputLat.setText(lat);
txtOutputLon.setText(lon);
}
}

Related

Location returning null for longitude and latitude

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();
}
}

How to implement an Action on Item Click in Order to show the result in CardView of RecyclerView

I am very new to Android programming. I can't find a solution for my current problem which I've been trying to solve for days.
I want to click on item of populated Array List and get the position i.e. the searched word result in Cardview (neither ItemClickListener nor OnSuggestionListener did work here. Here is my code of MainActivity and I would be very thankful if somebody could help me out:
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
SearchAdapter adapter;
MaterialSearchBar materialSearchBar;
List<String> suggestList = new ArrayList<>();
Database database;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//init View
recyclerView = (RecyclerView) findViewById(R.id.recycler_search);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
materialSearchBar = (MaterialSearchBar) findViewById(R.id.search_bar);
database = new Database(this);
materialSearchBar.setHint("Search");
materialSearchBar.setCardViewElevation(10);
loadSuggestList();
materialSearchBar.addTextChangeListener (new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
List<String> suggest = new ArrayList<>();
for (String search : suggestList) {
if (search.toLowerCase().contains(materialSearchBar.getText().toLowerCase()))
suggest.add(search);
}
materialSearchBar.setLastSuggestions(suggest);
}
#Override
public void afterTextChanged(Editable s) {
}
});
materialSearchBar.setOnSearchActionListener (new MaterialSearchBar.OnSearchActionListener() {
#Override
public void onSearchStateChanged(boolean enabled) {
if (!enabled)
adapter = new SearchAdapter(getBaseContext(), database.getLughats());
recyclerView.setAdapter(adapter);
}
#Override
public void onSearchConfirmed(CharSequence text) {
startSearch(text.toString());
}
#Override
public void onButtonClicked(int buttonCode) {
}
});
adapter = new SearchAdapter(this, database.getLughats());
recyclerView.setAdapter(adapter);
}
private void startSearch(String text) {
adapter = new SearchAdapter(this, database.getLughatByWort(text));
recyclerView.setAdapter(adapter);
}
private void loadSuggestList() {
suggestList = database.getWorts();
materialSearchBar.setLastSuggestions(suggestList);
}
}```
Let me know if I should post here also my AdapterCode for the ViewHolder.
Thank you for your help in advance!
Here ist my AdapterCode:
class SearchViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
RecyclerItemClick itemClickListener;
public TextView wort, praeteritum, partizip2, artikelGrammatik, uebersetzung1, uebersetzung2;
public ImageButton button1, button2;
public SearchViewHolder(#NonNull View itemView) {
super(itemView);
wort = (TextView)itemView.findViewById(R.id.wort);
praeteritum = (TextView)itemView.findViewById(R.id.praeteritum);
partizip2 = (TextView)itemView.findViewById(R.id.partizip2);
artikelGrammatik = (TextView)itemView.findViewById(R.id.artikelGrammatik);
uebersetzung1 = (TextView)itemView.findViewById(R.id.uebersetzung1);
uebersetzung2 = (TextView)itemView.findViewById(R.id.uebersetzung2);
button1 = (ImageButton)itemView.findViewById(R.id.button_id_1);
button2 = (ImageButton) itemView.findViewById(R.id.button_id_2);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
this.itemClickListener.onItemClickListener(v, getLayoutPosition());
}
public void setItemClickListener(RecyclerItemClick ic) {
this.itemClickListener = ic;
}
}
public class SearchAdapter extends RecyclerView.Adapter<SearchViewHolder> {
private Context context;
private List<Lughat> lughats;
public SearchAdapter(Context context, List<Lughat> lughats) {
this.context = context;
this.lughats = lughats;
}
#NonNull
#Override
public SearchViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
final View itemView = inflater.inflate(R.layout.layout_item, parent, false);
return new SearchViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull final SearchViewHolder holder, final int position) {
holder.wort.setText(lughats.get(position).getWort());
holder.praeteritum.setText(lughats.get(position).getPraeteritum());
holder.partizip2.setText(lughats.get(position).getPartizip2());
holder.artikelGrammatik.setText(lughats.get(position).getArtikelGrammatik());
holder.uebersetzung1.setText(lughats.get(position).getUebersetzung1());
holder.uebersetzung2.setText(lughats.get(position).getUebersetzung2());
CharSequence praet;
praet = holder.praeteritum.getText();
if (praet.length() == 0) {
holder.praeteritum.setVisibility(View.GONE);
holder.button1.setVisibility(View.GONE);
} else {
holder.praeteritum.setVisibility(View.VISIBLE);
holder.button1.setVisibility(View.VISIBLE);
}
CharSequence part2;
part2 = holder.partizip2.getText();
if (part2.length() == 0) {
holder.partizip2.setVisibility(View.GONE);
} else {
holder.partizip2.setVisibility(View.VISIBLE);
}
CharSequence artGr;
artGr = holder.artikelGrammatik.getText();
if (artGr.length() == 0) {
holder.artikelGrammatik.setVisibility(View.GONE);
holder.button2.setVisibility(View.GONE);
} else {
holder.artikelGrammatik.setVisibility(View.VISIBLE);
holder.button2.setVisibility(View.VISIBLE);
}
CharSequence ueb2;
ueb2 = holder.uebersetzung2.getText();
if (ueb2.length() == 0) {
holder.uebersetzung2.setVisibility(View.GONE);
} else {
holder.uebersetzung2.setVisibility(View.VISIBLE);
}
holder.button1.setOnClickListener(new ToastMaker(context.getApplicationContext()));
holder.button2.setOnClickListener(new ToastMaker(context.getApplicationContext()));
holder.setItemClickListener(new RecyclerItemClick() {
#Override
public void onItemClickListener(View v, int position) {
Toast.makeText(context, "Begriff", Toast.LENGTH_LONG).show();
}
});
}
#Override
public int getItemCount() {
return lughats.size();
}
}
If I do it also with OnClickListener it does not work too, it does not call the method startSearch.
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CharSequence text = materialSearchBar.getText();
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
startSearch(text.toString());
}

how to confirm selected items in recyclerview item list and make selected on layout

i am preparing textview seat numbers list by using recyclerview grid layout manager. i can select the multiple items in the recyclerview list by red color. now i want to keep this seat item selected as red color when on cliking on confirm seat button. when i reopen the recyclerview list it should show the seat selected red color and other seat item in normal color.
confirm seat button clickconfrim seat button click
SelectionAdapter
'''
public class SelectionAdapter extends RecyclerView.Adapter<SelectionAdapter.MygridViewHolder> {
private Context applicationContext;
private ArrayList<Seatnos> list, selected;
public SelectionAdapter(Context applicationContext, ArrayList<Seatnos> list) {
this.applicationContext = applicationContext;
this.list = list;
this.selected = new ArrayList<>();
}
#NonNull
#Override
public MygridViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater=LayoutInflater.from(parent.getContext());
View view=layoutInflater.inflate(R.layout.list_layout_selection,parent,false);
return new MygridViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final MygridViewHolder holder, final int position) {
final Seatnos seatnos = list.get(position);
holder.textView.setText(String.valueOf(position));
holder.textView.setText(seatnos.getTextno());
holder.textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (selected.contains(seatnos)) {
selected.remove(seatnos);
unhighlightView(holder);
} else {
selected.add(seatnos);
highlightView(holder);
}
}
});
if (selected.contains(seatnos))
highlightView(holder);
else
unhighlightView(holder);
}
private void highlightView(MygridViewHolder holder) {
holder.itemView.setBackgroundColor(ContextCompat.getColor(applicationContext, R.color.red));
}
private void unhighlightView(MygridViewHolder holder) {
holder.itemView.setBackgroundColor(ContextCompat.getColor(applicationContext, android.R.color.transparent));
}
#Override
public int getItemCount() {
return list.size();
}
class MygridViewHolder extends RecyclerView.ViewHolder {
TextView textView;
MygridViewHolder(#NonNull View itemView) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.textViewsA);
}
}
public void addAll(ArrayList<Seatnos> list) {
clearAll(false);
this.list = list;
notifyDataSetChanged();
}
public void clearAll(boolean isNotify) {
list.clear();
selected.clear();
if (isNotify) notifyDataSetChanged();
}
public void clearSelected() {
selected.clear();
notifyDataSetChanged();
}
public void selectAll() {
selected.clear();
selected.addAll(list);
notifyDataSetChanged();
}
public ArrayList<Seatnos> getSelected() {
return selected;
}
}
'''
SeatSelectionactivity.java
'''
public class SeatSelectionActivity extends AppCompatActivity {
RecyclerView recyclerView;
Activity activity = SeatSelectionActivity.this;
Button btnGetSelected,btnreset;
FirebaseDatabase database;
DatabaseReference ref;
SelectionAdapter selectionAdapter;
ArrayList<Seatnos> list;
Update update;
ChildEventListener mChildListner;
ValueEventListener mValueEventListner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_seat_selection);
btnGetSelected = (Button) findViewById(R.id.btconfirm);
recyclerView=(RecyclerView) findViewById(R.id.viewseat);
list = new ArrayList<>();
String uid = getIntent().getStringExtra(UpdateAdapter.USER_KEY);
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("updates").child(uid);
selectionAdapter=new SelectionAdapter(this, list);
RecyclerView.LayoutManager layoutManager=new GridLayoutManager(this,4);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
mValueEventListner = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Update update =dataSnapshot.getValue(Update.class);
update.setUid(dataSnapshot.getKey());
int seat= Integer.parseInt(update.getSeat());
ArrayList<String> array = new ArrayList<String>(seat);
for(long i=0; i<seat; i++) {
array.add(String.valueOf(i));
Seatnos seatnos = new Seatnos();
seatnos.setTextno(""+(i+1));
if(i==0){
seatnos.setChecked(true);
}
list.add(seatnos);
}
recyclerView.setAdapter(selectionAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
databaseReference.addValueEventListener(mValueEventListner);
}
public void reset(View view) {
}
public void bookconfirm(View view) {
if (selectionAdapter.getSelected().size() > 0) {
//ArrayList<Integer> mlist = new ArrayList<>();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < selectionAdapter.getSelected().size(); i++) {
stringBuilder.append(selectionAdapter.getSelected().get(i).getTextno());
stringBuilder.append("\n");
}
Toast.makeText(activity, String.format("Selected %d items", selectionAdapter.getSelected().size()), Toast.LENGTH_SHORT).show();
showToast(stringBuilder.toString().trim());
} else {
showToast("No Selection");
}
};
public void selectAll(View v) {
selectionAdapter.selectAll();
}
public void deselectAll(View v) {
selectionAdapter.clearSelected();
}
public void doAction(View v) {
Toast.makeText(activity, String.format("Selected %d items", selectionAdapter.getSelected().size()), Toast.LENGTH_SHORT).show();
}
private void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
}
'''
model class
'''
public class Seatnos implements Serializable {
String textno;
String sid;
private boolean isChecked = false;
public Seatnos() {
}
public boolean isChecked() {
return isChecked;
}
public void setChecked(boolean checked) {
isChecked = checked;
}
public String getSid() {
return sid;
}
public void setSid(String sid) {
this.sid = sid;
}
public Seatnos(String textno) {
this.textno = textno;
}
public String getTextno() {
return textno;
}
public void setTextno(String textno) {
this.textno = textno;
}
}
'''
You would use shared preferences to save the state of the selected item:
Do this in onBindViewHolder:
#Override
public void onBindViewHolder(#NonNull final MygridViewHolder holder, final int position) {
final Seatnos seatnos = list.get(position);
holder.textView.setText(String.valueOf(position));
holder.textView.setText(seatnos.getTextno());
//read from preferences
SharedPreferences pref = getSharedPreferences("item", MODE_PRIVATE);
String state = pref.getString(String.valueOf(position)+"state", "default");
if(state.equals("selected")){
//selected
highlightView(holder);
}else{
//not selected
unhighlightView(holder);
}
//on click
holder.textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (selected.contains(seatnos)) {
selected.remove(seatnos);
unhighlightView(holder);
//save state
SharedPreferences.Editor editor = getSharedPreferences("item", MODE_PRIVATE).edit();
editor.putString(String.valueOf(position)+"state", "not_selected");
editor.apply();
} else {
selected.add(seatnos);
highlightView(holder);
//save state
SharedPreferences.Editor editor = getSharedPreferences("item", MODE_PRIVATE).edit();
editor.putString(String.valueOf(position)+"state", "selected");
editor.apply();
}
}
});
......................
......................
......................
}
UPDATE:
Yes you should use the context passed to your adapter to access the shared prederences:
This:
getSharedPreferences("item", MODE_PRIVATE);
Becomes:
applicationContext.getSharedPreferences("item", MODE_PRIVATE);
This:
getSharedPreferences("item", MODE_PRIVATE).edit();
Becomes:
applicationContext.getSharedPreferences("item", MODE_PRIVATE).edit();

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.