onLongClick with Context Action Bar CAB not taking place, only onListItemClick performed, in tablet activity with ListFragment and DetailFragment - callback

I have a ListFragment that is called from a ListActivity, with a dual fragment layout on a tablet.
I have used the standard MasterDetail Fragment setup from Android Studio 0.3.6 API 19.
MyListFragment looks as follows:
import android.app.Activity;
import android.content.ContentUris;
import android.net.Uri;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.support.v4.widget.SimpleCursorAdapter;
import com.supascale.supascale.contentprovider.SupaScaleContentProvider;
import com.supascale.supascale.database.SupascaleDb;
/**
* A list fragment representing a list of Animals. This fragment
* also supports tablet devices by allowing list items to be given an
* 'activated' state upon selection. This helps indicate which item is
* currently being viewed in a {#link AnimalDetailFragment}.
* <p>
* Activities containing this fragment MUST implement the {#link Callbacks}
* interface.
*
* You can create new ones via the ActionBar entry "Insert".
* You can delete existing ones via a long press on the item.
*/
public class AnimalListFragment extends ListFragment implements
android.support.v4.app.LoaderManager.LoaderCallbacks<Cursor>{
private static final int ACTIVITY_CREATE = 0;
private static final int ACTIVITY_EDIT = 1;
private static final int DELETE_ID = Menu.FIRST + 1;
private SimpleCursorAdapter adapter;
protected Object mActionMode;
private ActionMode.Callback mActionModeCallback;
/**
* The serialization (saved instance state) Bundle key representing the
* activated item position. Only used on tablets.
*/
private static final String STATE_ACTIVATED_POSITION = "activated_position";
/**
* The fragment's current callback object, which is notified of list item
* clicks.
*/
private Callbacks mCallbacks = sDummyCallbacks;
/**
* The current activated item position. Only used on tablets.
*/
private int mActivatedPosition = ListView.INVALID_POSITION;
/**
* A callback interface that all activities containing this fragment must
* implement. This mechanism allows activities to be notified of item
* selections. NB AJW
*/
public interface Callbacks {
/**
* Callback for when an item has been selected.
*/
public void onItemSelected(Uri id);
}
/**
* A dummy implementation of the {#link Callbacks} interface that does
* nothing. Used only when this fragment is not attached to an activity.
*/
private static Callbacks sDummyCallbacks = new Callbacks() {
#Override
public void onItemSelected(Uri animalUri) {
}
};
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public AnimalListFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
return inflater.inflate(R.layout.animal_list, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
String[] from = new String[] { SupascaleDb.KEY_Animal_ANIMALIDENTIFICATION };
// Fields on the UI to which we map
int[] to = new int[] { R.id.label };
getLoaderManager().initLoader(0, null, this);
adapter = new SimpleCursorAdapter(getActivity(), R.layout.animal_row, null, from,
to, 0);
setListAdapter(adapter);
// Restore the previously serialized activated item position.
if (savedInstanceState != null
&& savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) {
setActivatedPosition(savedInstanceState.getInt(STATE_ACTIVATED_POSITION));
}
mActionModeCallback = new ActionMode.Callback() {
// Called when the action mode is created; startActionMode() was called
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// Inflate a menu resource providing context menu items
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.listmenu, menu);
return true;
}
// Called each time the action mode is shown. Always called after onCreateActionMode, but
// may be called multiple times if the mode is invalidated.
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false; // Return false if nothing is done
}
// Called when the user selects a contextual menu item
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case DELETE_ID:
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
.getMenuInfo();
Uri uri = Uri.parse(SupaScaleContentProvider.CONTENT_URI_ANIMAL + "/"
+ info.id);
getActivity().getContentResolver().delete(uri, null, null);
mode.finish(); // Action picked, so close the CAB
return true;
default:
return false;
}
}
// Called when the user exits the action mode
#Override
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
}
};
getView().setOnLongClickListener( new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
if (mActionMode != null) {
return false;
}
// Start the CAB using the ActionMode.Callback defined above
mActionMode = view.startActionMode(mActionModeCallback);
view.setSelected(true);
return true;
}
});
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Activities containing this fragment must implement its callbacks.
if (!(activity instanceof Callbacks)) {
throw new IllegalStateException("Activity must implement fragment's callbacks.");
}
mCallbacks = (Callbacks) activity;
}
#Override
public void onDetach() {
super.onDetach();
// Reset the active callbacks interface to the dummy implementation.
mCallbacks = sDummyCallbacks;
}
#Override
public void onListItemClick(ListView listView, View view, int position, long id) {
super.onListItemClick(listView, view, position, id);
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
//2013-11-26 AJW Append the clicked item's row ID with the content provider Uri
Uri animalUri = ContentUris.withAppendedId(SupaScaleContentProvider.CONTENT_URI_ANIMAL, id);
// Send the event and Uri to the host activity
mCallbacks.onItemSelected(animalUri);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mActivatedPosition != ListView.INVALID_POSITION) {
// Serialize and persist the activated item position.
outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition);
}
}
/**
* Turns on activate-on-click mode. When this mode is on, list items will be
* given the 'activated' state when touched.
*/
public void setActivateOnItemClick(boolean activateOnItemClick) {
// When setting CHOICE_MODE_SINGLE, ListView will automatically
// give items the 'activated' state when touched.
getListView().setChoiceMode(activateOnItemClick
? ListView.CHOICE_MODE_SINGLE
: ListView.CHOICE_MODE_NONE);
}
private void setActivatedPosition(int position) {
if (position == ListView.INVALID_POSITION) {
getListView().setItemChecked(mActivatedPosition, false);
} else {
getListView().setItemChecked(position, true);
}
mActivatedPosition = position;
}
/**
* Creates a new loader after the initLoader () call
*/
//#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] projection = { SupascaleDb.KEY_ROWID, SupascaleDb.KEY_Animal_ANIMALIDENTIFICATION };
CursorLoader cursorLoader = new CursorLoader(getActivity(),
SupaScaleContentProvider.CONTENT_URI_ANIMAL, projection, null, null, null);
return cursorLoader;
}
//#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
adapter.swapCursor(data);
}
//#Override
public void onLoaderReset(Loader<Cursor> loader) {
// data is not available anymore, delete reference
adapter.swapCursor(null);
}
}
My AnimalListActivity looks as follows:
/**
* An activity representing a list of Animals. This activity
* has different presentations for handset and tablet-size devices. On
* handsets, the activity presents a list of items, which when touched,
* lead to a {#link AnimalDetailActivity} representing
* item details. On tablets, the activity presents the list of items and
* item details side-by-side using two vertical panes.
* <p>
* The activity makes heavy use of fragments. The list of items is a
* {#link AnimalListFragment} and the item details
* (if present) is a {#link AnimalDetailFragment}.
* <p>
* This activity also implements the required
* {#link AnimalListFragment.Callbacks} interface
* to listen for item selections.
*/
public class AnimalListActivity extends FragmentActivity
implements AnimalListFragment.Callbacks {
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet
* device.
*/
private boolean mTwoPane;
private SimpleCursorAdapter adapter;
private static final int ACTIVITY_CREATE = 0;
private static final int ACTIVITY_EDIT = 1;
private static final int DELETE_ID = Menu.FIRST + 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_animal_list);
if (findViewById(R.id.animal_detail_container) != null) {
// The detail container view will be present only in the
// large-screen layouts (res/values-large and
// res/values-sw600dp). If this view is present, then the
// activity should be in two-pane mode.
mTwoPane = true;
// In two-pane mode, list items should be given the
// 'activated' state when touched.
((AnimalListFragment) getSupportFragmentManager()
.findFragmentById(R.id.animal_list))
.setActivateOnItemClick(true);
}
// TODO: If exposing deep links into your app, handle intents here.
}
/**
* Callback method from {#link AnimalListFragment.Callbacks}
* indicating that the item with the given ID was selected.
*/
#Override
public void onItemSelected(Uri animalUri) {
//String id = Long.toString(ContentUris.parseId(animalUri));
if (mTwoPane) {
// In two-pane mode, show the detail view in this activity by
// adding or replacing the detail fragment using a
// fragment transaction.
Bundle arguments = new Bundle();
arguments.putString(AnimalDetailFragment.ARG_URI, animalUri.toString()); //Key value pair Adrian "animal_uri = .."
AnimalDetailFragment fragment = new AnimalDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.animal_detail_container, fragment)
.commit();
} else {
// In single-pane mode, simply start the detail activity
// for the selected item ID.
Intent detailIntent = new Intent(this, AnimalDetailActivity.class);
//Uri todoUri = Uri.parse(SupaScaleContentProvider.CONTENT_URI_ANIMAL + "/" + id);
//detailIntent.putExtra(AnimalDetailFragment.ARG_ITEM_ID, id);
//startActivity(detailIntent);
detailIntent.putExtra(SupaScaleContentProvider.CONTENT_ITEM_TYPE, animalUri);
// Activity returns an result if called with startActivityForResult
startActivityForResult(detailIntent, ACTIVITY_EDIT);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.listmenu, menu);
return true;
}
// Reaction to the menu selection
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.insert:
createAnimal();
return true;
}
return super.onOptionsItemSelected(item);
}
private void createAnimal() {
if (mTwoPane) {
// In two-pane mode, show the detail view in this activity by
// adding or replacing the detail fragment using a
// fragment transaction.
Bundle arguments = new Bundle();
//arguments.putString(AnimalDetailFragment.ARG_URI, animalUri.toString()); //Key value pair Adrian "animal_uri = .."
AnimalDetailFragment fragment = new AnimalDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.animal_detail_container, fragment)
.commit();
} else {
// In single-pane mode, simply start the detail activity
Intent i = new Intent(this, AnimalDetailActivity.class);
startActivityForResult(i, ACTIVITY_EDIT);
}
}
}
AnimalListActivity.xml
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/animal_list"
android:name="com.supascale.supascale.AnimalListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
tools:context=".AnimalListActivity"
tools:layout="#android:layout/list_content" />
The List.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#android:id/list" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="No Animal Data"
android:id="#android:id/empty" />
</LinearLayout>
The row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/icon"
android:layout_width="30dp"
android:layout_height="24dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
android:src="#drawable/reminder" >
</ImageView>
<TextView
android:id="#+id/label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="6dp"
android:lines="1"
android:text="#+id/textViewNormalTotal"
android:textSize="24sp"
>
</TextView>
</LinearLayout>
The fragment list scrolls correctly, and when clicked the detail fragment is correctly populated. When I long click, nothing happens, and when I release the longclick, the click event is fired.
I need for the long click to result in the CAB (Context Action Bar) to display, so that I can delete a record, or share a record etc.
mActionMode = view.startActionMode(mActionModeCallback); just never appears to be called.
Hope I have been clear enough.
Regards
Adrian
I edited and added the imports for the ListFragment, as it may have to do with support.v4?

