[Q]Calling a method from another Class - Java for Android App Development

I had a class which i wanted to split into two for better readability and whenever i want to start a method from the second class the code gives NullPointerException.
So i ended up making another dummyclass and realized the problem is that either i dont know to to call from another class in android or am facing another issue.
In java id just make an object and call it but here NullPointerException and app crashes
Code:
public class active extends Activity {
public Button but;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void click()
{
but = (Button)findViewById(R.id.wifiSwitch);
but.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Rebooting...", Toast.LENGTH_LONG).show();
}
});
}
}
In the first class i do the following
Code:
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
rootReqSetting();
mActive = new active();
mActive.click();
return true;
}
the mActive = new active(); and mActive.click(); causes the nullexception.
Some help please ?

Well, first I request that you post logcats in the future.
Second: You call that:
Code:
but = (Button)findViewById(R.id.wifiSwitch);
but.setOnClickListener(new View.OnClickListener() {
What is the system doing? There is a new object whose onCreate method has never been called (just the constructor). For that reason the field but is null (equals "no value"). That's why it crashes.
Third: You do not do it that way:
mActive = new active();
Starting other Activities is done using Intents. Read this: http://www.vogella.com/articles/AndroidIntent/article.html

Where in the code did you inflate the wifi button ????
That is the cause of NullPointerException
Secondly,
You cant instantiate activities like this you must use
startActivity(Intent);
Sent from my GT-S5302 using Tapatalk 2

Thank you for you answer.
The Third part i understood that i should make an intent for the second class.
About the second part you said i didnt understand correctly , can you explain a little more ?
 @sak-venom1997 what do you mean by inflate the button, didnt the whole menu get inflated when i called it in the first ?
Code:
getMenuInflater().inflate(R.menu.main, menu);
or there is something i should add?
And a new window will show when i start the intent without calling anything in it. i just want the button to do what it is supposed to do.

Tell me how the hell did you manage to put a Button in a MenuItem that code would just infate the menu Button would be infalted only if the parent layout is inflated
Sent from my GT-S5302 using Tapatalk 2

sak-venom1997 said:
Tell me how the hell did you manage to put a Button in a MenuItem that code would just infate the menu Button would be infalted only if the parent layout is inflated
Sent from my GT-S5302 using Tapatalk 2
Click to expand...
Click to collapse
can you tell me then what am supposed to do, Am new to android and trying to learn.

You must call
setContentView(R.layout.layout_name);
Where is that button ure reffering
Sent from my GT-S5302 using Tapatalk 2

Related

[Q] How do I make a call through a long press context menu

I orginally had it setup to make a call based on a button click, but now I want the context menu through a long press to do it.
The menu works fine as it finds it way to my call class but I can't figure out how to change it around for it to just start dialing as any android phone does. Can someone suggest what I should change the code below to.
HTML:
public class Dial extends Activity {
Button Btn2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note_edit);
Btn2 = (Button) findViewById(R.id.dial);
Btn2.setOnClickListener(new OnClickListener () {
public void onClick(View v) {
EditText num=(EditText)findViewById(R.id.phone);
String number = "tel:" + num.getText().toString().trim();
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(number));
startActivity(callIntent);
}
});
}
}
take a look at these methods from View
http://developer.android.com/reference/android/view/View.html#setLongClickable(boolean)
http://developer.android.com/refere...ndroid.view.View.OnCreateContextMenuListener)
http://developer.android.com/refere...stener(android.view.View.OnLongClickListener)
should handle the many ways to make an item long clickable

Enabling selection in textview

I am using this android:textIsSelectable and still gets the error:
Code:
TextView does not support text selection. Action mode cancelled.
Can any one please tell me what I might be doing wrong?
obscurant1st said:
I am using this android:textIsSelectable and still gets the error:
Code:
TextView does not support text selection. Action mode cancelled.
Can any one please tell me what I might be doing wrong?
Click to expand...
Click to collapse
Please post the code and also the AP version you are testing the app cant say anything without that
I believe testIsSelectable for TextViews was introduced in Honeycomb, if you want to be able to mimic that feature with lower versions of Android, here's a little workaround :
Use an EditText instead of your TextView and set android:textIsSelectable to false
In your activity's java code, override onLongClickListener and set the EditText to selectable in this method, something like this :
Code:
public class yourClass extends Activity implements onLongClickListener {
EditText yourFakeTextView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.whatever);
yourFakeTextView = (EditText) findViewById(R.id.editText1);
yourFakeTextView.setOnLongClickListener(this);
}
@Override
public boolean onLongClick(View v) {
switch (v.getId()) {
case R.id.editText1:
yourFakeTextView.setTextIsSelectable(true);
break;
default:
return;
}
return false;
}
}
This will make the EditText look like a regular TextView, and when the user long-clicks it, it will allow him to select the text (just like if it was a normal, selectable TextView).
Hope this helps.
I want to enable this feature on ICS and upper version of android. I am testing this on an ics device. There is something which is messed up. I will post the code as soon as I reach home!

