Error: can not fine method findViewByID in onPageFinished of WebViewClient Class - imageview

I asked following question 1 month back , people here are not interested in replying questions , but they can spend hours and trolling who ask the questions, to increase their so called reputation, perhaps it can be called as bad reputation. so now I only answer this question, but these (bad) reputed trollers may not approve the post.
-----------------------the question was----------------------
In this example findViewById is called in onPageFinished of webview class, but when I am trying to do the same, it is giving error:
Error: can not find method findViewByID
Source Code:
#Override
public void onPageFinished(WebView view, String url) {
ImageView logo = (ImageView) findViewById(R.id.imageView1);
logo.setVisibility(0);
}
the answer is as follows
declare
public ImageView logo = (ImageView) findViewById(R.id.imageView1);
in main activity.
then in onPageFinished set visibility to invisible of imageview as follows
#Override
public void onPageFinished(WebView view, String url) {
logo.setVisibility(0);
}

Related

Start a fragment from MainActivity that calls another fragment. The listener returns to the MainActivity

My MainActivity(1) implements FragmentStatePagerAdapter, with SectionPagerAdapter and ViewPager. It works OK, apart from the problem I have to call getItemPosition to update one of the Fragments, which causes the whole thing to be recreated. Anyway...
One of the "tabs", calls a Fragment(2=BaixarOrcamentoFragment.java), which in turn, calls another Fragment(3=FillReasonToBaixaFragment.java), so the user can insert a text.
Fragment(2) implements THE LISTENER that Fragment(3) uses to return a "text value", so Fragment(2) can continue and finish it's tasks.
Here is the code in Fragment(2), that calls Fragment(3):
FragmentManager fragmentManager = getFragmentManager();
FillReasonToBaixaFragment fillFragment = new
FillReasonToBaixaFragment();
Bundle args = new Bundle();
args.putInt("ORCID", baixarModelList.get(masterPosition)
.getOrcGroupID());
fillFragment.setArguments(args);
fillFragment.show(fragmentManager, FILL_REASON_TO_BAIXA);
Then, Fragment(3) gets the bundle ORCID,stars the listener, get some data, shows a text input, and finishes by sending this "text" to the interface:
BaixaItemdoOrcamentoListener listener = (BaixaItemdoOrcamentoListener) this
.getContext();
..and then returning what has collected (text) using this interface (listener):
public interface BaixaItemdoOrcamentoListener
{
void OnFinishedFillReason(String mEditext);
}
However, it's not returning back to Fragment(2), which called Fragment(3), where I implemented the method to receive this returning value:
#Override
public void OnFinishedFillReason(String mEditext)
{}
It shows a cast error, saying that .MainActivity cannot be cast to .FillReasonToBaixaFragment$BaixaItemdoOrcamentoListener
I went on and DECLARED the OnFinishedFillReason inside the MainActivity, which implements FillReasonToBaixaFragment.BaixaItemdoOrcamentoListener.
Be aware now, that the actual implementation of the tasks are in Fragment(2).
Guess what: when I enter the text in Fragment(3) and press ( android:imeOptions="actionDone"), it returns to the MainActivity, NOT to the Fragment(2), the one that has called Fragment(3).
MainActivity doesn't know the existence of any of the the Views inside Fragment(2), a priori, which will, in turn, update all these views ONCE received the "text" from Fragment(3).
Perhaps I didn't search thoroughly, but I couldn't find anything that resembles this situation.
How can I make it happen?
Afternoon everyone.
I figured it out how to make this happen.
First: I removed OnFinishedFillReason interface from Fragment(2), and therefore, from Fragment(3).
In Fragment(2), I started the Fragment(3) like this, setting a setTargetFragment:
FragmentManager fragmentManager = getFragmentManager();
FillReasonToBaixaFragment fillFragment = new
FillReasonToBaixaFragment();
fillFragment.setTargetFragment(BaixaOrcamentoFragment.this,
FILL_REASON_TO_BAIXA);
Bundle args = new Bundle();
args.putInt("ORCID", baixarModelList.get(masterPosition)
.getOrcGroupID());
fillFragment.setArguments(args);
fillFragment.show(fragmentManager,
this.getClass().getSimpleName());
The target fragment is the Fragment(2) itself.
Then I added in Fragment(2):
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == FILL_REASON_TO_BAIXA && resultCode == Activity.RESULT_OK)
{// code in here }
In Fragment(3), I added in the onCreate(Bundle savedInstanceState) method, the following:
targetFragment = getTargetFragment();
if (targetFragment instanceof BaixaOrcamentoFragment)
{
orcID = getArguments().getInt("ORCID");
}
At the end of the returning elements, like this:
Intent returnData = new Intent();
Bundle bundle = new Bundle();
bundle.putString("EDITTEXT", txtEdited);
returnData.putExtras(bundle);
targetFragment.onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, returnData);
this.dismiss();
return true;
And then, inside the onActivityResult I collected the data, like this:
Bundle returnedValues = data.getExtras();
String mRazao = returnedValues.getString("EDITTEXT").trim();
And that was it.
But I still have a problem: I have 6 tabs. Tab 4 is never selected as currentItem, inside the method below:
#Override
public void onPageSelected(int position)
{
mViewPager.setCurrentItem(position);
}

