Preference changes only happen when restarting the app - Android Software Development

Hey there! I was coding an app I added a preferences menu, and it works, but changes happen only when I restart the application,anyone knows how to make changes happen whithout exitting the app??? Thanks in advance
My code ( from main activity):
preferencias = preferenceManager.getDefaultSharedPreferences(TimeToSpeechActivity.this);
OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
//nothing here, do I have to put anything?
}
};
preferencias.registerOnSharedPreferenceChangeListener(listener);
getPrefs();
changefont(fuente, letra);
if (boole == true) {fontcolors();}
private void getPrefs(){
fuente = Typeface.createFromAsset(getAssets() , preferencias.getString("elegirfuente", "fonts/Default.ttf"));
letra = Integer.parseInt(preferencias.getString("fontstyle", "0"));
bol = preferencias.getBoolean("randomcolors", true);
}
Click to expand...
Click to collapse
I have nothing put in preference activity, do i have to put anything?
Also, do I have to edit this?: (SharedPreferences prefs, String key) I ask this because i havent created prefs and key varibles
Thanks in advance!!!

It should update for you if you put getPrefs() inside the sharedpreferences listener
Sent from my Xoom using xda premium

thanks, but if I do that I get a nullpointer exception, I think its caused because the params I use to set "changefont(fuente, letra);" and "if (boole == true) {fontcolors();}" have null value....another idea ,please? I am breaking my head with this...
My updated code:
preferencias = preferenceManager.getDefaultSharedPreferences(Time ToSpeechActivity.this);
OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener () {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
getPrefs();
}
};
preferencias.registerOnSharedPreferenceChangeListener(listener);
changefont(fuente, letra);
if (boole == true) {fontcolors();}
private void getPrefs(){
fuente = Typeface.createFromAsset(getAssets() , preferencias.getString("elegirfuente", "fonts/Default.ttf"));
letra = Integer.parseInt(preferencias.getString("fontstyle ", "0"));
bol = preferencias.getBoolean("randomcolors", true);
}
Click to expand...
Click to collapse
i tried to put changefont and fontcolors functions inside the sharedpreference listener... but if i do, that options are not set... so I think there is a problem with the listener...why???
I will add the code of my preference class:
public class PantallaOpciones extends PreferenceActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.opciones);
}
}
Click to expand...
Click to collapse

