JMB
JMB

Reputation: 313

Have to close and relaunch app for correct location to be shown on map

When retrieving the post's location (Latitude and Longitude) from Firebase, the correct location is retrieved and the marker is placed in the correct spot only after stopping the app and relaunching it. Otherwise, I get the location of some other post...

Anyone can explain to me why that happens? So if I upload a new post and then try to open its location it won't give me back the correct location unless I stop the app and re-enter. If I do everything from one go it gives me the location of another post.

I'm thinking it's a problem I have with my Adapter because when I pull up the post from my ProfileFragment it gives me back the correct location always.

The way that I am transferring the postid from my PostAdapter.java class to my MapsActivityUser.class is by using Intent, so the correct post can be found in Firebase. How can I fix this issue, and more importantly why is it happening?

PostAdapter.java

public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {

    public Context mContext;
    public List<Post> mPost;

    public Post post;

    public PostAdapter(Context mContext, List<Post> mPost) {
        this.mContext = mContext;
        this.mPost = mPost;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.post_item, parent, false);
        return new PostAdapter.ViewHolder(view);

    }

 @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {

        firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
        post = mPost.get(position);

        Glide.with(mContext).load(post.getPostimage())
                .apply(new RequestOptions().placeholder(R.drawable.placeholderimg))
                .into(holder.post_image);

 if ("".equals(post.getText_location())) {
            holder.text_location.setVisibility(View.GONE);
        } else {
            holder.text_location.setVisibility(View.VISIBLE);
            holder.text_location.setText(post.getText_location());

 public class ViewHolder extends RecyclerView.ViewHolder {

public TextView text_location;

 public ViewHolder(@NonNull View itemView) {
            super(itemView);

 text_location = itemView.findViewById(R.id.text_location);

text_location.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, MapsActivityUser.class);
                    intent.putExtra("postid", post.getPostid());
                    mContext.startActivity(intent);
                }
            });
        }
    }
        }

MapsActivityUser.java

public class MapsActivityUser extends FragmentActivity implements OnMapReadyCallback {

    String postid;
    private GoogleMap map;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps_user);

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        postid = getIntent().getStringExtra("postid");
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        map = googleMap;

        final DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts").child(postid);
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                Post post = dataSnapshot.getValue(Post.class);
                if (post != null) {
                    double latitude = post.getLocation().getLatitude();
                    double longitude = post.getLocation().getLongitude();

                    LatLng location = new LatLng(latitude, longitude);
                    map.addMarker(new MarkerOptions().position(location).title("Event location"));
                    map.moveCamera(CameraUpdateFactory.newLatLngZoom(location, 10));
                } else {
                    Toast.makeText(MapsActivityUser.this, "Event doesn't have location on map", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }
}

MapsActivityuser.java updated code with RecyclerView

public class MapsActivityUser extends FragmentActivity implements OnMapReadyCallback {

    String postid;
    private GoogleMap map;
    private RecyclerView mRecyclerView;
    private PostAdapter mPostAdapter;
    private List<Post> mPostList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps_user);

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        postid = getIntent().getStringExtra("postid");

        mRecyclerView = findViewById(R.id.recycler_view);
        mRecyclerView.setHasFixedSize(true);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mPostList = new ArrayList<>();
        mPostAdapter = new PostAdapter(this, mPostList, postid);
        mRecyclerView.setAdapter(mPostAdapter);

    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        map = googleMap;

        final DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts").child(postid).child("location");
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                double latitude = dataSnapshot.child("latitude").getValue(Double.class);
                double longitude = dataSnapshot.child("longitude").getValue(Double.class);

                LatLng location = new LatLng(latitude, longitude);
                map.addMarker(new MarkerOptions().position(location).title("Event location"));
                map.moveCamera(CameraUpdateFactory.newLatLngZoom(location, 10));
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }

    @Override
    public void onPostClick(int position) {
      //
    }
}

Upvotes: 1

Views: 56

Answers (1)

some user
some user

Reputation: 1775

Your approach is so wrong. Think about what's happening under the hood. Each time your adapter's onBindViewHolder() method is called and post = mPost.get(position); is executed that is the post is updated at each call. That's why yo're not getting correct post ids. You probably don't want to set the post to the last and only value updated by the call of onBindViewHolder() each time.

I assume what you want is some sort of text_field to display the location of your posts, depending on which is clicked.

Your position variable is really messed up and that is not the correct position, instead you should use getAdapterPosition().

Upvotes: 1

Related Questions