Progress bar with thread - android-progressbar

Now a days it's my first step in android. I am simply trying to implement progress bar with with a "Download" Button. When i press download button progress bar keep on progressing but when the whole progress gets over i am not able to hide progress bar. Here is my code. please help me.
public class ProgressBarDemo extends Activity
{
ProgressBar pb;
Button bt;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.progressbar);
pb = (ProgressBar) findViewById(R.id.progressBar1);
bt = (Button) findViewById(R.id.button1);
pb.setVisibility(View.VISIBLE);
bt.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Thread timer = new Thread()
{
public void run()
{
try
{
for(int i=0; i<=50; i ++)
{
pb.incrementProgressBy(i);
sleep(1000);
}
pb.setVisibility(View.INVISIBLE);
Toast.makeText(ProgressBarDemo.this, "Thank you for downloading", Toast.LENGTH_SHORT).show();
}catch(Exception e){}
}
};
timer.start();
}
});
}
}

You should only modifiy ui elements from the mainThread (the UI Thread) try
pb.post(new Runnable() {
#Override
public void run() {
pb.setVisibility(View.INVISIBLE);
}
})
instead.
Maybe u have to use the same thing for incrementing your progressbar. Alternativley you could use the AsyncTask http://developer.android.com/reference/android/os/AsyncTask.html class. onProgressUpdate and onPostExecute are called in the UIThread automatically.

you can also use AsynTask that is a better solution...
public class ProgressBarDemo extends Activity
{
ProgressBar pb;
Button bt;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
pb = (ProgressBar) findViewById(R.id.progressBar1);
bt = (Button) findViewById(R.id.button1);
pb.setVisibility(View.VISIBLE);
bt.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
new AsynTasks().execute();
}
});
}
class AsynTasks extends AsyncTask<Void, Integer, Void>
{
#Override
protected Void doInBackground(Void... params) {
for(int i=1;i<=100;i++)
{
SystemClock.sleep(1000);
publishProgress(i);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pb.setVisibility(View.INVISIBLE);
Toast.makeText(ProgressBarDemo .this, "Thank you for downloading", Toast.LENGTH_SHORT).show();
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
pb.setProgress(values[0]);
}
}
}

You should not do UI task from different thread.Use this...
public class ProgressBarDemo extends Activity
{
ProgressBar pb;
Button bt;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
pb = (ProgressBar) findViewById(R.id.progressBar1);
bt = (Button) findViewById(R.id.button1);
pb.setVisibility(View.VISIBLE);
bt.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Thread timer = new Thread()
{
public void run()
{
try
{
for(int i=1; i<=100; i ++)
{
pb.setProgress(i);
sleep(100);
}
}catch(Exception e){}
finally{
runOnUiThread( new Runnable() {
public void run() {
pb.setVisibility(View.INVISIBLE);
Toast.makeText(ProgressBarDemo .this, "Thank you for downloading", Toast.LENGTH_SHORT).show();
}
});
}
}
};
timer.start();
}
});
}
}

Related

Retrieve data from Firebase in Recycler view using fragment take too much time