[Q] Repeat Button Action

Hello. New here and I hope this post is okay. The "Is this a question?" checkbox says it not the QA forum but it is?
Working on an app that all it's supposed to do is repeat taking a picture every 5 seconds after pressing a button. Now, I've looked at handler, timer, etc but I can't figure out the right way to do it. This is the code currently, and the onCameraClick of course runs when the button on the screen is pressed. I want that button to activate some kind of repeater so the picture gets taken every 5000ms.
Code:
public class CameraImage extends Activity {
public static int cameraID = 0;
public static ImageView image;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cameraimage);
image = (ImageView) findViewById(R.id.imgView);
}
public void onCameraClick(View v)
{
cameraID = 1;
Intent i = new Intent(CameraImage.this, CameraView.class);
startActivityForResult(i, 9999);
}
}
Now, this is something I'd definitely like to use but I'm not sure how to implement this correctly into the code above. Been trying trial and error for past few hours and nothing. Tried out a timer example someone put on another website, 10792454/image-capture-in-android-automatically but not much there.
At the same time however though, I'm not sure if the code should go in the other class with all the functions to run the camera. Any suggestions/tip or help I'd greatly appreciate it.
Try a loop. I'm not sure if you have tried this or if it will work with launching an activity, but it sounds like that is what you want to do. I don't know how you determine when to stop taking pictures but you can use a "for loop" or a "while loop".
example "for loop":
Code:
for (int i; i > someNumber; i++){
//Your code here
}
someNumber would be perhaps the number of pictures you want to take and you can use i to number each picture.
example "while loop":
Code:
Boolean buttonClick = false;
onCreate(){
OnButtonClick(){
OnClick(){
if(buttonClick == true){
buttonClick = false;
}else{
buttonClick = true;
}
onCameraStart(buttonClick);
}
public void onCameraStart(boolean runCamera){
while (runCamera == true){
//Your code here
}
}
This example I showed you how you would be able to start the camera on the first click and stop it when clicked again. The OnButtonClick would be the OnClickListener for your button.
Both these examples may need a little refinement but this should point you in the right direction. Hope this helps. You can put these in threads and pause the thread at the end of the loop for 5 secs so it will wait (I think).
It's simple use a timer and invoke it on first click
Sent from my GT-S5302 using Tapatalk 2

Action Bar and OptionsMenu troubleshooting

I just discovered how to use the action bar to have a OptionsMenu. I just solved a problem with it and I wanted to know if I did it the right way.
What I did
So, I added the menu to a fragment started by an activity, adding to it the setHasOptionsMenu(true) in the onCreate method and setting up the two convenience methods public void onCreateOptionsMenu() and public boolean onOptionsItemSelected() of course setting up the xml first.
The problem
Now, if I rotate my device in landscape mode the button in the action bar duplicates. If I put it in portrait mode again, the number of items stays the same (I'm sure it doesn't actually increase, checked the size in different ways) though.
What I thought and how I solved it
So, I was thinking about some fragment overlaps, but if they actually overlap then I shouldn't notice anything, right?
Is the menu being recreated, while not destroyed when the fragment is destroyed?
I solved the problem removing the item in the menu, in the Fragment.onDestroy() method manually.
Is the menu supposed to be cleared manually, or there is something wrong with my code (eg. fragments overlapping, etc..) ?
domenicop said:
Is the menu supposed to be cleared manually, or there is something wrong with my code (eg. fragments overlapping, etc..) ?
Click to expand...
Click to collapse
Could you please post your code? That would make helping much easier.
nikwen said:
Could you please post your code? That would make helping much easier.
Click to expand...
Click to collapse
Of course. Thanks for the interest.
This is the onCreate method of MainActivity.java, from where I handle the arrangement of fragments on the screen.
Also, place check my comment under the line "Log.d(TAG, "Orientation Portrait detected.");", where I try to explain why I handle fragments in that specific way. It's the way I understood it, but I'm not sure if that's correct.
Code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Initialize the mDatabase
mContactsDatabase = ContactsDatabase.getInstance(getApplicationContext());
// Determine device orientation
mDualPane = getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE;
// Set the fragment that will be changed
mFragmentToReplace = mDualPane ? R.id.contactsPagerFragmentContainer : R.id.portraitFragmentContainer;
// Set up the GUI
FragmentManager fm = getSupportFragmentManager();
if (!mDualPane) {
Log.d(TAG, "Orientation Portrait detected.");
// First, look for previously saved fragments
// findByFragmentId(int id) look for the fragment that was previously associated
// to the resource that has for id the argument passed in. Then, we try to cast it
// to the type of fragment we want, and if that goes all right, we have our fragment.
// Else, null will be returned.
mContactListFragment = (ContactListFragment) fm.findFragmentById(R.id.portraitFragmentContainer);
if (mContactListFragment == null) {
mContactListFragment = ContactListFragment.newInstance(mContactsDatabase);
fm.beginTransaction()
.replace(R.id.portraitFragmentContainer, mContactListFragment)
.commit();
}
}
else {
Log.d(TAG, "Orientation Landscape detected.");
// First, look for previously saved fragments
mContactListFragment = (ContactListFragment) fm.findFragmentById(R.id.landscapeFragmentContainer);
mContactsPagerFragment = (ContactsPagerFragment) fm.findFragmentById(R.id.contactsPagerFragmentContainer);
if (mContactListFragment == null) {
mContactListFragment = ContactListFragment.newInstance(mContactsDatabase);
fm.beginTransaction()
.replace(R.id.contactListFragmentContainer, mContactListFragment)
.commit();
}
if (mContactsPagerFragment == null) {
final int FIRST_CONTACT_POSITION = 0;
mContactListFragment = ContactListFragment.newInstance(mContactsDatabase);
mContactsPagerFragment =
ContactsPagerFragment.newInstance(FIRST_CONTACT_POSITION, mContactsDatabase);
fm.beginTransaction()
.replace(R.id.contactsPagerFragmentContainer, mContactsPagerFragment)
.commit();
}
}
}
This are the relevant pieces of the ContactListFragment.java, that have something to do with the menu
Note that I changed the way I checked for double menu entries.
Now I check if (menu.size() != 1), because I have just one item in there.
If I remove that clause, there will be two item in the menu after rotating to landscape mode, and if I take the device back to portrait mode, the two items will remain two. That's so even if I change from landscape to portrait and vice versa a hundred times from now, the menu items will always be two.
Code:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
Bundle args = getArguments();
mDatabase = (ContactsDatabase) args.getSerializable(DATABASE);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
if (menu.size() != 1) {
inflater.inflate(R.menu.contact_list_fragment_menu, menu);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.addContactMenu:
mCallback.onAddContactMenuOptionSelected();
default:
return super.onOptionsItemSelected(item);
}
}
domenicop said:
I just discovered how to use the action bar to have a OptionsMenu. I just solved a problem with it and I wanted to know if I did it the right way.
What I did
So, I added the menu to a fragment started by an activity, adding to it the setHasOptionsMenu(true) in the onCreate method and setting up the two convenience methods public void onCreateOptionsMenu() and public boolean onOptionsItemSelected() of course setting up the xml first.
The problem
Now, if I rotate my device in landscape mode the button in the action bar duplicates. If I put it in portrait mode again, the number of items stays the same (I'm sure it doesn't actually increase, checked the size in different ways) though.
What I thought and how I solved it
So, I was thinking about some fragment overlaps, but if they actually overlap then I shouldn't notice anything, right?
Is the menu being recreated, while not destroyed when the fragment is destroyed?
I solved the problem removing the item in the menu, in the Fragment.onDestroy() method manually.
Is the menu supposed to be cleared manually, or there is something wrong with my code (eg. fragments overlapping, etc..) ?
Click to expand...
Click to collapse
I agree with nikwen but broadly the idea is...
- the menu belongs to the Activity not the Fragment.
- for an Activity for which you'd like an options menu you override onCreateOptionsMenu and do 2 things...
1/ call menu.add(...) for each menu item
2/ return 'true' at the end, so that your menu can be displayed
Also, see the Activity docs for onCreateOptionsMenu()
"This is only called once, the first time the options menu is displayed.
To update the menu every time it is displayed, see onPrepareOptionsMenu(Menu)."
If you want to add menu options to the Activity menu from within a Fragment you can also..
- override setHasOptionsMenu() in Fragment to return true
- override onCreateOptionsMenu() to add any items you like (just like you did at the Activity level)
- override onDestroyOptionsMenu()
The key thing here is that onCreateOptionsMenu() in Fragment is adding to the Activity menu.
It's hard to see without debugging exactly what's going on here but watch for calls to all of the above methods in Activity and Fragment and that will probably tell you what's going on.
If it is possible to control all menu options at the Activity level instead of the Fragment level, I would do that.
If not, and you need to use the Fragment menu methods, beware of Android's Fragment management (saving / restoring state)
Also, make sure your Fragments have an ID and/or tag.
(from the docs..)
"The fragment being instantiated must have some kind of unique identifier so that it can be re-associated with a previous instance if the parent activity needs to be destroyed and recreated. This can be provided these ways:
If nothing is explicitly supplied, the view ID of the container will be used.
android:tag can be used in <fragment> to provide a specific tag name for the fragment.
android:id can be used in <fragment> to provide a specific identifier for the fragment."
Finally, if all else fails, using Menu's findItem() before calling add() would be a safeguard, I suppose.
---------- Post added at 10:14 PM ---------- Previous post was at 09:52 PM ----------
domenicop said:
Of course. Thanks for the interest.
Click to expand...
Click to collapse
Sorry caught in the crossfire - have only just seen your code.
I think much of the above applies.
Set the menu up in the Activity instead of the Fragment, if you can.
I would also consider using layout-port and layout-land to control your two different layouts.
PicomatStudios said:
I agree with nikwen but broadly the idea is...
- the menu belongs to the Activity not the Fragment.
- for an Activity for which you'd like an options menu you override onCreateOptionsMenu and do 2 things...
1/ call menu.add(...) for each menu item
2/ return 'true' at the end, so that your menu can be displayed
Also, see the Activity docs for onCreateOptionsMenu()
"This is only called once, the first time the options menu is displayed.
To update the menu every time it is displayed, see onPrepareOptionsMenu(Menu)."
If you want to add menu options to the Activity menu from within a Fragment you can also..
- override setHasOptionsMenu() in Fragment to return true
- override onCreateOptionsMenu() to add any items you like (just like you did at the Activity level)
- override onDestroyOptionsMenu()
The key thing here is that onCreateOptionsMenu() in Fragment is adding to the Activity menu.
It's hard to see without debugging exactly what's going on here but watch for calls to all of the above methods in Activity and Fragment and that will probably tell you what's going on.
If it is possible to control all menu options at the Activity level instead of the Fragment level, I would do that.
If not, and you need to use the Fragment menu methods, beware of Android's Fragment management (saving / restoring state)
Also, make sure your Fragments have an ID and/or tag.
(from the docs..)
"The fragment being instantiated must have some kind of unique identifier so that it can be re-associated with a previous instance if the parent activity needs to be destroyed and recreated. This can be provided these ways:
If nothing is explicitly supplied, the view ID of the container will be used.
android:tag can be used in <fragment> to provide a specific tag name for the fragment.
android:id can be used in <fragment> to provide a specific identifier for the fragment."
Finally, if all else fails, using Menu's findItem() before calling add() would be a safeguard, I suppose.
---------- Post added at 10:14 PM ---------- Previous post was at 09:52 PM ----------
Sorry caught in the crossfire - have only just seen your code.
I think much of the above applies.
Set the menu up in the Activity instead of the Fragment, if you can.
I would also consider using layout-port and layout-land to control your two different layouts.
Click to expand...
Click to collapse
Wow. thanks for that detailed answer. :good: (Why have I used all my thanks?)
I've always put it into the Activity as well but it might make sense to add it to the Fragment sometimes. For example if you need the same Fragment in multiple Activities...
In that case you'd need to add a listener to the item in the Fragment method though.
@PicomatStudio Thank you for the detailed answer, I really appreciate that =)
Now I'm creating the menu in the activity and I don't have to worry about the fragments life cycle anymore.
The only problem is: I didn't get the menuInflater for free here, I guess it's because of the fact that in the Fragment scenario, I had to use the Activity inflater, whereas here in the activity, I can get my own, with getMenuInflater().
Here's the way I modified it, now is in MainActivity.java.
Please report back if you find something strange
Code:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (getSupportFragmentManager().findFragmentByTag(CONTACT_LIST_FRAGMENT) != null)
getMenuInflater().inflate(R.menu.contact_list_fragment_menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.addContactMenu:
onAddContactMenuOptionSelected();
default:
return super.onOptionsItemSelected(item);
}
}
domenicop said:
@PicomatStudio Thank you for the detailed answer, I really appreciate that =)
Now I'm creating the menu in the activity and I don't have to worry about the fragments life cycle anymore.
The only problem is: I didn't get the menuInflater for free here, I guess it's because of the fact that in the Fragment scenario, I had to use the Activity inflater, whereas here in the activity, I can get my own, with getMenuInflater().
Here's the way I modified it, now is in MainActivity.java.
Please report back if you find something strange
Code:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (getSupportFragmentManager().findFragmentByTag(CONTACT_LIST_FRAGMENT) != null)
getMenuInflater().inflate(R.menu.contact_list_fragment_menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.addContactMenu:
onAddContactMenuOptionSelected();
default:
return super.onOptionsItemSelected(item);
}
}
Click to expand...
Click to collapse
I don't tend to use MenuInflater (just menu.add()..)
But looking at the docs it takes a Context so could you do..
Code:
new MenuInflater(this);
.. from your Activity ?
On a general design point the less your Activity depends on its Fragments the better, I reckon.
domenicop said:
The only problem is: I didn't get the menuInflater for free here, I guess it's because of the fact that in the Fragment scenario, I had to use the Activity inflater, whereas here in the activity, I can get my own, with getMenuInflater().
Click to expand...
Click to collapse
Well, you can get one:
Code:
getActivity().getMenuInflater();

