How to write android junit test case of expandablelist child view? - android-listview

I want write test case for ExpandableListView child view.
I have a 5 group of Expandable list view. Every group has individual child layout. So every time it would be child count is 1.
I want settext of AutoCompleteTextView for mAcTxtCarName using
TouchUtils.tapView(this, mAcTxtCarName);
sendKeys(KeyEvent.KEYCODE_H, KeyEvent.KEYCODE_U);
But i could not sendkeys like this.
This is code which i am using.
In this code, at assertSame(view, expandedView); not found same.
public void testStartCheckListActivity() throws Exception {
// add monitor to check for the second activity
final ActivityMonitor monitor = getInstrumentation().addMonitor(
CheckListActivity.class.getName(), null, false);
// find button and click it
final Button btnNewCalibration = (Button) mMenuActivity
.findViewById(R.id.btn_new_calibration);
// TouchUtils handles the sync with the main thread internally
TouchUtils.clickView(this, btnNewCalibration);
// wait 2 seconds for the start of the activity
final CheckListActivity checkListActivity = (CheckListActivity) monitor
.waitForActivityWithTimeout(2000);
assertNotNull(checkListActivity);
/** **New Calibration** */
// add monitor to check for the second activity
final ActivityMonitor monitorNewCalibration = getInstrumentation().addMonitor(
NewCalibrationActivity.class.getName(), null, false);
// find button and click it
final Button btnCheckListNext = (Button) checkListActivity
.findViewById(R.id.btn_footer_done);
TouchUtils.clickView(this, btnCheckListNext);
// wait 2 seconds for the start of the activity
final NewCalibrationActivity newCalibrationActivity = (NewCalibrationActivity) monitorNewCalibration
.waitForActivityWithTimeout(2000);
assertNotNull(newCalibrationActivity);
/** we get list view */
final ExpandableListView expandableListView = (ExpandableListView) newCalibrationActivity
.findViewById(R.id.explist_newcalibration);
newCalibrationActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
expandableListView.requestFocus();
expandableListView.performItemClick(expandableListView, 2,
expandableListView.getItemIdAtPosition(2));
}
});
JunitUtils.waitTime(10);
// *******get last calibration or validation details for default
// display.**********
final PreferencesStorage preferncesStorage = new PreferencesStorage();
// New Calibration Details object from preference storage.
final NewCalibrationDetails calibrationDetails = preferncesStorage
.getNewCalibrationDetails(newCalibrationActivity);
final SQLAdapter adapter = new SQLAdapter(newCalibrationActivity);
adapter.open();
adapter.getLastCalibrationDetails(calibrationDetails);
adapter.close();
// **************************************************************************
if (expandableListView.isGroupExpanded(2)) {
Logger.d(tag, "$$$$$$$$$$$$$$$$$$$$$$$$$$$");
final LayoutInflater mLayoutInflater = (LayoutInflater) newCalibrationActivity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View view = mLayoutInflater.inflate(R.layout.items_newcalibration_child_3,
expandableListView, false);
// final View view = View.inflate(newCalibrationActivity,
// R.layout.items_newcalibration_child_3, null);
AutoCompleteTextView mAcTxtCarName = (AutoCompleteTextView) view
.findViewById(R.id.actxt_car_name);
AutoCompleteTextView mAcTxtModelNumber = (AutoCompleteTextView) view
.findViewById(R.id.actxt_model_number);
EditText mEdTxtLicencePlate1 = (EditText) view.findViewById(R.id.et_licence_plate_1);
EditText mEdTxtLicencePlate2 = (EditText) view.findViewById(R.id.et_licence_plate_2);
EditText mEdTxtLicencePlate3 = (EditText) view.findViewById(R.id.et_licence_plate_3);
AutoCompleteTextView mAcTxtOdometerValue = (AutoCompleteTextView) view
.findViewById(R.id.actxt_odometer_value);
AutoCompleteTextView mAcTxtReportingCode = (AutoCompleteTextView) view
.findViewById(R.id.actxt_reporting_code);
final NewCalibrationAdapter calibrationAdapter = new NewCalibrationAdapter(
newCalibrationActivity, calibrationDetails);
final View expandedView = calibrationAdapter.getChildView(2, 0, true, view,
expandableListView);
assertSame(view, expandedView);
mAcTxtCarName.requestFocus();
TouchUtils.tapView(this, mAcTxtCarName);
sendKeys(KeyEvent.KEYCODE_H, KeyEvent.KEYCODE_U);
getInstrumentation().waitForIdleSync();
}
else {
Logger.e(tag, "##############", null);
}
}