I am using two fragments in the main activity, In first fragment[FirstFragment] load data from firebase and show in Recycler view, In the second fragment[uploadUserCarInformation] take data from user and store at the firebase,
I am facing a problem when the application starts then first fragment load very quickly and data show but when replace the first fragment from the second fragment and when replacing back from the second fragment to the first fragment then take 4 to 5 minutes to load data from firebase in recyclerView.
Kindly tell me where I modify the code,
Main Activity
public class MainActivity extends AppCompatActivity {
FrameLayout simpleFrameLayout;
TabLayout tabLayout;
Fragment fragment1 = new FirstFragment();
Fragment fragment2 =new SecondFragment();
#SuppressLint("WrongViewCast")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the reference of FrameLayout and TabLayout
tabLayout=findViewById(R.id.simpleTabLayout);
simpleFrameLayout = (FrameLayout) findViewById(R.id.simpleFrameLayout);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.simpleFrameLayout, fragment1);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
// perform setOnTabSelectedListener event on TabLayout
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
// get the current selected tab's position and replace the fragment accordingly
switch (tab.getPosition()) {
case 0:
tab.getIcon().setColorFilter(null);
fragmentReplace(fragment1,"fragment1");
break;
case 1:
fragmentReplace(fragment2,"fragment2");
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
public void fragmentReplace(Fragment fragment,String fragmentName)
{
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.simpleFrameLayout, fragment);
Log.d("Running Fragment",fragmentName+ " is running");
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
}
}
FirstFragment
public class FirstFragment extends Fragment {
private RecyclerView mRecyclerView;
private ImageAdapter mAdapter;
private DatabaseReference mDatabaseRef;
private List<carInformation> mUpload;
View view;
public FirstFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//retrieveAndSendData();
Log.d("Lifecycle","onCreate called");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("Lifecycle","onCreateView called");
view=inflater.inflate(R.layout.fragment_first,container,false);
mRecyclerView=view.findViewById(R.id.recyler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.d("Lifecycle","onViewCreate called");
retrieveAndSendData();
}
public void retrieveAndSendData()
{
mUpload=new ArrayList<>();
mDatabaseRef= FirebaseDatabase.getInstance().getReference();
ValueEventListener valueEventListener=new ValueEventListener() {
#Override
//get firebase data using datasnapshot (read data)
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapshot : dataSnapshot.getChildren())
{
String key = postSnapshot.getKey();
DatabaseReference databaseReference=mDatabaseRef.child(key);
for (DataSnapshot child: postSnapshot.getChildren())
{
String userBookId = child.getKey();
if(userBookId.equals("city") )
{
break;
}
else
{
// Toast.makeText(getActivity(),userBookId,Toast.LENGTH_LONG).show();
databaseReference.child(userBookId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
carInformation userInformationObj=dataSnapshot.getValue(carInformation.class);
mUpload.add(userInformationObj);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
}
mAdapter = new ImageAdapter(getActivity(),mUpload);
mRecyclerView.setAdapter(mAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getActivity(),databaseError.getMessage(),Toast.LENGTH_SHORT).show();
}
};
mDatabaseRef.addValueEventListener(valueEventListener);
}
uploadUserCarInformation
public class uploadUserCarInformation extends Fragment {
View view;
FirebaseAuth firebaseAuth;
DatabaseReference databaseReference;
StorageReference storageReference;
private StorageTask mUploadTask;
ImageView imageView;
static int PICK_IMAGE=1;
Spinner spin;
// mdatabase.push().getkey() -> generate uniqe id
RadioGroup radioGroupCondition,radioGroupTransmission,radioGroupSupported;
RadioButton radioButtonCondition,radioButtonTranmission,radioButtonSupported;
String radioButtonConditionString,radioButtonSupportedString,radioButtonTransmissionString;
Button addCar,signout;
int selectedIdCondition,selectedIdTransmission,selectedIdSupported;
String ownerName,carName,phoneNuberString,countryString;
TextInputLayout name,carNamePlusModel,phoneNumber,country;
carInformation car_Information=new carInformation();
private ProgressBar progressBar;
private Uri imageUri;
String[] bankNames=new String[374];
InputStream in;
int i=0;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view=inflater.inflate(R.layout.upload_user_car_information,container,false);
firebaseAuth=FirebaseAuth.getInstance();
storageReference=FirebaseStorage.getInstance().getReference("uploads");
name=view.findViewById(R.id.textFieldCarOwner);
carNamePlusModel=view.findViewById(R.id.textFieldCarNameModel);
phoneNumber=view.findViewById(R.id.textFieldPhoneNumber2);
addCar=view.findViewById(R.id.addCar);
signout=view.findViewById(R.id.sign_out);
progressBar=view.findViewById(R.id.progress_bar);
// progressBar.getProgressDrawable().setColorFilter(
// Color.RED, android.graphics.PorterDuff.Mode.SRC_IN);
radioGroupCondition=view.findViewById(R.id.radioGroupCarCondtion);
radioGroupSupported=view.findViewById(R.id.radioGroupCarSupport);
radioGroupTransmission=view.findViewById(R.id.radioGroupCarTransmission);
// progressBar=new ProgressBar(getActivity());
spin = view.findViewById(R.id.Countryspinner2);
imageView=(ImageView) view.findViewById(R.id.selectImage);
//imageView.setImageResource(R.drawable.select_image);
try
{
InputStream fr = this.getResources().openRawResource(R.raw.cities);
BufferedReader br = new BufferedReader(new InputStreamReader(fr));
ArrayList<String> lines=new ArrayList<String>();
String currentLine=br.readLine();
while(currentLine!=null)
{
lines.add(currentLine);
currentLine=br.readLine();
}
Collections.sort(lines);
fr.close(); //closes the stream and release the resources
for(String line : lines)
{
bankNames[i]=line;
// System.out.println(line);
i++;
}
}
catch(IOException e)
{
e.printStackTrace();
}
ArrayAdapter<String> aa=new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_item,bankNames);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
AdapterView.OnItemSelectedListener listener = new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
};
spin.setOnItemSelectedListener(listener);
spin.setAdapter(aa);
signout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firebaseAuth.signOut();
Fragment fragment = new SecondFragment();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.simpleFrameLayout, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
}
});
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onFileChooser();
}
});
addCar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mUploadTask !=null && mUploadTask.isInProgress())
{
Toast.makeText(getActivity(),"Uploading Task",Toast.LENGTH_SHORT).show();
}
else
{
carImageAndDetailUploading();
}
}
});
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PICK_IMAGE && resultCode == RESULT_OK && data != null && data.getData() != null)
{
imageUri = data.getData();
//A powerful image downloading and caching library and get image from library for Android
Picasso.with(getActivity()).load(imageUri).into(imageView);
}
}
private void carImageAndDetailUploading()
{
FirebaseUser user=firebaseAuth.getCurrentUser();
databaseReference= FirebaseDatabase.getInstance().getReference(user.getUid());
selectedIdCondition=radioGroupCondition.getCheckedRadioButtonId();
radioButtonCondition=view.findViewById(selectedIdCondition);
radioButtonConditionString=radioButtonCondition.getText().toString();
selectedIdSupported=radioGroupSupported.getCheckedRadioButtonId();
radioButtonSupported=view.findViewById(selectedIdSupported);
radioButtonSupportedString=radioButtonSupported.getText().toString();
selectedIdTransmission=radioGroupTransmission.getCheckedRadioButtonId();
radioButtonTranmission=view.findViewById(selectedIdTransmission);
radioButtonTransmissionString=radioButtonTranmission.getText().toString();
ownerName=name.getEditText().getText().toString().trim();
carName=carNamePlusModel.getEditText().getText().toString().trim();
phoneNuberString=phoneNumber.getEditText().getText().toString().trim();
countryString=spin.getSelectedItem().toString();
if(TextUtils.isEmpty(ownerName) || TextUtils.isEmpty(carName) || TextUtils.isEmpty(phoneNuberString) || TextUtils.isEmpty(countryString))
{
Toast.makeText(getActivity(),"Please fill the empty fields ",Toast.LENGTH_LONG).show();
return; //return stooping the function to execute further
}
else if(imageUri == null)
{
Toast.makeText(getActivity(),"No file Selected ",Toast.LENGTH_LONG).show();
return;
}
long phone=Long.parseLong(phoneNuberString);
car_Information.setCarName(carName);
car_Information.setOwnerName(ownerName);
car_Information.setUserPhoneNumber(phone);
car_Information.setCountry(countryString);
car_Information.setCarCondtion(radioButtonConditionString);
car_Information.setCarSupported(radioButtonSupportedString);
car_Information.setCarTransmission(radioButtonTransmissionString);
StorageReference fileReference=storageReference.child(System.currentTimeMillis()+ "." + getFileExtension(imageUri));
mUploadTask = fileReference.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//below code user can see 100 % progress bar for 5 sec
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
progressBar.setProgress(0);
}
},5000);
String uniqueKey=databaseReference.push().getKey();
Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
while (!urlTask.isSuccessful());
Uri downloadUrl = urlTask.getResult();
car_Information.setImageUrl(downloadUrl.toString());
car_Information.setUnique_key(uniqueKey);
// databaseReference.child("car details"+car_Information.getUnique_key());
// databaseReference.child("car details"+car_Information.getUnique_key()).setValue(car_Information);
databaseReference.child(car_Information.getUnique_key());
databaseReference.child(car_Information.getUnique_key()).setValue(car_Information);
Toast.makeText(getActivity(),"Successfully Upload",Toast.LENGTH_SHORT).show();
clear_editText();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress=(100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
progressBar.setProgress((int) progress);
}
});
}
private void onFileChooser()
{
Intent intent =new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent,PICK_IMAGE);
//startActivityForResult(Intent.createChooser(intent,"Select Picture"),PICK_IMAGE);
}
private String getFileExtension(Uri uri)
{
//this method for get file extension
ContentResolver cR=getActivity().getContentResolver();
MimeTypeMap mime=MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
private void clear_editText()
{
name.getEditText().setText(" ");
carNamePlusModel.getEditText().setText(" ");
phoneNumber.getEditText().setText(" ");
}
}
enter image description here
enter image description here

