How to setInfoWindowAdapter for particular markers only - java

I'm trying to use the 'setInfoWindowAdapter' propery within my map view for a particular marker, but with 'Marker 2' there appears to be some unwanted space appearing underneath the title for some reason (Marker 2) (see attached screenshots). What can be done in order to prevent this from happening?
FragmentCustomMapview.java
public class FragmentCustomMapview extends android.support.v4.app.Fragment implements OnMapReadyCallback {
public FragmentCustomMapview() {
// Required empty constructor
}
GoogleMap mGoogleMap;
MapView mMapView;
SwitchCompat swt;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_custommapview, container, false);
mMapView = (MapView) v.findViewById(R.id.map_custommapview);
mMapView.onCreate(savedInstanceState);
mMapView.getMapAsync(this); //this is important
swt = (SwitchCompat) v.findViewById(R.id.switch_map_custommapview);
return v;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mGoogleMap.setBuildingsEnabled(true);
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
swt.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
initMap(isChecked);
}
});
initMap(swt.isChecked());
// Add markers and move the camera
LatLng marker1 = new LatLng(51.510256, -0.135106);
mGoogleMap.addMarker(new MarkerOptions()
.position(marker1)
.title("Lorem ipsum dolor")
.snippet("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.")
);
LatLng marker2 = new LatLng(51.509793, -0.134961);
mGoogleMap.addMarker(new MarkerOptions()
.position(marker2)
.title("Marker 2")
);
mGoogleMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker arg0) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
Context mContext = getActivity();
LinearLayout info = new LinearLayout(mContext);
info.setOrientation(LinearLayout.VERTICAL);
TextView title = new TextView(mContext);
title.setTextColor(Color.BLACK);
title.setGravity(Gravity.CENTER);
title.setTypeface(null, Typeface.BOLD);
title.setText(marker.getTitle());
title.setSingleLine(false);
TextView snippet = new TextView(mContext);
snippet.setTextColor(Color.GRAY);
snippet.setText(marker.getSnippet());
snippet.setMultiline(false)
info.addView(title);
info.addView(snippet);
return info;
}
});
// Updates the location and zoom level of the MapView
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(51.509932, -0.134720), 18);
mGoogleMap.animateCamera(cameraUpdate);
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mMapView.onSaveInstanceState(outState);
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
private void initMap(boolean isChecked){
if (isChecked) {
mGoogleMap.setMapStyle(new MapStyleOptions(getResources().getString(R.string.style_json)));
} else {
mGoogleMap.setMapStyle(null);
}
}
}
1st marker
2nd marker

Don't add your TextView snippet to your LinearLayout info if your Marker has no snippet:
#Override
public View getInfoContents(Marker marker) {
Context mContext = getActivity();
LinearLayout info = new LinearLayout(mContext);
info.setOrientation(LinearLayout.VERTICAL);
TextView title = new TextView(mContext);
title.setTextColor(Color.BLACK);
title.setGravity(Gravity.CENTER);
title.setTypeface(null, Typeface.BOLD);
title.setText(marker.getTitle());
title.setSingleLine(false);
info.addView(title);
if (marker.getSnippet() != null) {
TextView snippet = new TextView(mContext);
snippet.setTextColor(Color.GRAY);
snippet.setText(marker.getSnippet());
snippet.setSingleLine(false);
info.addView(snippet);
}
return info;
}

Related

Using SearchView to retrieve matching values in Firebase database