One way ive always done preference updates was to use a dedicated method for updating (like you have with openPrefs()) then calling it after operations:
runOperation(){
updatePrefsMethod();
getPrefsMethod();
}
If i was near my pc i could give you a more solid example, but alas, im stuck at work lol
Also, use the stacktraces to check which line gives it null (itll say something like "at com.yourapp.identifier(offending Class - line number)
maybe if you a null check on the boolean for color that sets it false, you may not get the nullPointerException
Sent from my Xoom using xda premium

z3nful said:
One way ive always done preference updates was to use a dedicated method for updating (like you have with openPrefs()) then calling it after operations:
runOperation(){
updatePrefsMethod();
getPrefsMethod();
}
If i was near my pc i could give you a more solid example, but alas, im stuck at work lol
Also, maybe if you a null check on the boolean for color that sets it false, you may not get the nullPointerException
Sent from my Xoom using xda premium
Click to expand...
Click to collapse
OK, could you give me an example as soon as you can,please?

Related

New Developer - Need Some Advise on RSS Code

Hello,
I'm new to developing software in Java, but especially with Android. I am going through a tutorial on how to create an RSS Feed Reader and so far I've got it mostly working, but I've got a few bugs I can't seem to figure out.
I wanted to post images, but it wouldn't let me, but anyway:
main activity - title, pubdate both work, as does each article's title.
after clicking on a title, the other activity is launched and the article is shown:
showdescription activity is launched - title, pubdate, link all work and display correctly.
bug: description does not always display everything or even display at all depending on the xml source.
I'm wondering if my problem is somewhere these code snippets, as this tutorial was written some time ago.
These are pretty basic, so I'm doubting the problem is in here.
RSSHandler said:
if (localName.equals("description"))
{
currentstate = RSS_DESCRIPTION;
return;
}
...
case RSS_DESCRIPTION:
_item.setDescription(theString);
currentstate = 0;
break;
Click to expand...
Click to collapse
RSSItem said:
void setDescription(String description)
{
_description = description;
}
...
String getDescription()
{
return _description;
}
Click to expand...
Click to collapse
This is where I believe the problem exists, in the onItemClick method or the ShowDescription class.
RSSReader said:
public void onItemClick(AdapterView parent, View v, int position, long id)
{
Log.i(tag,"item clicked! [" + feed.getItem(position).getTitle() + "]");
Intent itemintent = new Intent(this,ShowDescription.class);
Bundle b = new Bundle();
b.putString("title", feed.getItem(position).getTitle());
b.putString("description", feed.getItem(position).getDescription());
b.putString("link", feed.getItem(position).getLink());
b.putString("pubdate", feed.getItem(position).getPubDate());
itemintent.putExtra("android.intent.extra.INTENT", b);
//startSubActivity(itemintent, 0);
startActivity(itemintent);
}
Click to expand...
Click to collapse
ShowDescription said:
public class ShowDescription extends Activity
{
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.showdescription);
String theStory = null;
Intent startingIntent = getIntent();
if (startingIntent != null)
{
Bundle b = startingIntent.getBundleExtra("android.intent.extra.INTENT");
if (b == null)
{
theStory = "bad bundle?";
}
else
{
theStory = b.getString("title")
+ "\n\n" + b.getString("pubdate")
+ "\n\n" + b.getString("description")
+ "\n\nView Website:\n" + b.getString("link");
}
}
else
{
theStory = "Information Not Found.";
}
TextView db= (TextView) findViewById(R.id.storybox);
db.setText(theStory);
Button backbutton = (Button) findViewById(R.id.back);
backbutton.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
finish();
}
});
}
}
Click to expand...
Click to collapse
Originally the tutorial called for "startSubActivity" for starting the ShowDescription activity, but that doesn't seem to exist anymore?
The XML source I'm using can't be displayed because I can't link in outside pages, but I can PM it to you if you'd like.
I have tried using a .replaceAll("\\<.*?>","") but it didn't seem to change much about whether the <description> tag's content is displayed or not.
Anyway, if anyone takes the time to look at this, it'd be greatly appreciated, and thank you!
If you need me to post anymore code let me know.
So I think I've figured it out, well somewhat.
While stepping through the code, the <description> tag's content consists of a single < character. Then the parser goes through two more tags that contain, p and > before actually hitting the content I want.
So it looks something like this:
<description>
<
<?>
p
<?>
>
<?>
"wanted content"
</?>
</?>
</?>
</description>
Click to expand...
Click to collapse

[Q] DatePickerDialog cancelclick