javafx: Progress bar to show the progress of the process?

I want to show progress bar while a functionality is running. What is the best way to show it? Basically I am building a program to send multiple mails on a single click. While sending the mail I want to show progress bar while sending the mails.
The best solution in this case is using a Task.
Example:
Task<Parent> yourTaskName = new Task<Parent>() {
#Override
public Parent call() {
// DO YOUR WORK
//method to set progress
updateProgress(workDone, max);
//method to set labeltext
updateMessage(message);
}
};
//ProgressBar
ProgressBar pBar = new ProgressBar();
//Load Value from Task
pBar.progressProperty().bind(yourTaskName.progressProperty());
//New Loading Label
Label statusLabel = new Label();
//Get Text
statusLabel.setText("Loading...");
//Layout
VBox root = new VBox(statusLabel, pBar);
//SetFill Width TRUE
root.setFillWidth(true);
//Center Items
root.setAlignment(Pos.CENTER);
//SetOnSucceeded methode
yourTaskName.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
#Override
public void handle(WorkerStateEvent event) {
System.out.println("Finish");
}
});
//Start Thread
Thread loadingThread = new Thread(yourTaskName);
loadingThread.start();
Hope this helps you.
P.S.: The code in the task run as a Thread...
I implemented what you want last time ,If you want to show progressIndicator or progressBar when sending is running ,try this part of code
senderThreadlive = new Thread(new Runnable() {
#Override
public void run() {
try {
Platform.runLater(new Runnable() {
#Override
public void run() {
ProgressIndicator WaitingSend=new ProgressIndicator();
WaitingSend.setProgress(ProgressIndicator.INDETERMINATE_PROGRESS);
WaitingBox.getChildren().add(WaitingSend);//this is an HBOX
SendMailButton.setDisable(true);
SendMailButton.setText("sending in progress");
}
});
//call Your method of sending
SimpleMail.EmailSender.sendEmail(MailSenderTxt.getText(), MotMailTxt.getText(), DestMailTxt.getText(), ObjetMailTxt.getText(), org.jsoup.Jsoup.parse(ContentMail.getHtmlText()).text());
Platform.runLater(new Runnable() {
#Override
public void run() {
WaitingSend.setProgress(0);
WaitingSend.setVisible(false);
SendMailButton.setDisable(false);
SendMailButton.setText("Send");
}
});
} catch (AuthenticationFailedException e) {
Platform.runLater(new Runnable() {
#Override
public void run() {
//Your popUp here
}
});
} catch (SendFailedException e) {
Platform.runLater(new Runnable() {
#Override
public void run() {
//Your popUp here
}
});
} catch (MessagingException e) {
Platform.runLater(new Runnable() {
#Override
public void run() {
//Your popUp here
}
});
} catch (Exception ex) {
Platform.runLater(new Runnable() {
#Override
public void run() {
//Your popUp here
}
});
}
}
});
senderThreadlive.start();
Just use javafx.scene.control.ProgressBar
Documentation:
http://docs.oracle.com/javafx/2/ui_controls/progress.htm