Related

How to get Menu or MenuItem width in JavaFX?

I am extending the default Menu and MenuItem class to add some animated effects to it.
The problem is that I need to know the width and height of the Menu and MenuItem I'm working on. This classes doesn't extend Node or Region so there are no public methods to get their size. The size is composed by the text size inside the MenuItem plus the corresponding default padding, I can calculate how much space the text takes, but I can't get how much padding the MenuItem has neither.
There is a method called impl_styleableGetNode() that returns a Node but it always returns null for me.
Is there anyway to get the size? MenuBar also doesn't seems to expose any helpful method for this.
EDIT:
Here is my class, I'm trying to implement this material design button into the Menu class. Basically I render all the button using the setGraphic() method. It's working perfectly but I'm using the Pane width which doesn't take into account the padding of the Menu so the effect is not complete.
public class MaterialDesignMenu extends Menu {
private Pane stackPane = new Pane();
private Label label = new Label();
private Circle circleRipple;
private Rectangle rippleClip = new Rectangle();
private Duration rippleDuration = Duration.millis(250);
private double lastRippleHeight = 0;
private double lastRippleWidth = 0;
private Color rippleColor = new Color(1, 0, 0, 0.3);
public MaterialDesignMenu() {
init("");
}
public MaterialDesignMenu(String text) {
init(text);
}
public MaterialDesignMenu(String text, Node graphic) {
init(text);
}
private void init(String text){
label.setText(text);
createRippleEffect();
stackPane.getChildren().addAll(circleRipple, label);
setGraphic(stackPane);
}
private void createRippleEffect() {
circleRipple = new Circle(0.1, rippleColor);
circleRipple.setOpacity(0.0);
// Optional box blur on ripple - smoother ripple effect
//circleRipple.setEffect(new BoxBlur(3, 3, 2));
// Fade effect bit longer to show edges on the end of animation
final FadeTransition fadeTransition = new FadeTransition(rippleDuration, circleRipple);
fadeTransition.setInterpolator(Interpolator.EASE_OUT);
fadeTransition.setFromValue(1.0);
fadeTransition.setToValue(0.0);
final Timeline scaleRippleTimeline = new Timeline();
final SequentialTransition parallelTransition = new SequentialTransition();
parallelTransition.getChildren().addAll(
scaleRippleTimeline,
fadeTransition
);
// When ripple transition is finished then reset circleRipple to starting point
parallelTransition.setOnFinished(event -> {
circleRipple.setOpacity(0.0);
circleRipple.setRadius(0.1);
});
stackPane.addEventHandler(MouseEvent.MOUSE_PRESSED, event -> {
parallelTransition.stop();
// Manually fire finish event
parallelTransition.getOnFinished().handle(null);
circleRipple.setCenterX(event.getX());
circleRipple.setCenterY(event.getY());
// Recalculate ripple size if size of button from last time was changed
if (stackPane.getWidth() != lastRippleWidth || stackPane.getHeight() != lastRippleHeight) {
lastRippleWidth = stackPane.getWidth();
lastRippleHeight = stackPane.getHeight();
rippleClip.setWidth(lastRippleWidth);
rippleClip.setHeight(lastRippleHeight);
/*
// try block because of possible null of Background, fills ...
try {
rippleClip.setArcHeight(stackPane.getBackground().getFills().get(0).getRadii().getTopLeftHorizontalRadius());
rippleClip.setArcWidth(stackPane.getBackground().getFills().get(0).getRadii().getTopLeftHorizontalRadius());
circleRipple.setClip(rippleClip);
} catch (Exception e) {
e.printStackTrace();
}*/
circleRipple.setClip(rippleClip);
// Getting 45% of longest button's length, because we want edge of ripple effect always visible
double circleRippleRadius = Math.max(stackPane.getHeight(), stackPane.getWidth()) * 0.45;
final KeyValue keyValue = new KeyValue(circleRipple.radiusProperty(), circleRippleRadius, Interpolator.EASE_OUT);
final KeyFrame keyFrame = new KeyFrame(rippleDuration, keyValue);
scaleRippleTimeline.getKeyFrames().clear();
scaleRippleTimeline.getKeyFrames().add(keyFrame);
}
parallelTransition.playFromStart();
});
}
public void setRippleColor(Color color) {
circleRipple.setFill(color);
}
}
First you have to listen to parentPopupProperty changes of MenuItem. When you get the instance of parent popup than register listener for skinProperty of ContextMenu (parentPopup). When you get the skin then you can get MenuItemContainer which is Node equivalent of MenuItem and you can listen to widthProperty or heightProperty changes of MenuItemContainer.
Note: skinProperty change is fired just before ContextMenu is shown on the screen.
Custom class extending MenuItem class:
public class CstMenuItem extends MenuItem {
public CstMenuItem() {
// Create custom menu item listener.
new CstMenuItemListener(this);
}
/*
* Returns MenuItemContainer node associated with this menu item
* which can contain:
* 1. label node of type Label for displaying menu item text,
* 2. right node of type Label for displaying accelerator text,
* or an arrow if it's a Menu,
* 3. graphic node for displaying menu item icon, and
* 4. left node for displaying either radio button or check box.
*
* This is basically rewritten impl_styleableGetNode() which
* should not be used since it's marked as deprecated.
*/
public ContextMenuContent.MenuItemContainer getAssociatedNode() {
ContextMenu contextMenu = getParentPopup();
ContextMenuSkin skin = (ContextMenuSkin) contextMenu.getSkin();
ContextMenuContent content = (ContextMenuContent) skin.getNode();
// Items container contains MenuItemContainer nodes and Separator nodes.
Parent itemsContainer = content.getItemsContainer();
List<Node> children = itemsContainer.getChildrenUnmodifiable();
for (Node child : children) {
if (child instanceof ContextMenuContent.MenuItemContainer) {
ContextMenuContent.MenuItemContainer menuItemContainer =
(ContextMenuContent.MenuItemContainer) child;
if (menuItemContainer.getItem() == this) {
return menuItemContainer;
}
}
}
return null;
}
}
Custom MenuItem listener class:
public class CstMenuItemListener implements ChangeListener {
private CstMenuItem menuItem;
private ContextMenu parentPopup;
private Region menuItemContainer;
public CstMenuItemListener(CstMenuItem menuItem) {
this.menuItem = menuItem;
menuItem.parentPopupProperty().addListener(this);
}
#Override
public void changed(ObservableValue observable, Object oldValue, Object newValue) {
if (observable == menuItem.parentPopupProperty()) {
parentPopup = (ContextMenu) newValue;
parentPopup.skinProperty().addListener(this);
} else if (observable == parentPopup.skinProperty()) {
menuItemContainer = menuItem.getAssociatedNode();
menuItemContainer.widthProperty().addListener(this);
menuItemContainer.heightProperty().addListener(this);
} else if (observable == menuItemContainer.widthProperty()) {
System.out.println("width: " + (double) newValue);
} else if (observable == menuItemContainer.heightProperty()) {
System.out.println("height: " + (double) newValue);
}
}
}