I have an activity where I want to search matching values in my firebase database. I don't want anything to appear up until something is typed on my SearchBar, after something has been typed I want to display values that match what was typed in my SearchBar. I have created an activity and it is not displaying anything up until you type something, my problem is that it does not retrieve the matching values but it shows everything within my database directory.
This is my activity:
public class MyUsersActivity extends AppCompatActivit {
private Toolbar toolbar, searchtollbar;
private RecyclerView mUsersList;
private DatabaseReference mUsersDatabase;
private LinearLayoutManager mLayoutManager;
Menu search_menu;
MenuItem item_search;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//getSupportActionBar().setTitle("Search Users");
//toolbar.setTitleTextColor(android.graphics.Color.WHITE);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
mLayoutManager = new LinearLayoutManager(this);
mUsersList = (RecyclerView) findViewById(R.id.users_list);
mUsersList.setHasFixedSize(true);
mUsersList.setLayoutManager(mLayoutManager);
setSearchtollbar();
}
#Override
protected void onStart() {
super.onStart();
}
public static class UsersViewHolder extends RecyclerView.ViewHolder {
View mView;
public UsersViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setDisplayName(String name){
TextView userNameView = (TextView) mView.findViewById(R.id.user_single_name);
userNameView.setText(name);
}
public void setUserStatus(String status){
TextView userStatusView = (TextView) mView.findViewById(R.id.user_single_status);
userStatusView.setText(status);
}
public void setUserImage(String thumb_image, Context ctx){
CircleImageView userImageView = (CircleImageView) mView.findViewById(R.id.user_single_image);
Picasso.with(ctx).load(thumb_image).placeholder(R.drawable.my_profile).into(userImageView);
}
}
public void setSearchtollbar()
{
searchtollbar = (Toolbar) findViewById(R.id.searchtoolbar);
if (searchtollbar != null) {
searchtollbar.inflateMenu(R.menu.menu_search);
search_menu=searchtollbar.getMenu();
searchtollbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
circleReveal(R.id.searchtoolbar,1,true,false);
else
searchtollbar.setVisibility(View.GONE);
}
});
item_search = search_menu.findItem(R.id.action_filter_search);
MenuItemCompat.setOnActionExpandListener(item_search, new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
// Do something when collapsed
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
circleReveal(R.id.searchtoolbar,1,true,false);
}
else
searchtollbar.setVisibility(View.GONE);
return true;
}
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
// Do something when expanded
return true;
}
});
initSearchView();
} else
Log.d("toolbar", "setSearchtollbar: NULL");
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void circleReveal(int viewID, int posFromRight, boolean containsOverflow, final boolean isShow)
{
final View myView = findViewById(viewID);
int width=myView.getWidth();
if(posFromRight>0)
width-=(posFromRight*getResources().getDimensionPixelSize(R.dimen.abc_action_button_min_width_material))-(getResources().getDimensionPixelSize(R.dimen.abc_action_button_min_width_material)/ 2);
if(containsOverflow)
width-=getResources().getDimensionPixelSize(R.dimen.abc_action_button_min_width_overflow_material);
int cx=width;
int cy=myView.getHeight()/2;
Animator anim;
if(isShow)
anim = ViewAnimationUtils.createCircularReveal(myView, cx, cy, 0,(float)width);
else
anim = ViewAnimationUtils.createCircularReveal(myView, cx, cy, (float)width, 0);
anim.setDuration((long)220);
// make the view invisible when the animation is done
anim.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
if(!isShow)
{
super.onAnimationEnd(animation);
myView.setVisibility(View.INVISIBLE);
}
}
});
// make the view visible and start the animation
if(isShow)
myView.setVisibility(View.VISIBLE);
// start the animation
anim.start();
}
public void initSearchView()
{
final SearchView searchView = (SearchView) search_menu.findItem(R.id.action_filter_search).getActionView();
// Enable/Disable Submit button in the keyboard
searchView.setSubmitButtonEnabled(false);
// Change search close button image
ImageView closeButton = (ImageView) searchView.findViewById(R.id.search_close_btn);
closeButton.setImageResource(R.drawable.ic_close);
// set hint and the text colors
EditText txtSearch = ((EditText) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text));
txtSearch.setHint("Search..");
txtSearch.setHintTextColor(Color.DKGRAY);
txtSearch.setTextColor(getResources().getColor(R.color.colorPrimary));
// set the cursor
AutoCompleteTextView searchTextView = (AutoCompleteTextView) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
try {
Field mCursorDrawableRes = TextView.class.getDeclaredField("mCursorDrawableRes");
mCursorDrawableRes.setAccessible(true);
mCursorDrawableRes.set(searchTextView, R.drawable.search_cursor); //This sets the cursor resource ID to 0 or #null which will make it visible on white background
} catch (Exception e) {
e.printStackTrace();
}
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
callSearch(query);
searchView.clearFocus();
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
callSearch(newText);
return true;
}
public void callSearch(String query) {
//Do searching
Log.i("query", "" + query);
if(!query.equals("")){
FirebaseRecyclerAdapter<Users, UsersViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(
Users.class,
R.layout.users_single_layout,
UsersViewHolder.class,
mUsersDatabase
) {
#Override
protected void populateViewHolder(UsersViewHolder usersViewHolder, Users users, int position) {
usersViewHolder.setDisplayName(users.getName());
usersViewHolder.setUserStatus(users.getStatus());
usersViewHolder.setUserImage(users.getThumb_image(), getApplicationContext());
final String user_id = getRef(position).getKey();
usersViewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent profileIntent = new Intent(MyUsersActivity.this, ProfileActivity.class);
profileIntent.putExtra("user_id", user_id);
startActivity(profileIntent);
}
});
}
};
mUsersList.setAdapter(firebaseRecyclerAdapter);
}
}
});
}
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.menu_home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.action_search:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
circleReveal(R.id.searchtoolbar,1,true,true);
else
searchtollbar.setVisibility(View.VISIBLE);
item_search.expandActionView();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
How can I implement the match function to retrieve what's matching in my database?