Android Code for Refresh Button that destroys and recreates Text MediaPlayer (Hangs)!

viewPager4 Fragment Activities
If I click on the Texts that play short sounds, one after another then after sometimes the mediaplayer hangs and doesn't play any sound. But if I'm able to destroy activity and recreate the same activity with refresh button in Action Bar, I'd be able to click sounds again.
So what to write in the code for R.id.item2?
Or there is any other way that continuous clicking on short sounds by these texts is possible without any hang kind of problem?
Following is the reference code:
public class module1 extends FragmentActivity {
static Context con;
static int length = 0;
ViewPager mViewPager;
SectionsPagerAdapter mSectionsPagerAdapter;
static MediaPlayer mediaplayer, mediaplayert, m;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
con = this;
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.mains, menu);
// Just .main into .mains [created new for different behavior of Action Bar]
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.item1) {
Intent in = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.google.com"));
startActivity(in);
}
if (item.getItemId() == R.id.item2) {
//what should i write here? to destroy and recreate the same fragment activity again.
//Problem: After clicking fast on one after another text links, mediaplayert hangs and doesnt play
//Solution: exit app destroy and reopen, then mediaplayer works fine...
//SO, what to write here? kindly help!
}
return super.onOptionsItemSelected(item);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int arg0) {
Fragment ff = new DummySectionFragment1();
switch (arg0) {
case 0:
ff = new DummySectionFragment1();
break;
}
Bundle args = new Bundle();
args.putInt(DummySectionFragment1.ARG_SECTION_NUMBER, arg0 + 1);
ff.setArguments(args);
return ff;
}
#Override
public int getCount() {
return 1;
}
#Override
public CharSequence getPageTitle(int arg0) {
Locale l = Locale.getDefault();
switch (arg0) {
case 0:
return getString(R.string.title_section27).toUpperCase(l);
}
return null;
}
}
public static class DummySectionFragment1 extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment1() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.m01set01, container, false);
// Genius Shot by Stupid vIC//
TextView Text = (TextView) rootView.findViewById(R.id.textView2);
Text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mediaplayert = MediaPlayer.create(MainActivity.con,
R.raw.sound1);
mediaplayert.start();
}
});
TextView Text1 = (TextView) rootView.findViewById(R.id.textView4);
Text1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mediaplayert = MediaPlayer.create(MainActivity.con,
R.raw.sound2);
mediaplayert.start();
}
});
TextView Text2 = (TextView) rootView.findViewById(R.id.textView6);
Text2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mediaplayert = MediaPlayer.create(MainActivity.con,
R.raw.sound3);
mediaplayert.start();
}
});
return rootView;
}
}
#Override
protected void onDestroy() {
if (mediaplayert != null) {
mediaplayert.stop();
mediaplayert= null;
}
super.onDestroy();
}
}