JavaFX MediaPlayer - seek() method makes the player hang

I've been looking for ages for direction on this matter and I finally post here.
I have a JavaFX application with MediaPlayer. One day, seeking at a later position in video (that had not been accessed previously) started hanging the player. No status change before it gets to PLAYING, the buffer is loaded, status at READY before I call seek().
First I thought it is because I went out of Application thread, tried to put the MediaPlayer back on the root to be sure, and the seek method worked as before, fast enough for me.
But then for a reason I can't get, it started hanging again all the time, with same symptoms.
Now, even with the most simple code, it hangs too.
I'm desperate, the waiting time can be 30 seconds to reach a position 2 minutes later in the video. Looks like the Media Player is scanning again all video until it finds the good position it's seeking, thus taking more time for a later position. If the position has been accessed before though, seek() won't hang...
Am I the only one with this problem?
I'm on Mac os EL Capitan, but tried on Windows VM too and I get the same behaviour.
Here is a standalone code, but I don't see how it will help, I don't even hope for ppl to reproduce:
public class VideoPlayerExample extends Application {
public static void main(String[] args) throws Exception {
launch(args);
}
#Override
public void start(final Stage stage) throws Exception {
File file = new FileChooser().showOpenDialog(stage);
Media media = new Media(file.toURI().toString());
MediaPlayer mp = new MediaPlayer(media);
mp.statusProperty().addListener(new ChangeListener<MediaPlayer.Status>() {
#Override
public void changed(ObservableValue<? extends Status> observable, Status oldValue, Status newValue) {
System.out.println(newValue);
}
});
Group gp = new Group(new MediaView(mp));
Button buttonTest = new Button("It's gonna hang...");
buttonTest.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
mp.pause();
System.out.println(mp.getCurrentTime().toMillis());
mp.seek(new Duration(mp.getCurrentTime().toMillis() +10000));
mp.play();
}
});
gp.getChildren().add(buttonTest);
stage.setScene(new Scene(gp, 540, 208));
stage.show();
}
}
Any help will be so greatly appreciated!
You're right - I can't reproduce your problem. I have macOS Sierra 10.12.6. All I can say is check the type of movie you're trying to play - not all encodings are supported. Also, according to the documentation, if the movie's duration is Duration.INDEFINITE, seek() will have no effect.
Place the seek method in a new thread not on your JavaFX thread.
new Thread(() -> mp.seek(new Duration(mp.getCurrentTime().toMillis() +10000)))).start();

Issue with ViewPager and FragmentStatePagerAdapter when activity is destroyed