Method doesnot override method from it's super class

I just copied this code from somewhere put when I tried to run it says method doesnot override method from it's super class. I am a newbie to java inheritance. Please help me understand this. How can I solve this? This error is shown for last two #override methods.
public class MapViewFragment extends Fragment implements OnMapReadyCallback {
private Button btnFindPath;
private EditText etOrigin;
private EditText etDestination;
private ProgressDialog progressDialog;
private List<Marker> originMarkers = new ArrayList<>();
private List<Marker> destinationMarkers = new ArrayList<>();
private List<Polyline> polylinePaths = new ArrayList<>();
GoogleMap mGoogleMap;
MapView mMapView;
View mView;
public MapViewFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mView = inflater.inflate(R.layout.fragment_map_view, container, false);
btnFindPath = (Button) getView().findViewById(R.id.btnFindPath);
etOrigin = (EditText) getView().findViewById(R.id.etOrigin);
etDestination = (EditText) getView().findViewById(R.id.etDestination);
btnFindPath.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendRequest();
}
});
return mView;
}
private void sendRequest() {
String origin = etOrigin.getText().toString();
String destination = etDestination.getText().toString();
if (origin.isEmpty()) {
Toast.makeText(getActivity(), "Please enter origin address!", Toast.LENGTH_SHORT).show();
return;
}
if (destination.isEmpty()) {
Toast.makeText(getActivity(), "Please enter destination address!", Toast.LENGTH_SHORT).show();
return;
}
try {
new DirectionFinder(getActivity(), origin, destination).execute();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mMapView = (MapView) mView.findViewById(R.id.map);
if (mMapView != null){
mMapView.onCreate(null);
mMapView.onResume();
mMapView.getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
MapsInitializer.initialize(this.getActivity());
mGoogleMap = googleMap;
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.addMarker(new MarkerOptions().position(new LatLng(27.717245, 85.323960)).title("Yo ho Kathmandu University") .snippet("I study Here"));
CameraPosition Liberty = CameraPosition.builder().target(new LatLng(27.717245, 85.323960)).zoom(16).bearing(0).tilt(45).build();
googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(Liberty));
googleMap.setMyLocationEnabled(true);
}
#Override
public void onDirectionFinderStart() {
progressDialog = ProgressDialog.show(getActivity(), "Please wait.",
"Finding direction..!", true);
if (originMarkers != null) {
for (Marker marker : originMarkers) {
marker.remove();
}
}
if (destinationMarkers != null) {
for (Marker marker : destinationMarkers) {
marker.remove();
}
}
if (polylinePaths != null) {
for (Polyline polyline:polylinePaths ) {
polyline.remove();
}
}
}
#Override
public void onDirectionFinderSuccess(List<Route> routes) {
progressDialog.dismiss();
polylinePaths = new ArrayList<>();
originMarkers = new ArrayList<>();
destinationMarkers = new ArrayList<>();
for (Route route : routes) {
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(route.startLocation, 16));
((TextView) getView().findViewById(R.id.tvDuration)).setText(route.duration.text);
((TextView) getView().findViewById(R.id.tvDistance)).setText(route.distance.text);
originMarkers.add(mGoogleMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_media_pause))
.title(route.startAddress)
.position(route.startLocation)));
destinationMarkers.add(mGoogleMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_media_play))
.title(route.endAddress)
.position(route.endLocation)));
PolylineOptions polylineOptions = new PolylineOptions().
geodesic(true).
color(Color.BLUE).
width(10);
for (int i = 0; i < route.points.size(); i++)
polylineOptions.add(route.points.get(i));
polylinePaths.add(mGoogleMap.addPolyline(polylineOptions));
}
}
}
You are missing "DirectionFinderListener" interface:
public class MapViewFragment extends Fragment implements OnMapReadyCallback, DirectionFinderListener
Don't forget to add all the classes from Google map direction sample app:
https://github.com/hiepxuan2008/GoogleMapDirectionSimple/tree/master/app/src/main/java/Modules