Hi there!
I have been trying to catch the Cancel click of a DatePickerDialog, because I want to do some additional stuff, when the user clicks on the Cancel Button.
I tried it like described in the second answer from esilver from this Question:
http://stackoverflow.com/questions/...erner-of-datepicker-dialog?tab=active#tab-top
But I can't get it to work like that. When do I have to call this onClick method?
Would be great if someone could help me with that!
Thanks!
cTrox said:
Hi there!
I have been trying to catch the Cancel click of a DatePickerDialog, because I want to do some additional stuff, when the user clicks on the Cancel Button.
I tried it like described in the second answer from esilver from this Question:
http://stackoverflow.com/questions/...erner-of-datepicker-dialog?tab=active#tab-top
But I can't get it to work like that. When do I have to call this onClick method?
Would be great if someone could help me with that!
Thanks!
Click to expand...
Click to collapse
the "checked" solution in that example seems wrong to me. but the second one people voted up seems correct.
You can also set the onDissmissListener which will catch if the user backs out with the back key ( recommended for user friendliness )
have a look here:
http://developer.android.com/refere...id.content.DialogInterface.OnDismissListener)
Also, since DatePickerDialog is a subclass of AlertDialog, you can set the buttons the same way:
http://developer.android.com/guide/topics/ui/dialogs.html#AlertDialog
That should get you started but feel free to post back if you get stuck again. And post the code you are using.
Also, one other thing, it might be useful to keep a private reference to your dialog in your activity class.
All those examples (in the API docs and tutorials) always show a new dialog created when "onCreateDialog(int ID)" is called by the OS on your activity and they never save any sort of reference to it. They give you just enough code to hang yourself
Anyways, while this is a perfectly normal way to do things, it doesnt give you a chance to follow what is actually happening with the dialog. It also makes it harder to reference your dialog from elsewhere in the activity.
Keeping a reference, and exploring the onPrepareDialog(int ID) method are good for learning what the OS is doing with your dialog. (IMHO)
hth
Thanks a lot for your answers. But I still can't figure out how to do it.
Here's my current Code:
Code:
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker datePicker, int year, int monthOfYear,
int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
// do some more stuff...
}
};
Code:
protected Dialog onCreateDialog(int id) {
Calendar cDate = Calendar.getInstance();
int cyear = cDate.get(Calendar.YEAR);
int cmonth = cDate.get(Calendar.MONTH);
int cday = cDate.get(Calendar.DAY_OF_MONTH);
switch(id){
case DATE_DIALOG_ID:
return new DatePickerDialog(this, mDateSetListener, cyear, cmonth, cday);
}
return null;
}
With that I can just call showDialog(DATE_DIALOG_ID); and I get the dialog. Now, where do I have to implement this OnDismissListener and how?
Thanks!
there are lots of ways to do this but I broke it out into several parts so hopefully it seems more obvious what is happening.
Code:
//here's our field reference we could use later or reuse or whatever
private DatePickerDialog dateDialog = null;
protected Dialog onCreateDialog(int id)
{
//your calendar code here... just removed to save space
switch(id)
{
case DATE_DIALOG_ID:
dateDialog = new DatePickerDialog(this, mDateSetListener, cyear, cmonth, cday);
dateDialog.setButton ( DialogInterface.BUTTON_NEGATIVE, android.R.string.cancel, cancelBtnListener );
dateDialog.setOnDismissListener ( listener );
break;
}
return dateDialog;
}
//our dismiss listener
protected DialogInterface.OnDismissListener dismissListener = new OnDismissListener( )
{
@Override
public void onDismiss ( DialogInterface dialog )
{
// do your thang here
}
};
//our click listener
protected DialogInterface.OnClickListener cancelBtnListener = new OnClickListener( )
{
@Override
public void onClick ( DialogInterface dialog, int which )
{
dialog.dismiss ( );
// since we dismiss here, the next listener to get called
// is the dismiss listener. now we'll have consistent behavoir
}
};
Ah thank you very much! I was always confused, where to set the Button and the OnDismissListener.
It works perfectly like that!

[Guide] Listeners in Java development