Ok, so I did not understand the CAB help so nicely.
http://developer.android.com/guide/topics/ui/menus.html#CAB
For a ListView or ListFragment, and not another kind of view, you must use the setOnItemLongClickListener,
and not the setOnLongClickListener, as in the help from developer.android.com.
The setOnLongClickListener, is never activated by the listview, and thus never can procede to create the CAB.
I removed the following code:
getView().setOnLongClickListener( new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
if (mActionMode != null) {
return false;
}
// Start the CAB using the ActionMode.Callback defined above
mActionMode = view.startActionMode(mActionModeCallback);
view.setSelected(true);
return true;
}
});
and replaced with the following:
getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View view,
int position, long id) {
if (mActionMode != null) {
return false;
}
Animal_id = id;
// Start the CAB using the ActionMode.Callback defined above
mActionMode = getActivity().startActionMode(mActionModeCallback);
view.setSelected(true);
return true;
}
});
Now the long click event fires, and I can get the CAB to display properly.

Related

how do i implement android mapbox android sdk successfully in fragment

I am using mapbox in a fragment with bottom navigation, when i exit and resume the app or when i change tabs rapidly, the app crashes. this is the error i get
10-07 22:20:36.046 21867-21886/com.dropexpress.driver.dropexpressdriver E/Mbgl-FileSource: Failed to read the storage key:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.os.Bundle.getBoolean(java.lang.String, boolean)' on a null object reference
at com.mapbox.mapboxsdk.storage.FileSource.getCachePath(FileSource.java:88)
at com.mapbox.mapboxsdk.storage.FileSource$FileDirsPathsTask.doInBackground(FileSource.java:165)
at com.mapbox.mapboxsdk.storage.FileSource$FileDirsPathsTask.doInBackground(FileSource.java:155)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
the below code always fails when i exit the app and resume, or when i change tabs rapidly, i am using bottom navigation.
Steps to reproduce
here is my fragment code
package com.dropexpress.driver.dropexpressdriver.fragments;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.dropexpress.driver.dropexpressdriver.R;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.maps.MapView;
public class HomeFragment extends Fragment {
private MapView mapView;
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public HomeFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment HomeFragment.
*/
// TODO: Rename and change types and number of parameters
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#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 view = inflater.inflate(R.layout.fragment_home, container, false);
Mapbox.getInstance(requireActivity(), "pk.eyJ1Ijoic3ludGF4bHRkIiwiYSI6ImNqaDJxNnhzbDAwNnMyeHF3dGlqODZsYjcifQ.pcz6BWpzCHeZ6hQg4AH9ww");
mapView = (MapView) view.findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#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);
}
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onStop() {
super.onStop();
mapView.onStop();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
}
Android versions: 5.0 +
Device models: motorola g5
Mapbox SDK versions: 6.5.0
Put your Mapbox.getInstance before inflating your layout.
Mapbox.getInstance(requireActivity(),"Your Map Key");
View view = inflater.inflate(R.layout.fragment_home, container, false);
mapView = (MapView) view.findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
I hope this helps you.
i opened this issue in github, you check their response here
https://github.com/mapbox/mapbox-gl-native/issues/13044#issuecomment-427861016
this was their response:
I can see 2 issues with the provided code:
You are not calling MapView#onDestroy, this has to be called from you fragment's #onDestroyView.
MapView#onCreate should be called from fragment's #onViewCreatedinstead of #onCreateView.
I applied the changes and it worked!