Android maps v2 - Map view pins unexpectedly reappearing on resume

A tab within my view pager contains a map view is showing some unexpected behaviour. For some reason whenever I go to a different tab and return to the map view tab, all 4 pins within my map view appear when only 2 of them are supposed to appear. Does anyone know why this has happened? What can be done in order to prevent this from happening?
Stage 1 (flicked the top switch)
Stage 2 (flicked the bottom switch)
Stage 3 (switching to a different tab, then returning back to the map tab)
Java class
public class FragmentCentralPark extends android.support.v4.app.Fragment implements OnMapReadyCallback {
public FragmentCentralPark() {
// Required empty constructor
}
GoogleMap mGoogleMap;
MapView mMapView;
SwitchCompat swt0;
SwitchCompat swt1;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_centralpark, container, false);
mMapView = (MapView) v.findViewById(R.id.map_centralpark);
mMapView.onCreate(savedInstanceState);
mMapView.getMapAsync(this); //this is important
swt0 = (SwitchCompat) v.findViewById(R.id.switch0_map_centralpark);
swt1 = (SwitchCompat) v.findViewById(R.id.switch1_map_centralpark);
return v;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mGoogleMap.setBuildingsEnabled(true);
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
swt0.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
initMap0(isChecked);
}
});
swt1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
initMap1(isChecked);
}
});
initMap0(swt0.isChecked());
initMap1(swt1.isChecked());
// Add markers and move the camera
LatLng centralpark_museum1 = new LatLng(40.785407, -73.957145);
mGoogleMap.addMarker(new MarkerOptions()
.position(centralpark_museum1)
);
LatLng centralpark_museum2 = new LatLng(40.782993, -73.958985);
mGoogleMap.addMarker(new MarkerOptions()
.position(centralpark_museum2)
);
// Updates the location and zoom level of the MapView
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(40.780437, -73.981063), 16);
mGoogleMap.animateCamera(cameraUpdate);
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mMapView.onSaveInstanceState(outState);
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
private void initMap0(boolean isChecked){
if (isChecked) {
mGoogleMap.setMapStyle(new MapStyleOptions(getResources()
.getString(R.string.style_json)));
} else {
mGoogleMap.setMapStyle(null);
}
}
private void initMap1(boolean isChecked){
if (isChecked) {
mGoogleMap.clear();
// Add markers and move the camera
LatLng centralpark__theatre1 = new LatLng(40.780287, -73.968832);
mGoogleMap.addMarker(new MarkerOptions()
.position(centralpark_theatre1)
);
LatLng centralpark__theatre2 = new LatLng(40.780437, -73.981063);
mGoogleMap.addMarker(new MarkerOptions()
.position(centralpark_theatre2)
);
// Updates the location and zoom level of the MapView
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(40.780437, -73.981063), 16);
mGoogleMap.animateCamera(cameraUpdate);
} else {
mGoogleMap.clear();
// Add markers and move the camera
LatLng centralpark_museum1 = new LatLng(40.785407, -73.957145);
mGoogleMap.addMarker(new MarkerOptions()
.position(centralpark_museum1)
);
LatLng centralpark_museum2 = new LatLng(40.782993, -73.958985);
mGoogleMap.addMarker(new MarkerOptions()
.position(centralpark_museum2)
);
// Updates the location and zoom level of the MapView
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(40.780437, -73.981063), 16);
mGoogleMap.animateCamera(cameraUpdate);
}
}
}