[Q]Service doesn't stop even after calling stopService

Here is the service
Code:
public class SearchService extends IntentService {
public SearchService() {
super("SearchService");
// TODO Auto-generated constructor stub
}
// Binder given to clients
/**
* Class used for the client Binder. Because we know this service always
* runs in the same process as its clients, we don't need to deal with IPC.
*/
[user=439709]@override[/user]
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
String FILENAME=intent.getStringExtra("name");
String FILEPATH=intent.getStringExtra("path");
ArrayList a=getSearchResult(new File(FILEPATH),FILENAME);
Toast.makeText(this, "Search Completed", Toast.LENGTH_LONG).show();
publishResults(a);
this.stopSelf();
}
private void publishResults(ArrayList<File> outputPath) {
Intent intent = new Intent("notify");
ArrayList<String> a=new ArrayList<String>();
for(int i=0;i<outputPath.size();i++){a.add(outputPath.get(i).getPath());}
intent.putStringArrayListExtra("path", a);
sendBroadcast(intent);
} private void publishResults(String a) {
Intent intent = new Intent("current");
intent.putExtra("name", a);
sendBroadcast(intent);
}}
I am using it like this
Code:
final Intent intent = new Intent(getActivity(), SearchService.class);
intent.putExtra("path",fpath);
intent.putExtra("name",a);
p=new ProgressDialog(getActivity());
p.setCancelable(false);
p.setTitle("Searching Files");
p.setMessage("Please Wait");
p.getWindow().addFlags( WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON );
p.setButton("Cancel", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface p1, int p2)
{
getActivity().stopService(new Intent(getActivity(),SearchService.class));
// TODO: Implement this method
}
});
p.show();
getActivity().startService(intent);
but even after pressing cancel button,broadcast is received in activity
Sent from my GT-S5570 using XDA Premium 4 mobile app
A service to display a toast and brodcast the data it recieved looks like a design flaw
anyways you are extending the intent service i guess it does not implement stopService() rather it stops automatically when it has nothing to do[not sure with it please check documentation for IntentService never actually used one of those ]
I guess you need to extend the Service class from package android.app
Sent from my GT-S5302 using Tapatalk 2
sak-venom1997 said:
A service to display a toast and brodcast the data it recieved looks like a design flaw
anyways you are extending the intent service i guess it does not implement stopService() rather it stops automatically when it has nothing to do[not sure with it please check documentation for IntentService never actually used one of those ]
I guess you need to extend the Service class from package android.app
Sent from my GT-S5302 using Tapatalk 2
Click to expand...
Click to collapse
Actually I am using toast just for debugging.I am learning services. so I might be wrong at places.I made this service to search for files while an indeterminate progress dialog shows in activity till the broadcast of result is received.
I used intentservice because it was supposed to do one work at a time.please suggest me exact ways to use service in my case.I also want to make sure that if activity is paused(minimized) then, when task is completed activity is also started
Sent from my GT-S5570 using XDA Premium 4 mobile app
arpitkh96 said:
Actually I am using toast just for debugging.I am learning services. so I might be wrong at places. I made this service to search for files while an indeterminate progress dialog shows in activity till the broadcast of result is received.
I used intentservice because it was supposed to do one work at a time.please suggest me exact ways to use service in my case.I also want to make sure that if activity is paused(minimized) then, when task is completed activity is also started
Click to expand...
Click to collapse
You can still use an IntentService to do that. To stop it just pass an Intent to it with a boolean extra indicating that you don't want to do anything. You'll need only one more if clause in the onHandleIntent of the service.
SimplicityApks said:
You can still use an IntentService to do that. To stop it just pass an Intent to it with a boolean extra indicating that you don't want to do anything. You'll need only one more if clause in the onHandleIntent of the service.
Click to expand...
Click to collapse
That didnt worked I used it like this.
Code:
@Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
String FILENAME=intent.getStringExtra("name");
String FILEPATH=intent.getStringExtra("path");
boolean b=intent.getBooleanExtra("run",false);
while(b){
ArrayList<File> a=getSearchResult(new File(FILEPATH),FILENAME);
publishResults(a);
this.stopSelf();}
}
Code:
final Intent intent = new Intent(getActivity(), SearchService.class);
intent.putExtra("path",fpath);
intent.putExtra("name",a);
intent.putExtra("run",true);
p=new ProgressDialog(getActivity());
p.setCancelable(false);
p.setTitle("Searching Files");
p.setMessage("Please Wait");
p.getWindow().addFlags( WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON );
p.setButton("Cancel", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface p1, int p2)
{
Intent j=new Intent(getActivity(),SearchService.class);
j.putExtra("run",false);
getActivity().stopService(j);
// TODO: Implement this method
}
});
p.show();
getActivity().startService(intent);
Sent from my GT-S5570 using XDA Premium 4 mobile app
arpitkh96 said:
That didnt worked I used it like this.
Code:
@Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
String FILENAME=intent.getStringExtra("name");
String FILEPATH=intent.getStringExtra("path");
boolean b=intent.getBooleanExtra("run",false);
while(b){
ArrayList<File> a=getSearchResult(new File(FILEPATH),FILENAME);
publishResults(a);
this.stopSelf();}
}
Code:
final Intent intent = new Intent(getActivity(), SearchService.class);
intent.putExtra("path",fpath);
intent.putExtra("name",a);
intent.putExtra("run",true);
p=new ProgressDialog(getActivity());
p.setCancelable(false);
p.setTitle("Searching Files");
p.setMessage("Please Wait");
p.getWindow().addFlags( WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON );
p.setButton("Cancel", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface p1, int p2)
{
Intent j=new Intent(getActivity(),SearchService.class);
j.putExtra("run",false);
getActivity().stopService(j);
// TODO: Implement this method
}
});
p.show();
getActivity().startService(intent);
Click to expand...
Click to collapse
First, if you look in the Dokumentation for IntentService, it says that you should not call stopSelf because it is already implemented to do that when there are no intents left. So It really should be easier to use a Service if you want to stop it like that.
If you want to keep using the intent service, I'd instead use a boolean instance variable which is checked in the publishResults method so just let the service do its work, but before it is published in the UI thread check if the dialog was canceled or not. Otherwise because you have two threads you can't be sure when the other thread receives the boolean change.
To me it seems like you could also use an AsyncTask to handle the threading and that class is easily cancelable .
SimplicityApks said:
First, if you look in the Dokumentation for IntentService, it says that you should not call stopSelf because it is already implemented to do that when there are no intents left. So It really should be easier to use a Service if you want to stop it like that.
If you want to keep using the intent service, I'd instead use a boolean instance variable which is checked in the publishResults method so just let the service do its work, but before it is published in the UI thread check if the dialog was canceled or not. Otherwise because you have two threads you can't be sure when the other thread receives the boolean change.
To me it seems like you could also use an AsyncTask to handle the threading and that class is easily cancelable .
Click to expand...
Click to collapse
I cannot use Asynctask ,as operation could be long.checking the boolean before publish is good idea.I will try this
Sent from my GT-S5570 using XDA Premium 4 mobile app

Categories

Resources