SupportMapFragmentManagers getMapAsync() does not trigger onMapReady(GoogleMap map)

I have a
public abstract class MyMapFragment implements OnMapReadyCallback
{
//
public GoogleMap googleMap;
SupportMapFragment mapFragment;
#IdRes
public abstract int getSupportMapFragId();
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// http://stackoverflow.com/a/36592000/5102206
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
// Do something for lollipop and above versions
mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(getSupportMapFragId());
} else {
// do something for phones running an SDK before lollipop
mapFragment = (SupportMapFragment) getFragmentManager().findFragmentById(getSupportMapFragId());
}
mapFragment.getMapAsync(this);
}
//..
#Override
public void onMapReady(GoogleMap map) {
this.googleMap = map;
}
}
According to my breakpoints onViewCreated() is called, but onMapReady() is not called (breakpoint on this.googleMap = map not triggered)
On Android 5, 6 and 7 it works fine so far and I can see the Map..
On Android 4.X (API 16 - API 19) devices my app starts up, but then it seem to freeze there... I see a white blank screen.
On Android 4.X OS devices:
1. With getFragmentManager(), the mapFragment object is null after the else condition.
2. With getChildFragmentMenager() the mapfragment seem to be valid and non-null, but onMapReady not triggered.
What am I missing here?
Note: You cannot inflate a layout into a fragment when that layout includes a . Nested fragments are only supported when added to a fragment dynamically
If you want to inflate a map in a fragment you can either do it in xml or do it in java code like this:
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
FragmentManager fm = getChildFragmentManager();
SupportMapFragment mapFragment = (SupportMapFragment) fm.findFragmentByTag("mapFragment");
if (mapFragment == null) {
mapFragment = new SupportMapFragment();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.mapFragmentContainer, mapFragment, "mapFragment");
ft.commit();
fm.executePendingTransactions();
}
mapFragment.getMapAsync(callback);
}
And also the simple container
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mapFragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
Also, you don't need to implement the onMapReadyCallback in the class definition. Instead of callback you create a new OnMapReadyCallback() right there:
MapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
}
});
You also need these
MapView mMapView;
private GoogleMap googleMap;
I hope this helps somehow !
There was an issue with a blocking thread from RxJava on main thread. So it was not an Google Maps issue.
I don't quite understand why you are nesting fragments, specially because it can cause performance issues.
If you take a look at Google Samples, the Google Maps examples uses an Activity and SupportMapFragment:
public class MapsActivityCurrentPlace extends AppCompatActivity
implements OnMapReadyCallback, ConnectionCallbacks,
OnConnectionFailedListener {
#Override
public void onMapReady(GoogleMap map) {
mMap = map;
// Use a custom info window adapter to handle multiple lines of text in the
// info window contents.
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
// Return null here, so that getInfoContents() is called next.
public View getInfoWindow(Marker arg0) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
// Inflate the layouts for the info window, title and snippet.
View infoWindow = getLayoutInflater().inflate(R.layout.custom_info_contents,
(FrameLayout)findViewById(R.id.map), false);
TextView title = ((TextView) infoWindow.findViewById(R.id.title));
title.setText(marker.getTitle());
TextView snippet = ((TextView) infoWindow.findViewById(R.id.snippet));
snippet.setText(marker.getSnippet());
return infoWindow;
}
});
// Turn on the My Location layer and the related control on the map.
updateLocationUI();
// Get the current location of the device and set the position of the map.
getDeviceLocation();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
mLastKnownLocation = savedInstanceState.getParcelable(KEY_LOCATION);
mCameraPosition = savedInstanceState.getParcelable(KEY_CAMERA_POSITION);
}
setContentView(R.layout.activity_maps);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */,
this /* OnConnectionFailedListener */)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle connectionHint) {
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult result) {
Log.d(TAG, result.getErrorMessage());
}
#Override
public void onConnectionSuspended(int cause) {
Log.d(TAG, "Play services connection suspended");
}
}