Firebase and Android - Chat Message and OnClickListener

I learn Firebase and I found this project: https://github.com/firebase/FirebaseUI-Android/tree/0.3.1/codelabs/chat
I'm trying to expand this project for setOnClickListener method.
I would like to click on every item of this chat message(chat listview) and see
this in another activity.
For example: I have this chat in: ChatMessageActivity. And I would like show this in ChatMessageDetailsActivity.
Like this:
private Firebase firebaseRef;
private static final String FIREBASE_URL = "https://my-project.firebaseio.com/chat";
FirebaseListAdapter listAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_message);
Firebase.setAndroidContext(this);
firebaseRef = new Firebase(FIREBASE_URL);
final EditText mText = (EditText) findViewById(R.id.messageText);
Button sendButton = (Button) findViewById(R.id.sendButton);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = mText.getText().toString();
ChatMessage message = new ChatMessage("Android User", text);
firebaseRef.push().setValue(message);
mText.setText("");
}
});
final ListView listView = (ListView) this.findViewById(R.id.list);
listAdapter = new FirebaseListAdapter<ChatMessage>(this, ChatMessage.class,
android.R.layout.two_line_list_item, firebaseRef) {
#Override
protected void populateView(View v, ChatMessage model, int position) {
((TextView)v.findViewById(android.R.id.text1)).setText(model.getName());
((TextView)v.findViewById(android.R.id.text2)).setText(model.getText());
}
};
listView.setAdapter(listAdapter);
firebaseRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
}
public void onChildChanged(DataSnapshot dataSnapshot, String s) { }
public void onChildRemoved(DataSnapshot dataSnapshot) { }
public void onChildMoved(DataSnapshot dataSnapshot, String s) { }
public void onCancelled(FirebaseError firebaseError) { }
});
}
#Override
public View getView(View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if ( row == null || (row.getTag() == null)) {
holder = new ViewHolder();
holder.chatName = (TextView) row.findViewById(R.id.detsName);
holder.chatText = (TextView) row.findViewById(R.id.detsText);
row.setTag(holder);
}else {
holder = (ViewHolder) row.getTag();
}
holder.chatName.setText(holder.chatMessage.getName());
holder.chatText.setText(holder.chatMessage.getText());
final ViewHolder finalHolder = holder;
row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ChatMessage.this, ChatMessageDetails.class);
startActivity(i);
}
});
return row;
}
public class ViewHolder {
ChatMessage chatMessage;
TextView chatName;
TextView chatText;
}
#Override
protected void onDestroy() {
super.onDestroy();
listAdapter.cleanup();
}
}
But getView(at the bottom) method doesn't work. I had this in my old project without Firebase and internet connection. It worked. But now I'm trying to implement this in Chat Project but without positive results.
Is in Firebase some inside method to do this?
Does somebody has some preposition how to develop this listView with SetOnClickListener method with Firebase in AndroidStudio?

Getting indexOutOfBoundsException while trying to fetch data from parse

