Javafx Task - update progress from a method - javafx

In a JavaFX application I wish to update a status bar according to some work logic which I've implemented in an other class.
I can't figure out how to combine my desire to pass to work logic to the method (and not to write it inside the task) and to know about the work progress percentage.
This is an example of the controller with the Task:
public class FXMLDocumentController implements Initializable {
#FXML private Label label;
#FXML ProgressBar progressBar;
#FXML
private void handleButtonAction(ActionEvent event) {
Service<Void> myService = new Service<Void>() {
#Override
protected Task<Void> createTask() {
return new Task<Void>() {
#Override
protected Void call() throws Exception {
try {
DatabaseFunctionality.performWorkOnDb();
//updateProgress(1, 1);
} catch (InterruptedException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
};
}
};
progressBar.progressProperty().bind(myService.progressProperty());
myService.restart();
}
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
}
This is the helper class:
public class DatabaseFunctionality {
public static void performWorkOnDb () throws InterruptedException {
for (int i = 1; i <= 100; i++) {
System.out.println("i=" + i);
Thread.sleep(100);
//Update progress
}
}
}
Thank you

You have a couple of options here. One is to do as Uluk suggests and expose an observable property in your DatabaseFunctionality class:
public class DatabaseFunctionality {
private final ReadOnlyDoubleWrapper progress = new ReadOnlyDoubleWrapper();
public double getProgress() {
return progressProperty().get();
}
public ReadOnlyDoubleProperty progressProperty() {
return progress ;
}
public void performWorkOnDb() throws Exception {
for (int i = 1; i <= 100; i++) {
System.out.println("i=" + i);
Thread.sleep(100);
progress.set(1.0*i / 100);
}
}
}
And now in your Task, you can observe that property and update the task's progress:
Service<Void> myService = new Service<Void>() {
#Override
protected Task<Void> createTask() {
return new Task<Void>() {
#Override
protected Void call() throws Exception {
try {
DatabaseFunctionality dbFunc = new DatabaseFunctionality();
dbFunc.progressProperty().addListener((obs, oldProgress, newProgress) ->
updateProgress(newProgress.doubleValue(), 1));
dbaseFunc.performWorkOnDb();
} catch (InterruptedException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
};
}
};
Another option (in case you don't want your data access object to depend on the JavaFX properties API) is to pass the data access object a callback to update the progress. A BiConsumer<Integer, Integer> would work for this:
public class DatabaseFunctionality {
private BiConsumer<Integer, Integer> progressUpdate ;
public void setProgressUpdate(BiConsumer<Integer, Integer> progressUpdate) {
this.progressUpdate = progressUpdate ;
}
public void performWorkOnDb() throws Exception {
for (int i = 1; i <= 100; i++) {
System.out.println("i=" + i);
Thread.sleep(100);
if (progressUpdate != null) {
progressUpdate.accept(i, 100);
}
}
}
}
and then
Service<Void> myService = new Service<Void>() {
#Override
protected Task<Void> createTask() {
return new Task<Void>() {
#Override
protected Void call() throws Exception {
try {
DatabaseFunctionality dbFunc = new DatabaseFunctionality();
dbFunc.setProgressUpdate((workDone, totalWork) ->
updateProgress(workDone, totalWork));
dbaseFunc.performWorkOnDb();
} catch (InterruptedException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
};
}
};

public void initialize() {
Task<Void> task = new Task<>() {
#Override
protected Void call() {
try {
Double d = 0.0;
for (int i = 1; i <= 100; i++) {
Thread.sleep(100);
d = 1.0 * i / 100;
updateProgress(d, 1);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
};
task.progressProperty().addListener((obs, oldProgress, newProgress) -> {
System.out.println((newProgress.doubleValue() * 100) + "% completed");
});
new Thread(task).start();
}

Related

ProgressDailog in asynctask from another Activity

I Have two Activity. The MainActivity is calling the another Activity which extends AsyncTask. In AsyncTask i had display ProgressDailog onPreExecute(), but ProgressDailog is not been display. The reason may be AyncTask execute for less time but the response but response takes time and therefore ProgressDialog should be displayed.
The Following code is provide.
Aysnc class
public class NewConnections extends AsyncTask<Void,Void,String>{
Context context;
String[] name,value;
String Geturl,para;
ProgressDialog progressDialog;
NewConnections(Context context,String[] name,String[] value,String Url){
this.context = context;
this.name = name;
this.value = value;
Geturl = Url;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Please Wait");
progressDialog.show();
}
#Override
protected String doInBackground(Void... voids) {
try
{
para = DCBUtil.jsonCovertion(name,value);
URL url = new URL(Geturl);
String responseStr = XXX.callJsonHttp(url,para);
System.out.println("Response of Home Open FD :: "+responseStr);
return responseStr;
}catch(Exception e)
{
return "Error";
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressDialog.dismiss();
}
}
MainClass
public class FirstPage extends AppCompatActivity {
Button existUser,newUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first_page);
existUser = (Button)findViewById(R.id.existUser);
newUser = (Button)findViewById(R.id.newUser);
newUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String[] value = {"asdasd"};
String[] name = {"dprm"};
try {
NewConnections v= new NewConnections(FirstPage.this,name,value,"url is provided");
v.execute().get();
} catch (Exception e) {
e.printStackTrace();
}
}
});
try this :
public class NewConnections extends AsyncTask<Void,Void,String>{
Context context;
String[] name,value;
String Geturl,para;
public static ProgressDialog progressDialog;
NewConnections(Context context,String[] name,String[] value,String Url){
this.context = context;
this.name = name;
this.value = value;
Geturl = Url;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.setCancelable(false);
progressDialog.setMessage("Please Wait");
progressDialog.show();
}
#Override
protected String doInBackground(Void... voids) {
try
{
para = DCBUtil.jsonCovertion(name,value);
URL url = new URL(Geturl);
String responseStr = XXX.callJsonHttp(url,para);
System.out.println("Response of Home Open FD :: "+responseStr);
return responseStr;
}catch(Exception e)
{
return "Error";
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(progressDialog!=null)
progressDialog.dismiss();
}
}
and when you exit from activity then write below code in onDestry() method of that Activity
#Override
protected void onDestroy() {
if(NewConnections.progressDialog!=null)
NewConnections.progressDialog.dismiss();
super.onDestroy();
}
Try this:: I hope this helps you.
Dialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
showProgressBar();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try{
hideProgressBar();
}catch (Exception e){
e.printStackTrace();
}
}
public void showProgressBar() {
dialog = new Dialog(mContext, android.R.style.Theme_Translucent);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
dialog.setCancelable(false);
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View viewChild = inflater.inflate(R.layout.loader, null);
dialog.setContentView(viewChild);
Runtime.getRuntime().gc();
System.gc();
try {
dialog.show();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
/**
* Hide progress dialog
*/
public void hideProgressBar() {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
loader.xml::
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:gravity="center">
<ProgressBar
android:id="#+id/loading_spinner"
android:layout_width="48dp"
android:layout_height="48dp"
android:indeterminateTintMode="src_atop"
android:indeterminateTint="#color/colorAccent"
android:layout_gravity="center" />
</RelativeLayout>

Fragment in ViewPager shows nothing while returning from another fragment

I have a ViewPager in the fragment named FragmentHome, and the viewpager contains fragments. Am using FragmentStatePagerAdapter for this. When the fragmentHome loads first the fragments in Viewpager show perfectly. I have another fragment named FragmentCountryList to select a country, according to that country the fragments in the viewpager to be refreshed/updated. Now The problem is after selecting the country, the country fragment is popped and returns to the FragmentHome, but, there nothing is showing in the view pager, if we scrolls the second page(fragment) can be viewed then scrolls back the first page(fragment) can be viewed.
Am new with the FragmentStatePagerAdapter, so i couldn't rectify the reason for this problem. Please Help. The code i used gives below
public class FragmentHome extends WeGrabBaseFragment {
private static String TAG = "FragmentHome";
private HomeDealsDataClass homeDealsDataClass;//1, homeDealsDataClass2;
private ViewPager viewPagerHome;
private ImageView imgViewDealIndicator;
private OnCitySelectedListener onCitySelectedListener;
private FragPageAdapter fragAdapt;
private ArrayList<HomeDealsDataClass> arrayListHomeData;
private FragmentHomeDetails fragmentHomeDetails1,fragmentHomeDetails2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Activity = (WeGrabBaseActivity) this.getActivity();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater
.inflate(R.layout.fragment_home, container, false);
((WeGrabMainActivity) Activity).showBottomBar();
((WeGrabMainActivity) Activity).setShowActionBar();
((WeGrabMainActivity) Activity).setHeading(PrefUtil.getCityName(Activity));
((WeGrabMainActivity) Activity).defaultButtonState();
viewPagerHome = (ViewPager) v.findViewById(R.id.viewPagerHome);
viewPagerHome.setOffscreenPageLimit(2);
imgViewDealIndicator = (ImageView) v.findViewById(R.id.imgViewDealIndicator);
Picasso.with(Activity).load(R.drawable.deals1).into(imgViewDealIndicator);
viewPagerHome.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (position == 0) {
Picasso.with(Activity).load(R.drawable.deals1).into(imgViewDealIndicator);
} else if (position == 1) {
Picasso.with(Activity).load(R.drawable.deals2).into(imgViewDealIndicator);
}
}
#Override
public void onPageSelected(int position) {
fragAdapt.notifyDataSetChanged();
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
onCitySelectedListener = new OnCitySelectedListener() {
#Override
public void onCitySelected() {
fetchFromWeb();
}
};
fetchFromWeb();
return v;
}
private void fetchFromWeb() {
if (Activity.isNetworkAvailable()) {
if (VolleyUtils.volleyEnabled) {
Activity.startSpinwheel(false, true);
JSONObject jsonObject = new JSONObject();
try {
if (!PrefUtil.isGPSLocation(Activity)) {
jsonObject.putOpt(AppConstants.COUNTRY_ID, PrefUtil.getCountryCode(Activity));
jsonObject.putOpt(AppConstants.CITY_ID, PrefUtil.getCityCode(Activity));
Log.e(TAG, "Not GPS Home : " + jsonObject.toString());
CommandFactory commandFactory = new CommandFactory();
commandFactory.sendPostCommand(
AppConstants.WEGRAB_HOME_URL, jsonObject);
} else {
/*jsonObject.putOpt(AppConstants.COUNTRY_NAME, PrefUtil.getCountryName(Activity));
jsonObject.putOpt(AppConstants.CITY_NAME, PrefUtil.getCityName(Activity));*/
jsonObject.putOpt(AppConstants.COUNTRY_ID, "112");
jsonObject.putOpt(AppConstants.CITY_ID, "6");
CommandFactory commandFactory = new CommandFactory();
Log.e(TAG, "In GPS Home : " + jsonObject.toString());
/*commandFactory.sendPostCommand(
AppConstants.WEGRAB_HOME_URL_GPS, jsonObject);*/
commandFactory.sendPostCommand(
AppConstants.WEGRAB_HOME_URL, jsonObject);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
#Override
public void onHomeDetailsPageDataLoadedSuccessfully(JSONObject jsonObject) {
super.onHomeDetailsPageDataLoadedSuccessfully(jsonObject);
Activity.stopSpinWheel();
try {
if (jsonObject != null) {
if (jsonObject != null) {
fragAdapt = new FragPageAdapter(getFragmentManager());
viewPagerHome.setAdapter(fragAdapt);
JSONArray jsonArray = jsonObject.getJSONArray(AppConstants.DEALS);
arrayListHomeData = new ArrayList<HomeDealsDataClass>();
if(jsonArray.length() > 0) {
viewPagerHome.setVisibility(View.VISIBLE);
for (int i = 0; i < jsonArray.length(); i++) {
arrayListHomeData.add(new HomeDealsDataClass(jsonArray.getJSONObject(i)));
}
fragAdapt.notifyDataSetChanged();
}else{
viewPagerHome.setVisibility(View.GONE);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onHomeDetailsPageDataLoadedFailed(JSONObject jsonObject) {
super.onHomeDetailsPageDataLoadedFailed(jsonObject);
Activity.stopSpinWheel();
}
private class FragPageAdapter extends FragmentStatePagerAdapter {
FragPageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
switch (pos) {
case 0:
Log.e(TAG,"Returns Fragment Home deals 1");
fragmentHomeDetails1 = FragmentHomeDetails.newInstance(arrayListHomeData.get(0));
return fragmentHomeDetails1;
case 1:
Log.e(TAG,"Returns Fragment Home deals 2");
fragmentHomeDetails2 = FragmentHomeDetails.newInstance(arrayListHomeData.get(1));
return fragmentHomeDetails2;
default:
return null;
}
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public int getCount() {
if(arrayListHomeData != null)
return arrayListHomeData.size();
else
return 0;
}
}
}
I had this problem too before, after searching through SO answers, this helped me.
Basically try changing your PagerAdapter to extend FragmentStatePagerAdapter from FragmentPagerAdapter

Datas repeated in my ListFragment

I encounter a problem with my ListFragment provided by Volley Library and hosted by a ViewPager ! So when i swipe follow Fragment and back to my previous ListFragment, datas are repeated again ! Why ? Please help me !
This my code :
Code for bind ListFragment:
public class AllConferencesFragment extends ListFragment {
// Variables
final String URL_ALL_CONFERENCES = "http://192.168.43.246/android_christEvent/all_events_conference.php";
//final String URL_ALL_CONFERENCES = "http://7avecdieu.org/android_christEvent/all_events_conference.php";
//private static String TAG = ConferenceActivity.class.getSimpleName();
ListView listView;
View view;
List<Event> eventLists = new ArrayList<Event>();
CustomListEventsAdapter customListEventsAdapter;
CircularProgressView circularProgressView;
// Contructeur
public AllConferencesFragment() {
}
// Creation du fragment
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
// Creation de la vue
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.conferences_frag, container, false);
circularProgressView = (CircularProgressView) view.findViewById(R.id.circular_progress);
return view;
}
// Activité gestionnaire du fragment créé
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
circularProgressView.setVisibility(View.VISIBLE);
circularProgressView.startAnimation();
getListView();
//listView = (ListView) view.findViewById(R.id.list);
customListEventsAdapter = new CustomListEventsAdapter(getActivity(), eventLists);
//listView.setAdapter(customListEventsAdapter);
setListAdapter(customListEventsAdapter);
// On check si la cache est vide
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Cache.Entry entry = cache.get(URL_ALL_CONFERENCES);
if (entry != null) {
circularProgressView.setVisibility(View.VISIBLE);
// Parcours des données de la cache de cette url passée en parametre
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data));
// notify data changes to list adapater
customListEventsAdapter.notifyDataSetChanged();
}
catch (JSONException e) {
e.printStackTrace();
}
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
else {
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET,
URL_ALL_CONFERENCES,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d("Resultats ----> ", "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
// notify data changes to list adapater
customListEventsAdapter.notifyDataSetChanged();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Resultats ----> ", "Error: " + error.getMessage());
//progressBar.setVisibility(View.GONE);
circularProgressView.setVisibility(View.GONE);
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
// Au Cliq sur un iem
getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getContext(), DetailsEventsActivity.class);
intent.putExtra("position", position);
startActivity(intent);
}
});
}
/**
* Parsing json reponse and passing the data to event view list adapter
**/
private void parseJsonFeed(JSONObject response) {
try {
JSONArray eventArray = response.getJSONArray("events");
for (int i = 0; i < eventArray.length(); i++) {
JSONObject eventObj = (JSONObject) eventArray.get(i);
Event evt = new Event();
evt.setPriceEvent(eventObj.getString("event_price"));
// Image might be null sometimes
String image = eventObj.isNull("event_thumb") ? null : eventObj.getString("event_thumb");
evt.setThumbEvent(image);
evt.setNameEvent(eventObj.getString("event_name"));
evt.setPlaceEvent(eventObj.getString("event_place"));
evt.setHourEvent(eventObj.getString("event_hour"));
evt.setDateEvent(eventObj.getString("event_date"));
eventLists.add(evt);
}
circularProgressView.setVisibility(View.GONE);
}
catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onDestroy() {
super.onDestroy();
//progressBar.setVisibility(View.GONE);
}
}
Code for Volley Application :
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if(mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
mImageLoader = new ImageLoader(this.mRequestQueue, new LruBitmapCache());
}
return this.mImageLoader;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
// Set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
My parseJsonEvent :
private void parseJsonEvent(JSONObject response) {
try {
JSONArray eventArray = response.getJSONArray(TAG_EVENTS);
// Loop Json node
for (int i = 0; i < eventArray.length(); i++) {
JSONObject eventObj = (JSONObject) eventArray.get(i);
// Create event object
Event evt = new Event();
evt.setIdEvent(eventObj.getInt(TAG_EVENT_ID));
evt.setDateEvent(eventObj.getString(TAG_EVENT_DATE));
evt.setPriceEvent(eventObj.getString(TAG_EVENT_PRICE));
evt.setNameEvent(eventObj.getString(TAG_EVENT_NAME));
evt.setCountryEvent(eventObj.getString(TAG_EVENT_COUNTRY));
evt.setPlaceEvent(eventObj.getString(TAG_EVENT_PLACE));
evt.setTypeEvent(eventObj.getString(TAG_EVENT_TYPE));
// event thumbnail
String eventUrl = eventObj.isNull(TAG_EVENT_THUMB) ? null : eventObj.getString(TAG_EVENT_THUMB);
evt.setThumbEvent(eventUrl);
// Adding in the list object
eventList.add(evt);
// notify list view to adding
}
adapter.notifyDataSetChanged();
}
catch (JSONException e) {
e.printStackTrace();
}
}
My Main Activity :
public class ConferenceActivity extends AppCompatActivity {
private Toolbar toolbarConference;
private TabLayout tabLayoutConference;
private ViewPager viewPagerConference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Typeface tf = Typeface.createFromAsset(getAssets(), fontPath);
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbarConference = (Toolbar) findViewById(R.id.toolbar_conference);
setSupportActionBar(toolbarConference);
viewPagerConference = (ViewPager) findViewById(R.id.viewpager_conference);
setupViewPager(viewPagerConference);
tabLayoutConference = (TabLayout) findViewById(R.id.tabs_conference);
tabLayoutConference.setupWithViewPager(viewPagerConference);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new AllEventsConferenceFragments(), "TOUS");
adapter.addFragment(new ThisWeekFragment(), "AUJOURD'HUI");
adapter.addFragment(new TodayEventFragment(), "CETTE SEMAINE");
adapter.addFragment(new AllEventsConferenceFragments(), "SEMAINE PROCHAINE");
adapter.addFragment(new ThisWeekFragment(), "CE MOIS CI");
adapter.addFragment(new TodayEventFragment(), "MOIS PROCHAIN");
adapter.addFragment(new AllEventsConferenceFragments(), "ANNEE EN COURS");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
public class AllConferencesFragment extends ListFragment {
private boolean loaded = false;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(loaded){
return;
}
loaded = true;
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET,
URL_ALL_CONFERENCES,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d("Resultats ----> ", "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
// notify data changes to list adapater
customListEventsAdapter.notifyDataSetChanged();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Resultats ----> ", "Error: " + error.getMessage());
//progressBar.setVisibility(View.GONE);
circularProgressView.setVisibility(View.GONE);
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
}

JavaFx - is there any way to refresh whole treeview?

I'm newbie on java fx.
And I'm making an application with treeview and treeview has made by nested set model. So each treeitem has to have left, right data.(I made a treeitem like Treeitem>. Object has data(id, label name, left, right, etc) and String is label name to be shown at treeview.)
The problem is that whole treeitems have to be updated when I add a new treeitem(or delete treeitem). I already implemented whole data(the other treeitem's) to be updated on DB, but treeview still has data isn't updated.
I looked for the way to refresh treeview, but I just found user shouldn't use updateitem forcefully.
Is there any way or method to refresh whole treeview?
FYI. code below
Pair<LabelTreeItem,String> f = new Pair<>(new LabelTreeItem(1, "Root", 0, 0, "",0), "Root");
try {
f = new Pair<>(service.getRoot(), "Root");
} catch (SQLException e) {
System.out.println("Can't find Root Node");
e.printStackTrace();
}
TreeItem<Pair<LabelTreeItem,String>> root = createNode(f);
root.setExpanded(true);
treeView.setRoot(root);
treeView.setEditable(true);
treeView.setCellFactory(new Callback<TreeView<Pair<LabelTreeItem,String>>,TreeCell<Pair<LabelTreeItem,String>>>(){
#Override
public TreeCell<Pair<LabelTreeItem,String>> call(TreeView<Pair<LabelTreeItem,String>> p) {
return new TextFieldTreeCellImpl();
}
});
.....................................
private TreeItem<Pair<LabelTreeItem,String>> createNode(final Pair<LabelTreeItem,String> f) {
return new TreeItem<Pair<LabelTreeItem,String>>(f) {
private boolean isLeaf;
private boolean isFirstTimeChildren = true;
private boolean isFirstTimeLeaf = true;
#Override public ObservableList<TreeItem<Pair<LabelTreeItem,String>>> getChildren() {
if (isFirstTimeChildren) {
isFirstTimeChildren = false;
super.getChildren().setAll(buildChildren(this));
}
return super.getChildren();
}
#Override public boolean isLeaf() {
if (isFirstTimeLeaf) {
isFirstTimeLeaf = false;
Pair<LabelTreeItem,String> f = getValue();
int nodeLeft = f.getKey().getLeft();
int nodeRight = f.getKey().getRight();
if(nodeRight-nodeLeft == 1) {
isLeaf = true;
System.out.println("this is leaf");
}
}
return isLeaf;
}
private ObservableList<TreeItem<Pair<LabelTreeItem,String>>> buildChildren(TreeItem<Pair<LabelTreeItem,String>> TreeItem) {
Pair<LabelTreeItem,String> f = TreeItem.getValue();
System.out.println("ID: "+f.getKey().getId());
int nodeLeft = f.getKey().getLeft();
int nodeRight = f.getKey().getRight();
try {
if (f != null && nodeRight-nodeLeft != 1) {
ArrayList<LabelTreeItem> item = new ArrayList<>();
item = service.getChildren(f.getKey().getLeft(), f.getKey().getRight(), f.getKey().getDepth());
ArrayList<Pair<LabelTreeItem,String>> itemList = new ArrayList<>();
for(int i=0; i<item.size(); i++) {
System.out.println("test : " + item.get(i).getLabel());
Pair<LabelTreeItem,String> pair = createPair(item.get(i), item.get(i).getLabel());
itemList.add(pair);
}
if(itemList.size() != 0) {
ObservableList<TreeItem<Pair<LabelTreeItem,String>>> children = FXCollections.observableArrayList();
for (Pair<LabelTreeItem,String> childNode : itemList) {
children.add(createNode(childNode));
}
return children;
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return FXCollections.emptyObservableList();
}
};
}
private Pair<LabelTreeItem, String> createPair(LabelTreeItem item, String name) {
return new Pair<>(item, name);
}
LabelTreeItem.java
public class LabelTreeItem {
private int id;
private String label;
private int left;
private int right;
private String comment;
private int depth;
public LabelTreeItem(int id, String label, int left, int right, String comment, int depth) {
this.id = id;
this.label = label;
this.left = left;
this.right = right;
this.comment = comment;
this.depth = depth;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public int getLeft() {
return left;
}
public void setLeft(int left) {
this.left = left;
}
public int getRight() {
return right;
}
public void setRight(int right) {
this.right = right;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public int getDepth() {
return depth;
}
public void setDepth(int depth) {
this.depth = depth;
}
}
TextFieldTreeCellImpl.java
public TextFieldTreeCellImpl() {
service = SqliteService.getInstance();
MenuItem addLabel = new MenuItem("Label add");
addMenu.getItems().add(addLabel);
addLabel.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
getTreeItem().setExpanded(true);
LabelTreeItem newItem = null;
try {
id = getTreeItem().getValue().getKey().getId();
label = getTreeItem().getValue().getKey().getLabel();
depth = getTreeItem().getValue().getKey().getDepth()+1;
left = getTreeItem().getValue().getKey().getLeft();
right = getTreeItem().getValue().getKey().getRight();
newItem = service.getData("New Label", id,depth);
TreeItem<Pair<LabelTreeItem,String>> newLabel = new TreeItem(createPair(newItem, newItem.getLabel()));
getTreeItem().getChildren().add(newLabel);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
MenuItem editLabel = new MenuItem("Label modify");
addMenu.getItems().add(editLabel);
editLabel.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
startEdit();
}
});
MenuItem removeLabel = new MenuItem("Label delete");
addMenu.getItems().add(removeLabel);
removeLabel.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
try {
left = getTreeItem().getValue().getKey().getLeft();
right = getTreeItem().getValue().getKey().getRight();
service.deleteData(left, right, (right-left)+1);
} catch (SQLException e) {
e.printStackTrace();
}
getTreeItem().getParent().getChildren().remove(getTreeItem());
System.out.println("Remove");
}
});
}
#Override
protected void updateItem(final Pair<LabelTreeItem, String> pair, boolean empty) {
super.updateItem(pair, empty);
if (!empty && pair != null) {
if (isEditing()) {
if (textField != null) {
textField.setText(getString());
}
setText(null);
setGraphic(textField);
} else {
setText(pair.getKey().getLabel());
setGraphic(getTreeItem().getGraphic());
setContextMenu(addMenu);
}
} else {
setText(null);
setGraphic(null);
}
setOnMouseExited(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
if(pair !=null){
Tooltip tTip = new Tooltip(pair.getKey().getLabel());
tTip.uninstall(getTreeView(), tTip);
}
}
});
setOnMouseEntered(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
if(pair !=null){
Tooltip tTip = new Tooltip();
tTip.setText(pair.getKey().getLabel()
+"\nComment : "+pair.getKey().getComment()
+"\nLeft : "+pair.getKey().getLeft()
+"\nRight : "+pair.getKey().getRight());
tTip.setFont(new Font("Arial", 16));
tTip.setStyle("-fx-background-color: grey;");
tTip.centerOnScreen();
tTip.install(getTreeView(), tTip);
}
}
});
}
DB Table
id|label|left|right|comment|depth

Trying to implement swipe movement

public class CoursesActivity extends SherlockFragmentActivity {
ArrayList<CourseData> mCoursesList = new ArrayList<CourseData>();
public CoursesListAdapter coursesListAdapter;
public ListView mList;
public AlertDialog.Builder dlgAlert;
public Dialog loginDialog;
public Dialog loginDialogOverflow;
LinearLayout progressBar;
static SQLiteWebcourse dbHelper;
private GestureDetectorCompat mDetector;
public final static String EXTRA_MESSAGE = "com.technion.coolie.webcourse.MESSAGE";
public CoursesActivity() {
dbHelper = new SQLiteWebcourse(this, "WebcoureDB", null, 1);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create list of courses
mCoursesList = new ArrayList<CourseData>();
setContentView(R.layout.web_activity_courses);
mList = (ListView) findViewById(R.id.courses_list);
dlgAlert = new AlertDialog.Builder(getApplicationContext());
if (!CoolieAccount.WEBCOURSE.isAlreadyLoggedIn()) {
loginDialog = CoolieAccount.WEBCOURSE.openSigninDialog(this);
OnDismissListener dismissListener = new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
// Check if connection success
if (CoolieAccount.WEBCOURSE.isAlreadyLoggedIn()) {
// Connection SUCCESS
progressBar = (LinearLayout) findViewById(R.id.progressBarLayout_courses);
progressBar.setVisibility(View.VISIBLE);
asyncParse<CourseData> a = new asyncParse<CourseData>() {
#Override
protected List<CourseData> doInBackground(
String... params) {
// TODO Auto-generated method stub
try {
courseList crL = new courseList(
getApplicationContext());
crL.getCourses(CoolieAccount.WEBCOURSE
.getUsername(),
CoolieAccount.WEBCOURSE
.getPassword());
mCoursesList = dbHelper
.getAllCourses(CoolieAccount.WEBCOURSE
.getUsername());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return super.doInBackground(params);
}
#Override
protected void onPostExecute(List<CourseData> result) {
// TODO Auto-generated method stub
CoursesListAdapter coursesListAdapter = new CoursesListAdapter(
getApplicationContext(), mCoursesList);
mList.setAdapter(coursesListAdapter);
mList.setBackgroundColor(0xFFF0F0F0);
progressBar.setVisibility(View.INVISIBLE);
super.onPostExecute(result);
}
};
a.execute("");
} else {
// Connection FAILED
Log.v("dbAss", "Second Time");
}
}
};
loginDialog.setOnDismissListener(dismissListener);
} else {
mCoursesList = dbHelper.getAllCourses(CoolieAccount.WEBCOURSE
.getUsername());
CoursesListAdapter coursesListAdapter = new CoursesListAdapter(
getApplicationContext(), mCoursesList);
mList.setAdapter(coursesListAdapter);
mList.setBackgroundColor(0xFFF0F0F0);
}
Log.v("Gestures", "OnTouchEvent#!$#%##%^&^$%");
// OnItemClickListener itemClicked = new OnItemClickListener() {
//
// #Override
// public void onItemClick(AdapterView<?> list, View view,
// int position, long id) {
// // TODO Auto-generated method stub
// loadCourseInformationActivity(((CourseData) mList
// .getItemAtPosition(position)).CourseDescription);
// }
// };
// mList.setOnItemClickListener(itemClicked);
mDetector = new GestureDetectorCompat(this, new MyGestureListener());
}
#Override
public boolean onTouchEvent(MotionEvent event) {
Log.v("Gestures", "OnTouchEvent#!$#%##%^&^$%");
this.mDetector.onTouchEvent(event);
// Be sure to call the superclass implementation
return super.onTouchEvent(event);
}
class MyGestureListener extends GestureDetector.SimpleOnGestureListener {
private static final String DEBUG_TAG = "Gestures";
#Override
public boolean onFling(MotionEvent event1, MotionEvent event2,
float velocityX, float velocityY) {
Log.v(DEBUG_TAG,
"onFling: " + event1.toString() + event2.toString());
Toast.makeText(getApplicationContext(), "SWIPED", Toast.LENGTH_LONG)
.show();
if (event2.getX() - event1.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY)
Toast.makeText(getApplicationContext(), "SWIPED",
Toast.LENGTH_LONG).show();
// if (showDeleteButton(e1))
// return true;
return super.onFling(event1, event2, velocityX, velocityY);
}
}
}
Hey fellas, i'm trying to implement swipe detection I went through android lesson and did exactly what is written there: http://developer.android.com/training/gestures/detector.html
For some reason when I touch the screen it doesnt go to onTouchEvent. What seems to be the problem?
You haven't set the touch listener to your ListView.
listView.setOnTouchListener(this);

Resources