1 time run activity when app is installed

i want privacy policy , disclaimer statement and a color picker as 1 time run activity when the app is installed . So how can i use persistent storage so that when we install and run the app for the first time privacy policy runs then clicking on button(next) goes to disclaimer activity then to color picker and finally to main activity. And when second time app is run it directly goes to main activity.
MAIN ACTIVITY:
public static final String PREFS_NAME = "MyPrefsFile"; // Name of prefs file; don't change this after it's saved something
//public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); // Get preferences file (0 = no option flags set)
boolean firstRun = settings.getBoolean("firstRun", false); // Is it first run? If not specified, use "true"
if (firstRun == false) {
Log.w("activity", "first time");
setContentView(R.layout.activity_gasfurnancediagnostics);
SharedPreferences.Editor editor = settings.edit(); // Open the editor for our settings
editor.putBoolean("firstRun", false); // It is no longer the first run
editor.apply(); // Save all changed settings
return;
} else {
Log.w("activity", "second time");
checkColor();
setContentView(R.layout.activity_theme);
return;
}
// setContentView(R.layout.activity_main);
//*** CHECKING COLOR IF IT WAS SET PREVIOUSLY ***/
}
public void checkColor()
{
// INITIALIZING THE SHARED PREFRENECES
SharedPreferences pref = getApplicationContext().getSharedPreferences("Colors", 0);
// CHECK IF WE HAVE COLOR_SET VALIRABLE IF NOT DEFAULT WILL BE 0
int color_set = pref.getInt("color_set", 0);
if(color_set==0){
Intent e = new Intent(getApplicationContext(), ThemeActivity.class);
startActivity(e);
return;
}
if(color_set==1)
{ // IF IT IS ALREADY SET IN THE PREVIOUS THAN THIS CAN BE USED FOR REDIRECTING TO OTHER CONTROLLER AND THE BELOW FUNCTIONS CAN BE USED IN THAT CONTROLLER FOR COLOR MODIFICATIUON
String color = pref.getString("color", null); // COLOR CODE
ActionBar mActionBar = getActionBar(); // GETTING ACTIONBAR
//final Button testbutn = (Button) findViewById(R.id.testbtn); // GETTING BUTTON
if (color.equals("red")) {
mActionBar.setBackgroundDrawable(new ColorDrawable(0xFFBA1E1E)); // CHANGES ACTION BAR COLOR
// testbutn.setBackgroundColor(0xFFFF6666);
// CHANGES BUTTON COLOR
} else if (color.equals("blue")) {
mActionBar.setBackgroundDrawable(new ColorDrawable(0xFF21a4dd)); // CHANGES ACTION BAR COLOR
// testbutn.setBackgroundColor(0xFFFF4B7E); // CHANGES BUTTON COLOR
}
else if (color.equals("yellow")) {
mActionBar.setBackgroundDrawable(new ColorDrawable(0xFFF6D72B)); // CHANGES ACTION BAR COLOR
// testbutn.setBackgroundColor(0xFFFF4B7E); // CHANGES BUTTON COLOR
}
mActionBar.setDisplayShowTitleEnabled(false); // THESE TWO STEPS ARE REQUIRED AFTER CHANGING THE ACTION BAR COLOR
mActionBar.setDisplayShowTitleEnabled(true); // THESE TWO STEPS ARE REQUIRED AFTER CHANGING THE ACTION BAR COLOR
}
GAS FURNANCE ACTIVITY
Button btnnext = (Button)findViewById(R.id.nextbtn);
btnnext.setOnClickListener((OnClickListener) this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(parent.getContext(), "Button Clicked"+ dataModel.getName(),Toast.LENGTH_LONG).show();
//Intent yes= new Intent(parent.getContext(), yes(dataModel.getName().class));
switch(v.getId())
{
case R.id.nextbtn:
Intent a = new Intent(getApplicationContext(), MainActivity.class);
startActivity(a);
break;
default:
}
}
package com.example.gasfurnancediagnostics;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class ThemeActivity extends Activity implements ColorPicker.OnColorChangedListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_theme);
Button blueBtn = (Button) findViewById(R.id.bluebtn);
blueBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//***** PERSISTANCE STORAGE INITIALIZATION****/
SharedPreferences pref = getApplicationContext().getSharedPreferences("Colors", 0);
// **** PERSISTANCE STORAGE EDITOR *** /
SharedPreferences.Editor editor = pref.edit();
editor.putString("color", "blue");
//**** DEFINING THE VALUE THAT THE COLOR IS ALREADY SET SO THAT WE CAN OMIT THIS ACTIVITY ***/
editor.putInt("color_set", 1);
//*** COMMITING ALL THE DETAILS TO THE STORAGE...
//** NOTE WITHOUT THIS THE DATA WONT BE SAVED
editor.commit();
Intent e = new Intent(getApplicationContext(), MainActivity.class);
startActivity(e);
}
});
Button redBtn = (Button) findViewById(R.id.redbtn);
redBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//***** PERSISTANCE STORAGE INITIALIZATION****/
SharedPreferences pref = getApplicationContext().getSharedPreferences("Colors", 0);
// **** PERSISTANCE STORAGE EDITOR *** /
SharedPreferences.Editor editor = pref.edit();
editor.putString("color", "red");
//**** DEFINING THE VALUE THAT THE COLOR IS ALREADY SET SO THAT WE CAN OMIT THIS ACTIVITY ***/
editor.putInt("color_set", 1);
//*** COMMITING ALL THE DETAILS TO THE STORAGE...
//** NOTE WITHOUT THIS THE DATA WONT BE SAVED
editor.commit();
Intent e = new Intent(getApplicationContext(), MainActivity.class);
startActivity(e);
}
});
Button yellowBtn = (Button) findViewById(R.id.yellowbtn);
yellowBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//***** PERSISTANCE STORAGE INITIALIZATION****/
SharedPreferences pref = getApplicationContext().getSharedPreferences("Colors", 0);
// **** PERSISTANCE STORAGE EDITOR *** /
SharedPreferences.Editor editor = pref.edit();
editor.putString("color", "yellow");
//**** DEFINING THE VALUE THAT THE COLOR IS ALREADY SET SO THAT WE CAN OMIT THIS ACTIVITY ***/
editor.putInt("color_set", 1);
//*** COMMITING ALL THE DETAILS TO THE STORAGE...
//** NOTE WITHOUT THIS THE DATA WONT BE SAVED
editor.commit();
Intent e = new Intent(getApplicationContext(), MainActivity.class);
startActivity(e);
}
});
}
#Override
public void colorChanged(String key, int color) {
// TODO Auto-generated method stub
}
}
SharedPreferences is what you are looking for,add this piece of code in your very first activity
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Boolean firstRun = preferences.getString("FirstRun",true);
if(true)
{
/*Open your activity here which you want to open for only once*/
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("FirstRun",false);
editor.apply();
}
else
{
/*Open your activity which you want to open later,generally*/
}
See this for detailed explaination and this