How cancel network request in retrofit and rxjava

I have a multiple buttons; When I press new button, previous(with another button) running request should be interrupted and new runs. How to realize it?
for (button : Buttons) {
button.setOnClickListener(b -> networkApi.getLongContentFromUrl(url)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<JsonElement>() {
#Override
public void onCompleted() {}
#Override
public void onError(Throwable e) {
}
#Override
public void onNext(JsonElement jsonElement) {
//do with result
}
}));
}
You can have a common SerialSubscription and assign your subscriber to it on button click. It will unsubscribe and thus cancel your previous stream:
SerialSubscription serial = new SerialSubscription();
for (Button btn : buttons) {
btn.setOnClickListener(e -> {
Subscriber<JsonElement> s = new Subscriber<JsonElement>() {
#Override
public void onCompleted() {}
#Override
public void onError(Throwable e) {}
#Override
public void onNext(JsonElement jsonElement) {
//do with result
}
};
serial.set(s);
networkApi.getLongContentFromUrl(url)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(s);
});
}

Dispose JavaFX Tasks

I have a static BorderPane with ContextMenu insight Task
Task task = new Task()
{
#Override
protected Void call() throws Exception
{
Platform.runLater(new Runnable()
{
#Override
public void run()
{
try
{
contextMenu = new ContextMenu();
MenuItem item1 = new MenuItem("About");
item1.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent e)
{
System.out.println("About");
}
});
MenuItem item2 = new MenuItem("Preferences");
item2.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent e)
{
System.out.println("Preferences");
}
});
MenuItem item3 = new MenuItem("Close");
item3.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent e)
{
}
});
contextMenu.getItems().addAll(item1, item2, item3);
bp.setOnContextMenuRequested(new EventHandler<ContextMenuEvent>()
{
#Override
public void handle(ContextMenuEvent event)
{
contextMenu.show(bp, event.getScreenX(), event.getScreenY());
event.consume();
}
});
bp.addEventHandler(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>()
{
#Override
public void handle(MouseEvent event)
{
contextMenu.hide();
}
});
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
}
}
});
return null;
}
};
new Thread(task).start();
I noticed that when I close the component which holds the BorderPane the Java Threads are not disposed they are still initialized into the memory. I'm not sure is this caused by the static BorderPane. After the Task is completed the Java Thread should be disposed. Any idea why is this happening?
The problem is not a Task, but the anonymous classes in your Runnable.
In the next piece of code:
bp.setOnContextMenuRequested(new EventHandler<ContextMenuEvent>()
{
#Override
public void handle(ContextMenuEvent event) {
//...
}
});
you introduce an anonymous class extending EventHandler which holds inner link to a Runnable. To solve that you can use nested static class instead.
P.S.: Unfortunately you can't make anonymous class static in Java, see Is it possible to make anonymous inner classes in Java static?

Resources