I have an activity which creates viewpager adapter (FragmentStatePagerAdapter) and sets the viewpager to this adapter.
This is how viewpager adapter is created and is set to the viewpager widget.
viewPageAdapter = new viewPageAdapter(getSupportFragmentManager(), getApplicationContext());
mCustomSwipeViewPager.setAdapter(viewPageAdapter);
And this is how i am creating viewPageAdapter
public class viewPagerAdapter extends FragmentStatePagerAdapter {
private SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
public viewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// returning newly created fragment
}
#Override
public int getCount() {
// returning total count
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
// This is where i am putting created fragment in the sparse array,
// which i will be accessing in the activity based on position
// for updating fragment views.
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// And here i am removing it from the sparse array
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
}
Now, i went to the developers options and checked "Donot keep activities".
This is where the problem starts, after moving forward this activity, this activity will get destroyed, which is fine.
Now if i come back, the a new adapter is created in onCreate() and is set to the viewpager, but it's not calling getItem() again, instead it's calling instantiateItem(), with fragment in memory as null.
I checked the fragmentmanager in debug mode, the fragment manager holds two fragments as activestate, with all fragment fields as null.
Things i have tried...
Tried clearing the fragment manager in onDestroy() of activity using
fragmentManager.getFragments.clear() but no luck.
Made getItemCount() of adapter to 0 and called notifydatasetChanged() on adapter in onDestroy(), still getting the same.
However, if comment out the super.onSavedInstance() of activity, it's working fine, but this is not i want as it's failing for few cases.
Is there any way wherein if i create a new adapter and again set it to the viewpager, it should start afresh, i.e should call getItem() from first position without minimizing the performance of fragmentStateViewPagerAdapter.
Any kind of help or suggestion would be appreciated.
The only solution i figured out is to comment out the default super.onSaveInstanceState(outState) inside onSaveInstanceState(Bundle outState) callback of activity lifecycle.
#Override
protected void onSaveInstanceState(Bundle outState) {
// super.onSaveInstanceState(outState);
}
Doing so will not keep the fragment old instance in the fragmentManager of viewpager and will start afresh.
I couldn't thought of any better solution, as there are many global variables inside fragment and in also in activity and it's presenter, and saving them in the onSaveInstanceState bundle and them restoring them in onCreate or in onRestoreInstanceState() would be very heavy for me.
Any better solution or approach than this is still appreciable.
Had the same issue, was assigning the fragment's view container an id programmatically, we removed this and assigned an id in its layout XML file and the issue went away.

How to specify a button to open an URL?