Is there a way to fill a listview in activity2 with info from a listview in activity1?

Activity 1 sends the info I want to Activity 2:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id)
{
// Get the cursor, positioned to the corresponding row in the result set
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
final int item_id = cursor.getInt(cursor.getColumnIndex(GamesDbAdapter.KEY_ROWID));
String item_cursus = cursor.getString(cursor.getColumnIndex(GamesDbAdapter.KEY_CURSUS));
String item_onderdeel = cursor.getString(cursor.getColumnIndex(GamesDbAdapter.KEY_ONDERDEEL));
String item_tijd = cursor.getString(cursor.getColumnIndex(GamesDbAdapter.KEY_TIJD));
String item_game = cursor.getString(cursor.getColumnIndex(GamesDbAdapter.KEY_GAME));
String item_web = cursor.getString(cursor.getColumnIndex(GamesDbAdapter.KEY_WEB));
Intent intent = new Intent(actGames_FRONT_ListViewCursorAdaptorActivity.this, actGames_ALL_ListViewCursorAdaptorActivity.class);
intent.putExtra("cursus", item_cursus);
intent.putExtra("id", item_id);
intent.putExtra("game", item_game);
startActivity(intent);
Toast done =
Toast.makeText(getApplicationContext(), item_game, Toast.LENGTH_LONG);
done.show();
}
});
In Activity2 I want to display "game" in another listview, but setText doesn't work with Listview.
game = (TextView)findViewById(R.id.game);
Intent iin= getIntent();
Bundle c = iin.getExtras();
if(c!=null)
{
String item_game =(String) c.get("game");
game.setText(item_game);
}
String game_list = getIntent().getExtras().getString("game");
This is the simplecursoradapter in activity2:
private void displayListView() {
Cursor cursor = dbHelper.fetchAllCursus();
// The desired columns to be bound
String[] cursus = new String[] {
GamesDbAdapter.KEY_CURSUS,
};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.front,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.games_row_front,
cursor,
cursus,
to,
0);
ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
And this is in my DBadapter:
public Cursor fetchGames(){
String[] args = {"********************" };
Cursor mCursor = mDb.query(SQLITE_TABLE, null,
"cursus = ?" , args, KEY_GAME, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
When I replace the *** with a static item from the database it works but I can't get it to work with the intent from the first activity. Is there a way to fill a listview with info from another listview in another activity?

Unable to load tab in PagerSlidingTabStrip when fragment is replaced

I'm trying to implement a viewpager with a PagerSlidingTabStrip instead of a TabView. The viewpager has three tabs in which each listview displays a list of events. The three tabs are called Past, Tonight and Future.
I've set up the slider as the github page suggests:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
View v = inflater.inflate(R.layout.all_events_main_strip, container, false);
// Set up the ViewPager, attaching the adapter and setting up a listener for when the
// user swipes between sections.
pager = (ViewPager) v .findViewById(R.id.pager_main);
tabs = (PagerSlidingTabStrip) v.findViewById(R.id.tabs);
adapter = new MyPagerAdapter(getFragmentManager());
pager.setAdapter(adapter);
tabs.setViewPager(pager);
// Set Present tab as default
pager.setCurrentItem(1);
return v;
}
When the app starts the Main Activity adds for the first time this fragment and everything works great. 3 swipeable tabs with 3 listviews. (c.f. code section)
Here is the problem:
I've noticed that when I press the back button and replace the fragment again, in order to reopen the viewpager, the tab in the middle doesn't show any listview. If I swype left or right the content in the other tabs is loaded and displayed but the Present Tab remains empty.
When I debug the ToNightEvents ListFragment isn't called at all.
Do you guys have any suggestions to solve the problem?
The code:
The code is structured as follows: After the onCreateView I've added an OnDestroyView method to remove the fragment but it didn't work... Then in the fragmentPagerAdapter each page is called as a fragment in the getItem method. Finally at the end of the code you can see the three ListFragment classes in which a listview is populated through an AsyncTask
public class FragmentAllEvents extends Fragment
{
private static final String TAG_UID = "uid";
private static final String TAG_LOGO = "logo";
private static final String TAG_POKUID = "pokuid";
static ArrayList<HashMap<String, String>> userList;
ArrayList<HashMap<String, String>> userListTotal;
private final Handler handler = new Handler();
HashMap<String, String> userSelected;
EventsFunctions eventsFunctions;
UserFunctions userFunctions;
static ListView lv;
ActionBar actionBar;
MyPagerAdapter adapter;
ViewPager pager;
PagerSlidingTabStrip tabs;
private Drawable oldBackground = null;
private int currentColor = 0xFF666666;
//Context context = this;
#Override public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Set up the action bar.
actionBar = getActivity().getActionBar();
actionBar.setHomeButtonEnabled(true);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
View v = inflater.inflate(R.layout.all_events_main_strip, container, false);
pager = (ViewPager) v .findViewById(R.id.pager_main);
tabs = (PagerSlidingTabStrip) v.findViewById(R.id.tabs);
adapter = new MyPagerAdapter(getFragmentManager());
pager.setAdapter(adapter);
tabs.setViewPager(pager);
pager.setCurrentItem(1);
return v;
}
#Override
public void onDestroyView()
{
super.onDestroyView();
getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
}
public static class MyPagerAdapter extends FragmentPagerAdapter
{
public MyPagerAdapter(FragmentManager fm)
{
super(fm);
}
#Override
public Fragment getItem(int i)
{
switch (i)
{
case 0:
return new PastEvents();
case 1:
return new ToNightEvents();
case 2:
return new FutureEvents();
/*default:
// The other sections of the app are dummy placeholders.
return new ToNightEvents();
*/
}
return null;
}
/**
* A fragment that launches past events list.
*/
public static class PastEvents extends ListFragment implements
PullToRefreshAttacher.OnRefreshListener
{
private ListView pastList;
private PullToRefreshAttacher mPullToRefreshAttacher;
ProgressBar progress;
String tabTime;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View pastView = inflater.inflate(R.layout.pastlist, container, false);
progress = (ProgressBar) pastView.findViewById(R.id.loading_spinner_past);
tabTime="past";
pastList = (ListView) pastView.findViewById(android.R.id.list);
// Now get the PullToRefresh attacher from the Activity. An exercise to the reader
// is to create an implicit interface instead of casting to the concrete Activity
mPullToRefreshAttacher = ((Home) getActivity()).getPullToRefreshAttacher();
// Now set the ScrollView as the refreshable view, and the refresh listener (this)
mPullToRefreshAttacher.addRefreshableView(pastList, this);
new AsyncLoadEvents(getActivity(), progress, pastList, mPullToRefreshAttacher).execute(tabTime);
return pastView;
}
#SuppressWarnings("unchecked")
#Override
public void onListItemClick(ListView listView, View view, int position, long id)
{
super.onListItemClick (listView, view, position, id);
HashMap<String, String> map = (HashMap<String, String>) getListView().getItemAtPosition(position);
//Log.e("AttendList Report", "Clicked list item: " + position +" Content: \n" + map.get(TAG_ID).toString());
Log.e("PastList Report", "Clicked list item: " + position +" Event's content: \n" + map.get(TAG_UID).toString());
Intent intent = new Intent(getActivity(), SingleEventActivity.class);
intent.putExtra("pokuid",map.get(TAG_POKUID)); // Maybe remove attribute toString();
intent.putExtra("uid", map.get(TAG_UID));
intent.putExtra("logo",map.get(TAG_LOGO));
getActivity().startActivity(intent);
}
#Override
public void onRefreshStarted(View view)
{
new AsyncLoadEvents(getActivity(), progress, pastList, mPullToRefreshAttacher).execute(tabTime);
}
}
/**
* A fragment that launches future event list.
*/
public static class FutureEvents extends ListFragment implements
PullToRefreshAttacher.OnRefreshListener
{
private ListView futureList;
private PullToRefreshAttacher mPullToRefreshAttacher;
ProgressBar progress;
String tabTime;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View futureView = inflater.inflate(R.layout.futurelist, container, false);
progress = (ProgressBar) futureView.findViewById(R.id.loading_spinner_future);
tabTime = "future";
futureList = (ListView) futureView.findViewById(android.R.id.list); //change to attendlist if needed
// Now get the PullToRefresh attacher from the Activity. An exercise to the reader
// is to create an implicit interface instead of casting to the concrete Activity
mPullToRefreshAttacher = ((Home) getActivity()).getPullToRefreshAttacher();
// Now set the ScrollView as the refreshable view, and the refresh listener (this)
mPullToRefreshAttacher.addRefreshableView(futureList, this);
new AsyncLoadEvents(getActivity(), progress, futureList, mPullToRefreshAttacher).execute(tabTime);
return futureView;
}
#SuppressWarnings("unchecked")
#Override
public void onListItemClick(ListView listView, View view, int position, long id)
{
super.onListItemClick (listView, view, position, id);
HashMap<String, String> map = (HashMap<String, String>) getListView().getItemAtPosition(position);
Log.e("PastList Report", "Clicked list item: " + position +" Event's content: \n" + map.get(TAG_UID).toString());
Intent intent = new Intent(getActivity(), SingleEventActivity.class);
intent.putExtra("pokuid",map.get(TAG_POKUID)); // Maybe remove attribute toString();
intent.putExtra("uid", map.get(TAG_UID));
intent.putExtra("logo",map.get(TAG_LOGO));
getActivity().startActivity(intent);
}
#Override
public void onRefreshStarted(View view)
{
new AsyncLoadEvents(getActivity(), progress, futureList, mPullToRefreshAttacher).execute(tabTime);
}
}
/**
* A fragment that launches future event list.
*/
public static class ToNightEvents extends ListFragment implements
PullToRefreshAttacher.OnRefreshListener
{
private ListView tonightList;
private PullToRefreshAttacher mPullToRefreshAttacher;
ProgressBar progress;
String tabTime;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View tonightView = inflater.inflate(R.layout.tonightlist, container, false);
progress = (ProgressBar) tonightView.findViewById(R.id.loading_spinner_tonight);
tabTime = "tonight";
tonightList = (ListView) tonightView.findViewById(android.R.id.list); //change to attendlist if needed
// Now get the PullToRefresh attacher from the Activity. An exercise to the reader
// is to create an implicit interface instead of casting to the concrete Activity
mPullToRefreshAttacher = ((Home) getActivity()).getPullToRefreshAttacher();
// Now set the ScrollView as the refreshable view, and the refresh listener (this)
mPullToRefreshAttacher.addRefreshableView(tonightList, this);
new AsyncLoadEvents(getActivity(), progress, tonightList, mPullToRefreshAttacher).execute(tabTime);
return tonightView;
}
#SuppressWarnings("unchecked")
#Override
public void onListItemClick(ListView listView, View view, int position, long id)
{
super.onListItemClick (listView, view, position, id);
HashMap<String, String> map = (HashMap<String, String>) getListView().getItemAtPosition(position);
Log.e("PastList Report", "Clicked list item: " + position +" Event's content: \n" + map.get(TAG_UID).toString());
Intent intent = new Intent(getActivity(), SingleEventActivity.class);
intent.putExtra("pokuid",map.get(TAG_POKUID)); // Maybe remove attribute toString();
intent.putExtra("uid", map.get(TAG_UID));
intent.putExtra("logo",map.get(TAG_LOGO));
getActivity().startActivity(intent);
}
#Override
public void onRefreshStarted(View view)
{
new AsyncLoadEvents(getActivity(), progress, tonightList, mPullToRefreshAttacher).execute(tabTime);
}
}
public String[] titles=
{
"Past",
"Tonight",
"Future"
};
#Override
public int getCount()
{
return titles.length;
}
#Override
public CharSequence getPageTitle(int position)
{
return titles[position];
}
}
}
This would normally work if you were in an Activity, however I guess you are in a Fragment since the code you posted is the method onCreateView(). The problem is that you are trying to use the FragmentManager of the Activity and you should be using the Fragment's FragmentManager. This FragmentManager is not what you need. Try this instead:
adapter = new MyPagerAdapter(getChildFragmentManager());
I think I'm a little bit late but if anyone happens to have the same error here is the solution =)
Q.
The following fixed it for me:
Add an OnBackStackChangedListener to the fragment manager.
In the onBackStackChanged method, get references to both the ViewPager and the PagerSlidingTabStrip (pager and tabs in your example). If the appropriate fragment is currently active, do the following:
pager.invalidate();
tabs.invalidate();
pager.setAdapter(new MyPagerAdapter(getFragmentManager()));
tabs.setViewPager(pager);