togglebutton state changes when listview is scrolled down in android?

i have placed a textview and a toggle button into a list view by using the following xml file and i have used an arrayadapter to set it on to my layout, my problem is when i scroll down in the list view by unchecking a few toggle buttons (which are all set to be checked by default), they go back to default state and few others change state. As i want to fetch the state of the toggle button in my later stages its very important to stick on to the state that ive assigned to the toggle button. Please help to resolve this problem. Here are my xml file and the java code i use to set it on to the adapter. thank you in prior...
xml file that is named listdecor is included here
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/lvlistdecor"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#000000"
android:orientation="horizontal"
android:weightSum="2" >
<TextView
android:id="#+id/tvlistdecor"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1.5"
android:ellipsize="marquee"
android:singleLine="true"
android:text="sample"
android:textColor="#FFFFFF"
android:textSize="24sp"
android:typeface="sans" />
<CheckBox
android:id="#+id/cbusn_checked"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginRight="6sp"
android:layout_weight="0.5"
android:checked="true"
android:focusable="false"
android:padding="10dp" />
</LinearLayout>
Sir i made certain changes and also included the custom adapter to the listview and also changed to CheckBox instead of toggle buttons. but now the entire list view is not visible on my emulator. i've included my edited java class and xml file, please suggest me the changes, thank you...
The modified java code is included here
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); // Setting the window to full screen Step 1
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN); // Setting the window to full screen Step 2
setContentView(R.layout.attendance5);
facid = (TextView) findViewById(R.id.tvfacid);
facname = (TextView) findViewById(R.id.tvfacname);
subjectchosen = (TextView) findViewById(R.id.tvsubject);
// llattendlist = (LinearLayout)findViewById(R.id.llattendlist);
String Uid = getIntent().getStringExtra("Uid");
facid.setText(Uid);
String Name = getIntent().getStringExtra("Name");
facname.setText(Name);
String Sub = getIntent().getStringExtra("Sub");
subjectchosen.setText(Sub);
Attendusn = getIntent().getExtras();
if(Attendusn!=null)
{
AttendStud_usn = (ArrayList<String>)Attendusn.getStringArrayList("AttendStud_usn");
}
String AttendLen = String.valueOf(AttendStud_usn.size());
//int flag = 0 ;
//subjectchosen.setText(String.valueOf(AttendStud_usn));
myListView = (ListView) findViewById(R.id.lvnames);
// myListView.setAdapter(new ArrayAdapter<String>(this, R.layout.listdecoration,R.id.tvlistdecor, AttendStud_usn));
//ArrayAdapter<String> MyAdapter= new ArrayAdapter<String>(this,R.layout.listdecoration, R.id.tvlistdecor,AttendStud_usn);
//myListView.setAdapter(MyAdapter);
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View item, int position,
long id) {
// TODO Auto-generated method stub
Stud_usn usn= MyAdapter.getItem(position);
usn.toggleChecked();
Stud_usnViewHolder vh_usn= (Stud_usnViewHolder) item.getTag();
vh_usn.getCheckBox().setChecked(usn.isChecked());
}
});
MyAdapter = new Stud_Adapter(this,AttendStud_usn);
myListView.setAdapter(MyAdapter);
}
private static class Stud_usn{
private String usn_no="";
private boolean checked=true;
public Stud_usn(String usn_no){
this.usn_no = usn_no;
}
public String getUsn(){
return usn_no;
}
public void setChecked(boolean checked){
this.checked=checked;
}
public Object isChecked() {
// TODO Auto-generated method stub
return checked;
}
public String toString(){
return usn_no;
}
public void toggleChecked() {
// TODO Auto-generated method stub
checked = !checked;
}
}
private static class Stud_usnViewHolder{
private CheckBox checkbox;
private TextView textview;
public Stud_usnViewHolder(TextView textview, CheckBox checkbox){
this.checkbox=checkbox;
this.textview=textview;
}
public CheckBox getCheckBox() {
// TODO Auto-generated method stub
return checkbox;
}
public TextView getTextView(){
return textview;
}
}
private static class Stud_Adapter extends ArrayAdapter<Stud_usn>{
public LayoutInflater inflater;
public Stud_Adapter(Context context, List<String> attendStud_usn) {
super(context,R.layout.listdecoration,R.id.tvlistdecor);
// TODO Auto-generated constructor stub
inflater = LayoutInflater.from(context);
}
public View getView(int position, View convertView, ViewGroup parent){
Stud_usn usn = (Stud_usn) this.getItem(position);
CheckBox checkbox;
TextView textview;
if(convertView == null){
convertView = inflater.inflate(R.layout.listdecoration,null);
textview = (TextView) convertView.findViewById(R.id.tvlistdecor);
checkbox = (CheckBox) convertView.findViewById(R.id.cbusn_checked);
}
return convertView;
}
}
}
The view objects are recycled. You have to store that info sepperately. Not in the view but in the with the data you use in the adapter. When generating the views use this info to set the button state again.
You have to implement a custom adapter. Use the BaseAdapter class.