I want to write a web application that triggers the default email client of the user to send an email.
Thus, I created a Link, that leads to an URL conforming to the mailto URI scheme (http://en.wikipedia.org/wiki/Mailto):
Link emailLink = new Link("Send Email",
new ExternalResource("mailto:someone#example.com"));
However, instead of using a Link, I want to provide a Button that allows to trigger the respective functionality. But, for buttons I cannot set an ExternalResource to be opened.
Does anybody know to solve this problem for Buttons, or how to create a Link that looks and behaves exactly like a button? I also tried some CCS modification but did not manage the task by myself. I also found some solutions for former Vaadin versions (https://vaadin.com/forum/#!/thread/69989), but, unfortunately they do not work for Vaadin 7.
I remember solving a similar problem using a ResourceReference.
Button emailButton = new Button("Email");
content.addComponent(emailButton);
Resource res = new ExternalResource("mailto:someone#example.com");
final ResourceReference rr = ResourceReference.create(res, content, "email");
emailButton.addClickListener(new Button.ClickListener() {
#Override
public void buttonClick(ClickEvent event) {
Page.getCurrent().open(rr.getURL(), null);
}
});
For solving similar issue, I applied previously:
String email="info#ORGNAME.org";
Link l=new Link();
l.setResource(new ExternalResource("mailto:" + email));
l.setCaption("Send email to " + email);
addComponent(l);
After some further tries a managed to adapt the proposed LinkButton solution from https://vaadin.com/forum/#!/thread/69989 for Vaadin 7:
public class LinkButton extends Button {
public LinkButton(final String url, String caption) {
super(caption);
setImmediate(true);
addClickListener(new Button.ClickListener() {
private static final long serialVersionUID = -2607584137357484607L;
#Override
public void buttonClick(ClickEvent event) {
LinkButton.this.getUI().getPage().open(url, "_blank");
}
});
}
}
However, this solution is still not perfect as it causes the opening of a popup window being blocked by some web browsers.

commit fragment from onLoadFinished within activity

I have an activity which loads a data list from the server using loader callbacks. I have to list out the data into a fragment which extends
SherlockListFragment
i tried to commit the fragment using
Fragment newFragment = CategoryFragment.newInstance(mStackLevel,categoryList);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.simple_fragment, newFragment).commit();
in onLoadFinished and it gives an IllegalStateException saying
java.lang.IllegalStateException: Can not perform this action inside of onLoadFinished
I have referred the example in actionbar sherlock, but those examples have loaders within the fragments and not the activity.
Can anybody help me with this o that I can fix it without calling the loader from the fragment!
Atlast, I have found a solution to this problem. Create a handle setting an empty message and call that handler onLoadFinished(). The code is similar to this.
#Override
public void onLoadFinished(Loader<List<Station>> arg0, List<Station> arg1) {
// do other actions
handler.sendEmptyMessage(2);
}
In the handler,
private Handler handler = new Handler() { // handler for commiting fragment after data is loaded
#Override
public void handleMessage(Message msg) {
if(msg.what == 2) {
Log.d(TAG, "onload finished : handler called. setting the fragment.");
// commit the fragment
}
}
};
The number of fragments depend on the requirement.
This method can be mainly used in case of stackFragments, where all fragments have different related functions.
As per the Android docs on the onLoadFinished() method:
Note that normally an application is not allowed to commit fragment transactions while in this call, since it can happen after an activity's state is saved. See FragmentManager.openTransaction() for further discussion on this.
https://developer.android.com/reference/android/app/LoaderManager.LoaderCallbacks.html#onLoadFinished(android.content.Loader, D)
(Note: copy/paste that link into your browser... StackOverflow is not handling it well..)
So you simply should never load a fragment in that state. If you really don't want to put the Loader in the Fragment, then you need to initialize the fragment in your onCreate() method of the Activity, and then when onLoadFinished occurs, simply call a method on your fragment.
Some rough pseudo code follows:
public class DummyFragment {
public void setData(Object someObject) {
//do stuff
}
public class DummyActivity extends LoaderCallbacks<Object> {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fragment newFragment = DummyFragment.newInstance();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.simple_fragment, newFragment).commit();
getSupportLoaderManager.initLoader(0, null, this)
}
// put your other LoaderCallbacks here... onCreateLoader() and onLoaderReset()
public void onLoadFinished(Loader<Object> loader, Object result) {
Fragment f = getSupportLoaderManager.findFragmentById(R.id.simple_fragment);
f.setData(result);
}
Obviously, you'd want to use the right object.. and the right loader, and probably define a useful setData() method to update your fragment. But hopefully this will point you in the right direction.
As #kwazi answered this is a bad user experience to call FragmentTransition.commit() from onLoadFinished(). I have found a solution for this event by using ProgressDialog.
First created ProgressDialog.setOnDismissListener(new listener) for watching the onLoadFinished().
Further i do progressDialog.show() before getLoaderManager().restartLoader().
And eventually place progressDialog.dismiss() in onLoadFinished().
Such approach allow do not bind main UI thread and Loader's thread.
public class FrPersonsListAnswer extends Fragment
implements
LoaderCallbacks<Cursor>{
private ProgressDialog progressDialog;
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_persons_list, container, false);
//prepare progress Dialog
progressDialog = new ProgressDialog(curActivity);
progressDialog.setMessage("Wait...");
progressDialog.setIndeterminate(true);
progressDialog.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
//make FragmentTransaction.commit() here;
//but it's recommended to pass control to your Activity
//via an Interface and manage fragments there.
}
});
lv = (ListView) view.findViewById(R.id.lv_out1);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
final int position, long id) {
//START PROGRESS DIALOG HERE
progressDialog.show();
Cursor c = (Cursor) parent.getAdapter().getItem(position);
// create Loader
getLoaderManager().restartLoader(1, null, curFragment);
}
});
return view;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
switch (loader.getId()) {
case 1:
//dismiss dialog and call progressDialog.onDismiss() listener
progressDialog.dismiss();
break;
default:
break;
}
}

Resources