Redraw CellTable from MainPresenter after popup view is hidden

My MainPresenter has a CellTable with a button column. When u hit a button the presenter calls "addToPopupSlot(editPopup, true)". A editPopup appears with several settings u can make there. After pressing the save button on the popup view it sends data to the database which the CellTable in the MainPresenter wants to get.
My problem is: When I click on the save button, the table doesnt get updated. I have to either refresh the page or navigate from another Presenter back to the MainPresenter.
EditPopupPresenter
#Override
protected void onBind() {
super.onBind();
this.username = Cookies.getCookie("domusr");
// hours and minutes displayed in listboxes
for (int i = 0; i < TimeSettings.HOURS_RANGE; i++) {
getView().getBeginHoursLBX().addItem(String.valueOf(i));
getView().getEndHoursLBX().addItem(String.valueOf(i));
getView().getPauseHoursLBX().addItem(String.valueOf(i));
}
for (int i = 0; i < 60; i += TimeSettings.MINUTES_RANGE) {
getView().getBeginMinutesLBX().addItem(String.valueOf(i));
getView().getEndMinutesLBX().addItem(String.valueOf(i));
getView().getPauseMinutesLBX().addItem(String.valueOf(i));
}
getView().getSaveBTN().addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
DateTimeFormat dtf = DateTimeFormat.getFormat("yyyy-MM-dd");
final String startHours = getView()
.getBeginHoursLBX()
.getValue(
getView().getBeginHoursLBX().getSelectedIndex());
final String startMinutes = getView().getBeginMinutesLBX()
.getValue(
getView().getBeginMinutesLBX()
.getSelectedIndex());
final String endHours = getView().getEndHoursLBX().getValue(
getView().getEndHoursLBX().getSelectedIndex());
final String endMinutes = getView()
.getEndMinutesLBX()
.getValue(
getView().getEndMinutesLBX().getSelectedIndex());
final String pauseHours = getView()
.getPauseHoursLBX()
.getValue(
getView().getPauseHoursLBX().getSelectedIndex());
final String pauseMinutes = getView().getPauseMinutesLBX()
.getValue(
getView().getPauseMinutesLBX()
.getSelectedIndex());
final String projectId = getView().getProjectIdLBL().getText();
final java.sql.Date date = new java.sql.Date(dtf.parse(
getView().getDateLBL().getText()).getTime());
dispatcher.execute(
new InsertTimesIntoDB(Integer.parseInt(startHours),
Integer.parseInt(startMinutes), Integer
.parseInt(endHours), Integer
.parseInt(endMinutes), Integer
.parseInt(pauseHours), Integer
.parseInt(pauseMinutes), Integer
.parseInt(projectId), date, username),
new AsyncCallback<InsertTimesIntoDBResult>() {
#Override
public void onFailure(Throwable caught) {
}
#Override
public void onSuccess(InsertTimesIntoDBResult result) {
}
});
getView().hide();
}
});
}
editColumn in MainPresenter (onBind())
// edit column
Column<Booking, String> editColumn = new Column<Booking, String>(
new ButtonCell()) {
#Override
public String getValue(Booking booking) {
return "edit";
}
};
editColumn.setFieldUpdater(new FieldUpdater<Booking, String>() {
#Override
public void update(int index, Booking object, String value) {
// pop up widget addToSlot call
editPopup.getView().getDateLBL()
.setText(String.valueOf(object.getFullDate()));
editPopup.getView().getProjectIdLBL()
.setText(String.valueOf(1234567));
editPopup.getView().getBeginHoursLBX()
.setItemSelected(object.getStartHours(), true);
editPopup
.getView()
.getBeginMinutesLBX()
.setItemText(
minutesRange.getIndex(object
.getEndMinutes()),
String.valueOf(object.getStartMinutes()));
editPopup.getView().getEndHoursLBX()
.setItemSelected(object.getEndHours(), true);
editPopup
.getView()
.getEndMinutesLBX()
.setItemText(
minutesRange.getIndex(object
.getEndMinutes()),
String.valueOf(object.getEndMinutes()));
editPopup.getView().getPauseHoursLBX()
.setItemSelected(object.getPauseHours(), true);
editPopup
.getView()
.getPauseMinutesLBX()
.setItemText(
minutesRange.getIndex(object
.getEndMinutes()),
String.valueOf(object.getPauseMinutes()));
addToPopupSlot(editPopup, true);
}
});
getView().getTimeTable().addColumn(editColumn);
I think you have some solutions here. If I were you I would do next steps:
Create a listener of events in the MainPresenter.
When you finished
update your DB (after pressing save in your popup); I´d fire an
event.
When the MainPresenter receives the event, you go to the DB
and fetch the data (filtering it using getVisibleRange()).
Refresh the CellTable using setRowData(...) method (passing correctly the arguments)
Other option is create a ListDataProvider associate with the CellTable, and call refresh on it.