I am trying to fetch some data from parse, but my app is getting crashed every time due to this error: java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0 at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255) at java.util.ArrayList.get(ArrayList.java:308) at com.abc.xyz.AcceptARequest$1$1.done(AcceptARequest.java:157)
Here's AcceptARequest.java(in which I'm fetching data from parse) file's code :
public class AcceptARequest extends Fragment{
private OnFragmentInteractionListener mListener;
public List<ListContentAAR> listContentAARs;
public RecyclerView recyclerView;
ImageView hPicAccept;
TextView hDescriptionAccept, currentCoordinatesTagAccept, currentLatAccept, currentLngAccept, post_date, post_time, posted_by;
String hDescriptionAcceptS, currentCoordinatesTagAcceptS, currentLatAcceptS, currentLngAcceptS, post_dateS, post_timeS, posted_byS;
Button btn_accept, btn_share;
LinearLayout latContainerAccept, lngContainerAccept, dateTimeContainer;
ParseQuery<ParseObject> query;
String hDescription, cLat, cLng;
public AcceptARequest() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_accept_a_request, container, false);
listContentAARs = new ArrayList<>();
hPicAccept = (ImageView) rootView.findViewById(R.id.h_pic_accept);
hDescriptionAccept = (TextView) rootView.findViewById(R.id.h_description_accept);
currentCoordinatesTagAccept = (TextView) rootView.findViewById(R.id.currentCoordinatesTagAccept);
currentLatAccept = (TextView) rootView.findViewById(R.id.currentLatAccept);
currentLngAccept = (TextView) rootView.findViewById(R.id.currentLngAccept);
btn_accept = (Button) rootView.findViewById(R.id.btn_accept);
btn_share = (Button) rootView.findViewById(R.id.btn_share);
latContainerAccept = (LinearLayout) rootView.findViewById(R.id.latContainerAccept);
lngContainerAccept = (LinearLayout) rootView.findViewById(R.id.lngContainerAccept);
dateTimeContainer = (LinearLayout) rootView.findViewById(R.id.date_time_container);
post_date = (TextView) rootView.findViewById(R.id.post_date);
post_time = (TextView) rootView.findViewById(R.id.post_time);
posted_by = (TextView) rootView.findViewById(R.id.posted_by);
hDescriptionAcceptS = hDescriptionAccept.getText().toString();
currentCoordinatesTagAcceptS = currentCoordinatesTagAccept.getText().toString();
currentLatAcceptS = currentLatAccept.getText().toString();
currentLngAcceptS = currentLngAccept.getText().toString();
post_dateS = post_date.getText().toString();
post_timeS = post_time.getText().toString();
posted_byS = posted_by.getText().toString();
currentCoordinatesTagAccept.setVisibility(View.INVISIBLE);
currentLatAccept.setVisibility(View.INVISIBLE);
currentLngAccept.setVisibility(View.INVISIBLE);
latContainerAccept.setVisibility(View.INVISIBLE);
lngContainerAccept.setVisibility(View.INVISIBLE);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
query = ParseQuery.getQuery("HomelessDetails");
query.whereEqualTo("objectId", ParseUser.getCurrentUser().getObjectId());
query.addDescendingOrder("createdAt");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
if (e == null) {
currentCoordinatesTagAccept.setVisibility(View.VISIBLE);
currentLatAccept.setVisibility(View.VISIBLE);
currentLngAccept.setVisibility(View.VISIBLE);
latContainerAccept.setVisibility(View.VISIBLE);
lngContainerAccept.setVisibility(View.VISIBLE);
hDescriptionAcceptS = list.get(1).getString("hDescription");
hDescriptionAccept.setText(hDescriptionAcceptS);
currentLatAcceptS = list.get(1).getString("hLatitude");
currentLatAccept.setText(currentLatAcceptS);
currentLngAcceptS = list.get(1).getString("hLongitude");
currentLngAccept.setText(currentLngAcceptS);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(e.getMessage());
builder.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
}, 1000);
recyclerView = (RecyclerView) rootView.findViewById(R.id.accept_request_list);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
Button btnAccept = (Button) view.findViewById(R.id.btn_accept);
btnAccept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.request_accepted_txt);
builder.setPositiveButton("Navigate me", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getActivity(), "Navigating you to the needy...", Toast.LENGTH_LONG).show();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getActivity(), "The help-request has been rejected.", Toast.LENGTH_LONG).show();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
Button btnShare = (Button) view.findViewById(R.id.btn_share);
btnShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// share the help-request here.
}
});
}
#Override
public void onLongClick(View view, int position) {
}
}));
initializeAdapter();
return rootView;
}
private void initializeAdapter(){
RVAdapterAAR adapter = new RVAdapterAAR(listContentAARs);
recyclerView.setAdapter(adapter);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
public void itemClicked(View view, int position) {
}
class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
super.onLongPress(e);
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public static interface ClickListener {
public void onClick(View view, int position);
public void onLongClick(View view, int position);
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
I don't know what's going wrong here.
Please let me know.
Please cooperate if question seems to be badly formatted, I'm still learning to post good questions.
You are trying to access the ArrayList which does not have any element in it. SO list.get(1) won't work.
Make sure that your ArrayList is getting populated correctly.
#Hammad:
The error that you are getting is because of the array list that you are using does not contain any elements/objects in it.
You need to populate the arraylist using list.Add()(or based on your preference) method.

Categories

Resources