GWT - button inside v3 google maps infowindow

I am trying to figure out how to propagate events for components inside google maps InfoWindow.
I create anchor or a button and want to handle click event on any of those.
I have found solutions described here
and
here
but those both are using google maps wrappers for gwt.
I would like to avoid those libraries.
QUESTION:
Do you know any way how can I propagate those events from info window to some GWT panel which wraps google maps?
Based on code found here:
http://gwt-maps3.googlecode.com/svn/trunk/src/com/googlecode/maps3/client/
I have created this class that solves problem with using no external library (you have to take Only InfoWindowJSO source from link given)
And then instead passing InnerHtml as string to setContent... you just pass Widget element.
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.ui.ComplexPanel;
import com.google.gwt.user.client.ui.Widget;
public class InfoWindow
{
static class FakePanel extends ComplexPanel
{
public FakePanel(Widget w)
{
w.removeFromParent();
getChildren().add(w);
adopt(w);
}
#Override
public boolean isAttached()
{
return true;
}
public void detachWidget()
{
this.remove(0);
}
}
/** */
InfoWindowJSO jso;
/** If we have a widget, this will exist so we can detach later */
FakePanel widgetAttacher;
/** Keep track of this so we can get it again later */
Widget widgetContent;
/** */
public InfoWindow()
{
this.jso = InfoWindowJSO.newInstance();
}
/** */
public InfoWindow(InfoWindowOptions opts)
{
this.jso = InfoWindowJSO.newInstance(opts);
}
/** Detaches the handler and closes */
public void close()
{
this.detachWidget();
this.jso.close();
}
/** Detaches the content widget, if it exists */
private void detachWidget()
{
if (this.widgetAttacher != null)
{
this.widgetAttacher.detachWidget();
this.widgetAttacher = null;
}
}
/** */
public void open(JavaScriptObject map)
{
this.jso.open(map);
}
public void open(JavaScriptObject map, JavaScriptObject marker)
{
this.jso.open(map, marker);
}
/** */
public void setOptions(InfoWindowOptions value)
{
this.jso.setOptions(value);
}
/** */
public void setContent(String value)
{
this.widgetContent = null;
this.detachWidget();
this.jso.setContent(value);
}
/** */
public void setContent(Element value)
{
this.widgetContent = null;
this.detachWidget();
this.jso.setContent(value);
}
/** */
public void setContent(Widget value)
{
this.widgetContent = value;
this.detachWidget();
this.jso.setContent(value.getElement());
if (this.widgetAttacher == null)
{
// Add a hook for the close button click
this.jso.addListener("closeclick", new Runnable() {
#Override
public void run()
{
detachWidget();
}
});
this.widgetAttacher = new FakePanel(value);
}
else if (this.widgetAttacher.getWidget(0) != value)
{
this.widgetAttacher.detachWidget();
this.widgetAttacher = new FakePanel(value);
}
}
/** #return the widget, if a widget was set */
public Widget getContentWidget()
{
return this.widgetContent;
}
/** */
public JavaScriptObject getPosition()
{
return this.jso.getPosition();
}
/** */
public void setPosition(JavaScriptObject value)
{
this.jso.setPosition(value);
}
/** */
public int getZIndex()
{
return this.jso.getZIndex();
}
/** */
public void setZIndex(int value)
{
this.jso.setZIndex(value);
}
/** */
public void addListener(String whichEvent, Runnable handler)
{
this.jso.addListener(whichEvent, handler);
}
}
A. Browser events bubble all the way to the top of the DOM tree. You can attach your click handlers to a widget that is parent to both the maps InfoWindow and your widget. Then, when a user clicks on your button, you need to check for the source of event to make sure it came from your button.
public void onClick(final ClickEvent event) {
Element e = Element.as(event.getNativeEvent().getEventTarget());
// check if e is your button
}
B. You can create a regular GWT button, attach a ClickHandler to it. Do not put it inside the InfoWindow: place it on top it using absolute positioning and a higher z-index.
I use the static value nextAnchorId to uniquely generate IDs for each InfoWindow, and when the InfoWindow is ready (usually when you call infoWindow.open(map);), I get the anchor by element ID and add my click handler to it. This is kind of what Manolo is doing, but this implementation doesn't require gwtquery, which means that I can run my code in Super Dev Mode.
private static int nextAnchorId = 1;
public InfoWindow makeInfo() {
InfoWindowOptions infoWindowOptions = InfoWindowOptions.create();
FlowPanel infoContentWidget = new FlowPanel();
final String theAnchorId_str = "theAnchor" + nextAnchorId;
HTML theAnchor = new HTML("<a id=\"" + theAnchorId_str + "\">Click me!</a>");
infoContentWidget.add(theAnchor);
infoWindowOptions.setContent(infoContentWidget.getElement());
InfoWindow infoWindow = InfoWindow.create(infoWindowOptions);
infoWindow.addDomReadyListenerOnce(new InfoWindow.DomReadyHandler() {
#Override
public void handle() {
com.google.gwt.user.client.Element muffinButton = (com.google.gwt.user.client.Element) Document.get().getElementById(theAnchorId_str);
DOM.sinkEvents(muffinButton, Event.ONCLICK);
DOM.setEventListener(muffinButton, new EventListener() {
#Override
public void onBrowserEvent(Event event) {
Window.alert("You clicked on the anchor!");
// This is where your click handling for the link goes.
}
});
}
});
nextAnchorId++;
return infoWindow
}
A very simple solution is to use gwtquery:
Identify the anchor in the map you want to add the click handler and define a css selector for that (for instance id=my_link)
Use gquery to locate it and to add the event.
$('#my_link').click(new Function() {
public boolean f(Event e) {
[...]
return false; //false means stop propagation and prevent default
}
});
Note that gwtquery is not a wrapper of jquery but an entire gwt implementation of its api, so including it in your project will not overload it, and the compiler will pick up just the stuff you use.