You are new to java development and want to get buttons working?
Maybe you are a Pro but want a reminder?
whatever you are this Guide is to help you to make buttons/check boxes...etc working and functional
Some people are distracted between guides over internet and want the easiest way to get their project working, me too
Steps :
1-Define the button :
Code:
Button btn1;
Checkbox chkbox1;
RadioButton radio1;
2- Intialize it :
Code:
btn1 = (Button) findViewById(R.id.btn1);
chkbox1= (Checkbox ) findViewById(R.id.chkbox1);
radio1= (RadioButton) findViewById(R.id.radio1);
3-Add the listener :
Button:
Code:
btn1.setOnClickListener(new OnClickListener() {
@SuppressWarnings("deprecation")
@Override
public void onClick(View arg0) {
//Write awesome code here
}
});
CheckBox :
Code:
chkbox1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (start.isChecked()) {
//if the checkbox checked
} else {
//if not checked
}
}
});
}
radio button:
Code:
public void onRadioButtonClicked(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch(view.getId()) {
case R.id.radio1:
if (checked){
}
else{
}
break;
}
}
or use it in a radio Group :
Code:
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radio1:
if (checked)
//Write code
break;
case R.id.radio2:
if (checked)
//Write code
break;
}
}
Also insted of this you can use a onCheckedChanged for a radio button (Thanks for GalaxyInABox)
Code:
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
switch (radioGroup.getCheckedRadioButtonId()) {
//Code
}
}
____________________________________________________________________
____________________________________________________________________
Also you can implement a Onclicklistener for the whole class to save resources : (thanks for @Jonny )
after defining and initializing your objects add this :
Code:
OnClickListener click_listener = new OnClickListener() {
public void onClick(View view) {
int id = view.getId();
if (id == your_id) {
//do stuff for this object
} else if (id == your_id2) {
//do other stuff for diffrent object
} else if (id == your_id3) {
//and so on
}
}
};
To do list :
-add on touch listeners
-add on drag listeners
Note : you can add a click listener to almost any thing (Textview or imageView or even EditText) just using the same method of adding listener to button
also there is some other ways to add a listener but this is the fastest and less disturbing :good:
If this guide is useful, press thanks
@ OP
CheckBox and RadioButtons don't they provide a CheckedChangeListener ?
Sent from my GT-S5302 using Tapatalk 2
sak-venom1997 said:
@ OP
CheckBox and RadioButtons don't they provide a CheckedChangeListener ?
Click to expand...
Click to collapse
Yes, and now you can use
Code:
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
switch (radioGroup.getCheckedRadioButtonId()) {
//Code
}
}
to get the checked button. They are pretty much the same, but you can use view.getTag() easier in the first one.
And @mohamedrashad please show how to put the listener into a inner class. Many people don't know/use it, but it's that useful!
GalaxyInABox said:
Yes, and now you can use
Code:
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
switch (radioGroup.getCheckedRadioButtonId()) {
//Code
}
}
to get the checked button. They are pretty much the same, but you can use view.getTag() easier in the first one.
Click to expand...
Click to collapse
I meant that the op shuld edit this guide and use those instead of OnCickListeners
GalaxyInABox said:
And @mohamedrashad please show how to put the listener into a inner class. Many people don't know/use it, but it's that useful!
Click to expand...
Click to collapse
ya new with java8 it will be a nice usage scenario of lambadas
Sent from my GT-S5302 using Tapatalk 2
GalaxyInABox said:
Yes, and now you can use
Code:
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
switch (radioGroup.getCheckedRadioButtonId()) {
//Code
}
}
to get the checked button. They are pretty much the same, but you can use view.getTag() easier in the first one.
And @mohamedrashad please show how to put the listener into a inner class. Many people don't know/use it, but it's that useful!
Click to expand...
Click to collapse
sak-venom1997 said:
@ OP
CheckBox and RadioButtons don't they provide a CheckedChangeListener ?
Sent from my GT-S5302 using Tapatalk 2
Click to expand...
Click to collapse
ok, i will add this
You can also add onClick property in XML and then handle it in a code.
Awesome tutorial! Thank you very much!
Please, you could share more related knowledge. It's really useful!
Also, an activity can be a listener. In this case:
MyActivity implements onClickListener {
btn1.setOnClickListener(this);
public void onClick (View v) {
//your code
}
}
For this kind of stuff, using some well known libraries from well known Android dev is a must.
https://github.com/JakeWharton/butterknife
Very powerfull, super easy to use, error prone and without any performance impact.
rafalniski said:
You can also add onClick property in XML and then handle it in a code.
Click to expand...
Click to collapse
SKAm69 said:
Also, an activity can be a listener. In this case:
MyActivity implements onClickListener {
btn1.setOnClickListener(this);
public void onClick (View v) {
//your code
}
}
Click to expand...
Click to collapse
will add them both, although I don't like this way
Mohamedrashad. Thanks a lot.
Sent from my P880 using Tapatalk
If you have multiple clickable objects then it's best to use just 1 onClickListener for all of them and use a switch on their ID's. This reduces resource usage as you only have 1 listener, not 5, 10 or however many you would have otherwise. It's not essential for this but it is a best practice if you want to streamline your code.
Mobile right now so I can't chuck up an example until tomorrow evening or so.
You dude had a great thread. Its helping me. Bravoo !!
Sent from my GT-I8190 using XDA Premium 4 mobile app
As @Jonny already pointed out: Use your class as a listener instead of creating a new (anonymous) inner class! Say you have a ListView, instead of doing this:
Code:
class MyFragment extends Fragment {
private void someMethod() {
((ListView) getView().findViewById(R.id.someListView)).setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Code...
}
});
}
}
you can do this:
Code:
class MyFragment extends ListFragment implements AdapterView.OnItemClickListener, View.OnClickListener {
private void someMethod() {
((ListView) getView().findViewById(R.id.someListView)).setOnItemClickListener(this);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Code...
}
}
This may look stupid, but when you have many listeners, you can un-clutter it. In my opinion this is the best way. You can also add "this" class as listener for as many ui elements as you want(because all of them extend view, you can use one OnClickListener), then you only need to have a switch statement to distinguish between the views. And voila, you prevented cluttering the code with boilerplate stuff.
Example using code in an app I'm making - app for my school.
Code:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Some code here for view/layouts etc
websitebutton = (Button) view.findViewById(R.id.website_btn);
facebookbutton = (Button) view.findViewById(R.id.facebook_btn);
twitterbutton = (Button) view.findViewById(R.id.twitter_btn);
websitebutton.setOnClickListener(handler);
facebookbutton.setOnClickListener(handler);
twitterbutton.setOnClickListener(handler);
return view;
}
OnClickListener handler = new OnClickListener() {
public void onClick(View view) {
switch (view.getId()) {
case R.id.website_btn :
Uri website = Uri.parse("http://wirralgrammarboys.com/");
Intent websiteintent = new Intent(Intent.ACTION_VIEW, website);
startActivity(websiteintent);
break;
case R.id.facebook_btn :
Uri facebook = Uri.parse("https://www.facebook.com/WirralGSB");
Intent facebookintent = new Intent(Intent.ACTION_VIEW, facebook);
startActivity(facebookintent);
break;
case R.id.twitter_btn :
Uri twitter = Uri.parse("https://twitter.com/WGSB");
Intent twitterintent = new Intent(Intent.ACTION_VIEW, twitter);
startActivity(twitterintent);
break;
}
}
};
Jonny said:
Example using code in an app I'm making.
Code:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Some code here for view/layouts etc
websitebutton = (Button) view.findViewById(R.id.website_btn);
facebookbutton = (Button) view.findViewById(R.id.facebook_btn);
twitterbutton = (Button) view.findViewById(R.id.twitter_btn);
websitebutton.setOnClickListener(handler);
facebookbutton.setOnClickListener(handler);
twitterbutton.setOnClickListener(handler);
return view;
}
OnClickListener handler = new OnClickListener() {
public void onClick(View view) {
int id = view.getId();
if (id == R.id.website_btn) {
Uri website = Uri.parse("http://wirralgrammarboys.com/");
Intent websiteintent = new Intent(Intent.ACTION_VIEW, website);
startActivity(websiteintent);
} else if (id == R.id.facebook_btn) {
Uri facebook = Uri.parse("https://www.facebook.com/WirralGSB");
Intent facebookintent = new Intent(Intent.ACTION_VIEW, facebook);
startActivity(facebookintent);
} else if (id == R.id.twitter_btn) {
Uri twitter = Uri.parse("https://twitter.com/WGSB");
Intent twitterintent = new Intent(Intent.ACTION_VIEW, twitter);
startActivity(twitterintent);
}
}
};
Click to expand...
Click to collapse
i'm adding this to OP if you don't mind jonny
mohamedrashad said:
i'm adding this to OP if you don't mind jonny
Click to expand...
Click to collapse
That's fine - if I didn't want people to use/adapt/learn from the code then I wouldn't put it up, use it as you want :good:
Sent from my HTC One using Tapatalk
Keep it up
Great tutorials, keep em coming!
Hey what about starting a new activity with onClickListiner
Sent from my M3S_D7 using XDA Free mobile app
---------- Post added at 03:57 PM ---------- Previous post was at 03:49 PM ----------
Hey and do u mind sending a source codes.zip file
Sent from my M3S_D7 using XDA Free mobile app
Rebound.co said:
Hey what about starting a new activity with onClickListiner
Sent from my M3S_D7 using XDA Free mobile app
---------- Post added at 03:57 PM ---------- Previous post was at 03:49 PM ----------
Hey and do u mind sending a source codes.zip file
Sent from my M3S_D7 using XDA Free mobile app
Click to expand...
Click to collapse
in the onClick method just have this code:
Code:
startActivity(new Intent(this, YourActivity.class));

[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

[Q] onSaveInstanceState

I'm new to android app development
Facing an issue:
Data (String values) lost while changing screen orientation
I googled about it and found it can be handled by onSaveInstanceState()
But didn't get how to use that in the java file
Can someone clear it to me?
static final String STATE_SCORE = "playerScore";
static final String STATE_LEVEL = "playerLevel";
...
@override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
 @override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Always call the superclass first
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
} else {
// Probably initialize members with default values for a new instance
}
...
}
ChahatGupta said:
I'm new to android app development
Facing an issue:
Data (String values) lost while changing screen orientation
I googled about it and found it can be handled by onSaveInstanceState()
But didn't get how to use that in the java file
Can someone clear it to me?
Click to expand...
Click to collapse
If It s so important then save it as file
Or save it as temporary data to Bundle
Code:
Bundle.putExtra("name", Data);
:good:

Categories

Resources