How to add a JDialog in to desktop pane or just call from an internal frame

I am working on a project that uses MDI form in java. I have created a frame and then added a desktop pane to it. My project uses lot of internal frames. Also those internal frames require to show custom dialogs that i have created on my own. for it to be clear, i say, one jdialog has a table asking the user to select one row. but the problem is when i call the jdialog from the internal frame (with modality=true), the dialog is show on the top of main frame and not just on the top of internal frame. This makes it impossible to minimize the window when the jdialog is showing.
In my view there are 2 possible solutions (which may not possible!!).. Either the jdialog should be shown inside the dektop pane or i should create an internal frame instead of jdialog and make it appear to be modal to the parent internal frame. i.e, when i want to show the dialog, i may disable the internal frame and set the form unable to focus and then show a new internal frame on the top of this internal frame. I have been searching the forums for weeks.. but i couldn't find an answer. I hope you would have a solution. Thanks in advance, sir.
I also had the same problem, while working on a java project that works quite fine in java 6 but shown the same problem when changed to java7.
I found a solution.
I added a
dialog.setVisible(false) followed by a dialog.setVisible(true).
Then the dialog is responding to keyboard.
I am also working on an MDI app that uses a lof internal frames which show custom dialogs. I make my dialogs non-modal so that the internal frames can be iconified and/or the whole desktoppane can be minimized while the dialogs remain visible.
If you absolutely need modal behavior (i.e., you want to require the user to interact with a dialog before doing anything else) perhaps you can leave the dialog modeless but code in de facto modality.
Also, have you looked at the behavior of
setModalityType(java.awt.Dialog.ModalityType.DOCUMENT_MODAL);
?
Wow!! I got the answer from webbyt... Just avoid using internal frames.. try using the class ModalityInternalFrame (subclass of JinternalFrame).. and everything works fine.. Here is the class
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
/**
* An extended
* <code>JInternalFrame</code> that provides modality in a child/parent
* hierarchy
*
* #author webbyit
*/
public class ModalityInternalFrame extends JInternalFrame {
protected JDesktopPane desktopPane;
protected JComponent parent;
protected ModalityInternalFrame childFrame;
protected JComponent focusOwner;
private boolean wasCloseable;
public ModalityInternalFrame() {
init(); // here to allow netbeans to use class in gui builder
}
public ModalityInternalFrame(JComponent parent) {
this(parent, null);
}
public ModalityInternalFrame(JComponent parent, String title) {
this(parent, title, false);
}
public ModalityInternalFrame(JComponent parent, String title, boolean resizable) {
this(parent, title, resizable, false);
}
public ModalityInternalFrame(JComponent parent, String title, boolean resizable, boolean closeable) {
this(parent, title, resizable, closeable, false);
}
public ModalityInternalFrame(JComponent parent, String title, boolean resizable, boolean closeable,
boolean maximizable) {
this(parent, title, resizable, closeable, maximizable, false);
}
public ModalityInternalFrame(JComponent parent, String title, boolean resizable, boolean closeable,
boolean maximizable,
boolean iconifiable) {
super(title, resizable, closeable, maximizable, iconifiable);
setParentFrame(parent);
//setFocusTraversalKeysEnabled(false);
if (parent != null && parent instanceof ModalityInternalFrame) {
((ModalityInternalFrame) parent).setChildFrame(ModalityInternalFrame.this);
/*
* set focus to the new frame and show the frame Code added by Jasir
*/
try {
((ModalityInternalFrame) parent).setSelected(false);
setSelected(true);
setVisible(true);
} catch (PropertyVetoException ex) {
Logger.getLogger(ModalityInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
// Add glass pane
ModalityInternalGlassPane glassPane = new ModalityInternalGlassPane(this);
setGlassPane(glassPane);
// Add frame listeners
addFrameListener();
// Add frame veto listenr
addFrameVetoListener();
init();
// calculate size and position
}
private void setParentFrame(JComponent parent) {
desktopPane = JOptionPane.getDesktopPaneForComponent(parent);
this.parent = parent == null ? JOptionPane.getDesktopPaneForComponent(parent) : parent; // default to desktop if no parent given
}
public JComponent getParentFrame() {
return parent;
}
public void setChildFrame(ModalityInternalFrame childFrame) {
this.childFrame = childFrame;
}
public ModalityInternalFrame getChildFrame() {
return childFrame;
}
public boolean hasChildFrame() {
return (childFrame != null);
}
protected void addFrameVetoListener() {
addVetoableChangeListener(new VetoableChangeListener() {
public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException {
if (evt.getPropertyName().equals(JInternalFrame.IS_SELECTED_PROPERTY)
&& evt.getNewValue().equals(Boolean.TRUE)) {
if (hasChildFrame()) {
//childFrame.setSelected(true);
if (childFrame.isIcon()) {
childFrame.setIcon(false);
}
throw new PropertyVetoException("no!", evt);
}
}
}
});
}
/**
* Method to control the display of the glass pane, dependant on the frame
* being active or not
*/
protected synchronized void addFrameListener() {
addInternalFrameListener(new InternalFrameAdapter() {
#Override
public void internalFrameActivated(InternalFrameEvent e) {
if (hasChildFrame() == true) {
getGlassPane().setVisible(true);
grabFocus();
} else {
getGlassPane().setVisible(false);
}
}
#Override
public void internalFrameOpened(InternalFrameEvent e) {
getGlassPane().setVisible(false);
try {
setSelected(true);
} catch (PropertyVetoException ex) {
Logger.getLogger(ModalityInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public void internalFrameClosing(InternalFrameEvent e) {
if (parent != null && parent instanceof ModalityInternalFrame) {
((ModalityInternalFrame) parent).childClosing();
}
}
});
}
/**
* Method to handle child frame closing and make this frame available for
* user input again with no glass pane visible
*/
protected void childClosing() {
setClosable(wasCloseable);
getGlassPane().setVisible(false);
if (focusOwner != null) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
moveToFront();
setSelected(true);
focusOwner.grabFocus();
} catch (PropertyVetoException ex) {
}
}
});
focusOwner.grabFocus();
}
getGlassPane().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
setChildFrame(null);
getDesktopPane().setSelectedFrame(this);
System.out.println(getDesktopPane().getSelectedFrame());
}
/*
* Method to handle child opening and becoming visible.
*/
protected void childOpening() {
// record the present focused component
wasCloseable = isClosable();
setClosable(false);
focusOwner = (JComponent) getMostRecentFocusOwner();
grabFocus();
getGlassPane().setVisible(true);
getGlassPane().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
#Override
public void show() {
if (parent != null && parent instanceof ModalityInternalFrame) {
// Need to inform parent its about to lose its focus due
// to child opening
((ModalityInternalFrame) parent).childOpening();
}
calculateBounds();
super.show();
}
protected void init() {
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 394, Short.MAX_VALUE));
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 274, Short.MAX_VALUE));
pack();
}
public void calculateBounds() {
Dimension frameSize = getPreferredSize();
Dimension parentSize = new Dimension();
Dimension rootSize = new Dimension(); // size of desktop
Point frameCoord = new Point();
if (desktopPane != null) {
rootSize = desktopPane.getSize(); // size of desktop
frameCoord = SwingUtilities.convertPoint(parent, 0, 0, desktopPane);
parentSize = parent.getSize();
}
//setBounds((rootSize.width - frameSize.width) / 2, (rootSize.height - frameSize.height) / 2, frameSize.width, frameSize.height);
// We want dialog centered relative to its parent component
int x = (parentSize.width - frameSize.width) / 2 + frameCoord.x;
int y = (parentSize.height - frameSize.height) / 2 + frameCoord.y;
// If possible, dialog should be fully visible
int ovrx = x + frameSize.width - rootSize.width;
int ovry = y + frameSize.height - rootSize.height;
x = Math.max((ovrx > 0 ? x - ovrx : x), 0);
y = Math.max((ovry > 0 ? y - ovry : y), 0);
setBounds(x, y, frameSize.width, frameSize.height);
}
/**
* Glass pane to overlay. Listens for mouse clicks and sets selected on
* associated modal frame. Also if modal frame has no children make class
* pane invisible
*/
class ModalityInternalGlassPane extends JComponent {
private ModalityInternalFrame modalFrame;
public ModalityInternalGlassPane(ModalityInternalFrame frame) {
modalFrame = frame;
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (modalFrame.isSelected() == false) {
try {
modalFrame.setSelected(true);
if (modalFrame.hasChildFrame() == false) {
setVisible(false);
}
} catch (PropertyVetoException e1) {
//e1.printStackTrace();
}
}
}
});
}
#Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(new Color(255, 255, 255, 100));
g.fillRect(0, 0, getWidth(), getHeight());
}
}
}
But there are some problems still with focus and something else..