PreferenceActivity for a widget? (Application coding) - Android Software Development

Howdy all. Have a question about allowing users to configure any widgets they place from an app I am developing.
I came across PreferenceActivity and it seems perfect, however I have no idea how to implement it. I have got a configuration activity working so when the user places a widget on a homescreen t opens a configuration activity.
So is there a way to use PreferenceActivity instead? Or PreferencceFragment as it is now. I already have a preference xml file to define the layout but I can't get the java to launch it.
Here is the Java I have so far:
Code:
public class PreferenceTest extends PreferenceFragment {
private static String CONFIGURE_ACTION = "android.appwidget.action.APPWIDGET_CONFIGURE";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
Any ideas? Thanks in advance! I was told this would be the best place to ask by a mod.

RED_ said:
Howdy all. Have a question about allowing users to configure any widgets they place from an app I am developing.
I came across PreferenceActivity and it seems perfect, however I have no idea how to implement it. I have got a configuration activity working so when the user places a widget on a homescreen t opens a configuration activity.
So is there a way to use PreferenceActivity instead? Or PreferencceFragment as it is now. I already have a preference xml file to define the layout but I can't get the java to launch it.
Here is the Java I have so far:
Code:
public class PreferenceTest extends PreferenceFragment {
private static String CONFIGURE_ACTION = "android.appwidget.action.APPWIDGET_CONFIGURE";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
Any ideas? Thanks in advance! I was told this would be the best place to ask by a mod.
Click to expand...
Click to collapse
you can call what ever you want as long as it is in your manifest.
you would just need to change the "android:configure=" to point to the new activity. eg.
android:configure="com.epic.widget.ConfigurationScreenActivity"
i would recommend a PreferenceActivity they are easy to code and run on there own. also that the PreferenceFrag wont work pre honeycomb.
if you know how to use a Activity you can use a PreferenceActivity.
https://github.com/pvyParts/EDT-Twe...om/roman/tweaks/activities/ClockActivity.java
this is a link my git hub, was a fork of someone else original but it does the job.
or use this code here if you are targeting post honeycomb devices.
http://developer.android.com/reference/android/preference/PreferenceActivity.html
Pvy.

Thanks for replying. I assumed PreferenceFragment worked pre-honycomb just that it was an updated way of working. Fair enough, guess I'll go back to PreferenceActivity. Only problem with that is that "addPreferencesFromResource(R.xml.preferences);" shows up as depreciated with PreferenceActivity. It's a warning only but still, it gets a strike-through so I don't know if it is actually being called.
This is my android:configure - android:configure="com.android.wifi.PreferenceTest" So it's calling the PreferenceFragment I posted above.
My manifest has the following activity that relates to the java code above:
Code:
<activity
android:name=".PreferenceTest"
android:label="God knows what">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />
</intent-filter>
</activity>
When I place the widget on the homescreen however, an alert shows up telling me my app has stopped. Can't see why.
Thanks for the github link as well, I'll dissect that and see if I can learn more!
EDIT: IT WORKS! I added the following from the github link to my code and it now works.
Code:
String pref;
Context mContext;
mContext = this.getApplicationContext();
PreferenceScreen prefs = getPreferenceScreen();

RED_ said:
Thanks for replying. I assumed PreferenceFragment worked pre-honycomb just that it was an updated way of working. Fair enough, guess I'll go back to PreferenceActivity. Only problem with that is that "addPreferencesFromResource(R.xml.preferences);" shows up as depreciated with PreferenceActivity. It's a warning only but still, it gets a strike-through so I don't know if it is actually being called.
This is my android:configure - android:configure="com.android.wifi.PreferenceTest" So it's calling the PreferenceFragment I posted above.
My manifest has the following activity that relates to the java code above:
Code:
<activity
android:name=".PreferenceTest"
android:label="God knows what">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />
</intent-filter>
</activity>
When I place the widget on the homescreen however, an alert shows up telling me my app has stopped. Can't see why.
Thanks for the github link as well, I'll dissect that and see if I can learn more!
EDIT: IT WORKS! I added the following from the github link to my code and it now works.
Code:
String pref;
Context mContext;
mContext = this.getApplicationContext();
PreferenceScreen prefs = getPreferenceScreen();
Click to expand...
Click to collapse
Glad you got it sorted.
Pvy
Sent from my LT18i using xda premium

Related

My newbie thread.

Some background: 10 years ago I had classes in basic, pascal, and c++( I missed something simple some where with functions or classes which messed me up in this I believe.)
So far I've watched a tutorial and set up my emulator and eclipse..
http://www.youtube.com/watch?v=z7bvrikkG7c
I then did a tutorial that ran my first program helloworld
http://www.youtube.com/watch?v=2gdhvwYUNJQ
I then did a tutorial and made a simple program that changes between two screens on a button click ( Why it is an hour long is beyond my understanding)
http://www.youtube.com/watch?v=m-C-QPGR2pM
I've proceeded to learning how to create menus and simply retrieved example code from the Google android site
Source: http://developer.android.com/guide/topics/ui/menus.html
Here's an example of this procedure, inside an Activity, wherein we create an Options Menu and handle item selections:
/* Creates the menu items */
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, MENU_NEW_GAME, 0, "New Game");
menu.add(0, MENU_QUIT, 0, "Quit");
return true;
}
/* Handles item selections */
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_NEW_GAME:
newGame();
return true;
case MENU_QUIT:
quit();
return true;
}
return false;
}
Click to expand...
Click to collapse
As I copy and pasted it into ecplise within an Activity, I realize there is some assumed information that I am missing when i received a bunch of errors
So.. I found A video tutorial
http://www.youtube.com/watch?v=6UYNnQOxCS8
and it instructs me to make sure I put these two lines of codes in first
Private static final int MENU1 = MENU.FIRST;
private static final int MENU2 = MENU.FIRST + 1;
I under line the menu's because it gives me errors on them as well... there seems to be some assumed knowledge I'm missing as well....
What specific piece of information am I missing to not have known that i would need those two lines as well as what I need to do to know the appropriate fix out of the suggestions they give me...
Are there any online tutorials or videos that'll bring me up to speed specifically with programming android apps... all the stuff I find just keeps leading me down a path to where I realize I've gotten ahead of myself because people are teaching things while assuming certain knowledge is known.
The tutorial I am following and getting errors on is for an 8th grade class of students...
Me: I'm pissed at that java toturial...
http://forum.xda-developers.com/showpost.php?p=6521891&postcount=6
Bastards.
Following the suggestion from this post
http://forum.xda-developers.com/showpost.php?p=6522089&postcount=7
I obtained a copy of Hello android.
Following the example to create a menu I used the code
I place this into my strings.xml
<string name="settings_label">Settings...</string>
name="settings_title">Sudoku settings</string>
<string
<string name="settings_shortcut">s</string>
<string name="music_title">Music</string>
<string name="music_summary">Play background music</string>
<string name="hints_title">Hints</string>
<string name="hints_summary">Show hints during play</string>
Click to expand...
Click to collapse
I place this into my main.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/settings"
android:title="@string/settings_label"
android:alphabeticShortcut="@string/settings_shortcut" />
</menu>
Click to expand...
Click to collapse
I import this files into my src app.java
right uner the other imports
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
Click to expand...
Click to collapse
I place this inside my activity ( where I think it would belong since it doesn't say where to put it. ) and ERROR
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
Click to expand...
Click to collapse
Quick fix says that menu needs to be either a field or constast so i give it a go and click field and it modifies a file called R.java.
I go back to app.java and not only is the menu highlighted but now R.menu.menu is entirely highlighted and says cannot be resolved or is not a field..
I try to modify the R.java file to remove what its done...
It won't let me..
Epic fail. on the third tutorial to create a menu.
I guess ill redo everything in a new project and then do the quick fix making menu a constant....
[edit] never mind ill look else where for help
http://www.youtube.com/watch?v=X3QO0ffg2Tc&feature=related
ok the toturial looks like it will work but when he types in this line in his app.java
public boolean onCreateOptionsMenu(Menu menu) {
Click to expand...
Click to collapse
it is under lined with an error on his screen as well as mine and then he says he is importing the missing classes and the error just disappeas with no demonstrations of what missing classing or what key combination he used to import them...
http://www.google.com/#hl=en&q=impo...=f&aqi=&aql=&oq=&gs_rfai=&fp=d059ab474882bfe2
WOO HOO found what he left out...
Compiled and installed...
Boo hoo menu key does nothing!! time to go back through the other menu tutorials and see if i cant get it working now that i know of this hot key..
Went back to this toturial with the elusive import missing classes hotkey..
http://www.youtube.com/watch?v=6UYNnQOxCS8
It worked like a charm
just had to remove
newGame();
and
quit();
and i have buttons that do nothing so far
More missing pieces.
I created a new activity as shown to me in previous tutorials giving it its own seperate XML file in the res/layouts as well as a jave file and I made sure it is calling for the right layout.
I also added the activity in the androidmanifest as shown to me as well..
off this site
http://developer.android.com/guide/topics/ui/menus.html
I've taken the code to create menus.. ( i got it working )
I then followed this and made the changes
Set an intent for a single menu item
If you want to offer a specific menu item that launches a new Activity, then you can specifically define an Intent for the menu item with the setIntent() method.
For example, inside the onCreateOptionsMenu() method, you can define a new menu item with an Intent like this:
MenuItem menuItem = menu.add(0, PHOTO_PICKER_ID, 0, "Select Photo");
menuItem.setIntent(new Intent(this, PhotoPicker.class));
Android will automatically launch the Activity when the item is selected.
Note: This will not return a result to your Activity. If you wish to be returned a result, then do not use setIntent(). Instead, handle the selection as usual in the onOptionsMenuItemSelected() or onContextMenuItemSelected() callback and call startActivityForResult().
Click to expand...
Click to collapse
It doesn't work... I don't understand why the intent would be in the onCreateOptionsMenu... it doesn't seem to work so I tried the alternative and replaced setIntent with with startActivityForResult.. and then I noticed it says "As usual" in the onOptionsMenuItemSelected()... which is where I would think the code would belong in the first place... but when I originally failed and tried to move the code there it errors...
Is ever step of the way really going to be half assed instructions.. i was beginning to think I had the hang of this.
Are the instructions bad or am i missing something???
Guess ill go dig in my hello android book.
EDIT: Wow that helped
startActivity(new Intent(this, register.class));
Click to expand...
Click to collapse
guess that book is worth something after all...
guess im just intending to start an activity with a particular intent and setting an intent alone isn't going to start the activity.... i suppose there must be some purpose behind setting an intent as they had describe on the google page.. just not seeing it yet...
Got to what i wanted tho.

Passing data from activity to Widget?

Hi.
I've been researching for many days. and i am really out of ideas.
First. I am new to all this.
Okay. my project:
I have:
- 1 Activity
- 1 Widget
So. my app is the widget itself. when you click the widget, it opens up the activity, the activity consists of a + and - button and a textview. the textview is on 0. when you click on +, you add up +1 to the textview and vica versa with the -.
So, what i want, in the activitys "onPause()", i want it to save the value and transfer it to the widget, i tried to send a broadcast, but that didnt work properly (i wanted to save the value in a hidden textview, but appwidget cant read values of TextViews -.-').
Also i tried some sql stuff.. didnt work either (appwidget doesnt support?)
Tried so save as a file on sd, didnt work (appwidget doesnt support?)
I couldnt use the broadcast thing because my app is made like this:
appwidget:
public void onUpdate(Context context,AppWidgetManager mgr,int[] appWidgetIds){
SetUp(context, mgr, appWidgetIds);
}
public void SetUp(Context c, AppWidgetManager mgr, int[] appWidgetIds){
//do stuff.....
}
public void onReceive(Context context, Intent intent) {
//If i get the number here, i cant really do anything with it, because i cant really save my value anywhere?
}
Bump. no one can help ?
I tried with the intent.putextra, but wont work.
If anyone wants to help me at msn, pm me. (eventually lightly paid)
Hi
Have you figured how to do it yet? I'm having the exact same problem and I'm unable to find any kind of solution.
Thank you!

[Q] How to keep layouts inflated after activity restarts

Hi guys,
On a button click I am inflating a layout like so:
Code:
public void plusLayout(View v) {
// inflating layout here:
LinearLayout ll1 = (LinearLayout) findViewById(R.id.main_layout);
// this layout is being inflated:
View newView = getLayoutInflater().inflate(R.layout.layout_to_be_added, null);
// add layout
ll1.addView(newView);
}
But when the activity restarts, the inflated layouts are gone.
I'd like the layouts to stay there.
(The user can click a button to remove the layout by hand).
I must be missing something trivial here right?
Cheers,
Daan
Which way is it restarted?
If the complete app is restarted, a new layout will be set in the onCreate method.
nikwen said:
Which way is it restarted?
If the complete app is restarted, a new layout will be set in the onCreate method.
Click to expand...
Click to collapse
Yeah when you press back button and start the app again or completely kill it.
It also happens on orientation change as the activity get restarted then as well.
But I think you can override that in the manifest somewhere.
DaanJordaan said:
Yeah when you press back button and start the app again or completely kill it.
It also happens on orientation change as the activity get restarted then as well.
But I think you can override that in the manifest somewhere.
Click to expand...
Click to collapse
Ah ok.
The point is: If you open the app or turn your device, the onCreate method is called. There you set a completely new layout. You would need to save that the layout is inflated (you could use a SharedPreferences entry) and inflate it in the onCreate method. If you just want it to appear again after turning the device, use the onSaveInstanceState method and the onRestoreInstanceState method. That would be better practice.
Look at the activity lifecycle.
Just so I'm sure I get this right :
The user launches the app, the layouts are not inflated
He presses a button which calls your plusLayout() method, so the layouts are now inflated
The user quits the activity and restarts it, the layouts are not inflated anymore but you want them to.
Is that correct ?
If it is, 2 ways I can think of :
Overriding savedInstanceState() & onRestoreInstanceState() :
First, declare a private Boolean before the onCreate() of your activity :
Code:
private Boolean isInflated = false;
Then, set it to true in the onClick() of your button, and override savedInstanceState and onRestoreInstanceState like so :
Code:
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save state changes to the savedInstanceState.
// This bundle will be passed to onCreate if th activity is
// killed and restarted.
savedInstanceState.putBoolean("inflate", isInflated);
}
Code:
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
Boolean myBoolean = savedInstanceState.getBoolean("inflate");
if (myBoolean == true)
plusLayout(myView);
}
Using the sharedPreferences
Same logic, different way to save the boolean :
Before onCreate(), declare a private boolean and a private SharedPreferences :
Code:
private Boolean isInflated = false;
private SharedPreferences prefs = getSharedPreferences("MY_PREFS");
in the onClick of your button :
Code:
isInflated = true;
Editor e = prefs.edit();
e.putBoolean("inflate", isInflated);
e.commit();
Then, in your onCreate(), retrieve the stored value and if it's true, call your plusLayout() method :
Code:
Boolean doInflate = prefs.getBoolean("inflate", false // this is the default value);
if (doInflate == true)
plusLayout(myView);
nikwen said:
Ah ok.
The point is: If you open the app or turn your device, the onCreate method is called. There you set a completely new layout. You would need to save that the layout is inflated (you could use a SharedPreferences entry) and inflate it in the onCreate method. If you just want it to appear again after turning the device, use the onSaveInstanceState method and the onRestoreInstanceState method. That would be better practice.
Look at the activity lifecycle.
Click to expand...
Click to collapse
Okay I'm working on that at the moment.
Whenever a layout is created an (int) "counter" get incremented.
I will save this "counter" in the SharedPreferences.
When the app starts layouts get created "counter" times.
Is this good practice?
It seems so strange that there isn't an easier way to save layout/activity states.
Edit:
Androguide.fr said:
Just so I'm sure I get this right :
The user launches the app, the layouts are not inflated
He presses a button which calls your plusLayout() method, so the layouts are now inflated
The user quits the activity and restarts it, the layouts are not inflated anymore but you want them to.
Is that correct ?
Click to expand...
Click to collapse
That is correct. Big thanks for the examples.
DaanJordaan said:
Okay I'm working on that at the moment.
Whenever a layout is created an (int) "counter" get incremented.
I will save this "counter" in the SharedPreferences.
When the app starts layouts get created "counter" times.
Is this good practice?
It seems so strange that there isn't an easier way to save layout/activity states.
Edit:
That is correct. Big thanks for the examples.
Click to expand...
Click to collapse
I would use his snippets. They are good (as always). Decide which one to use by what I have given above:
Just for turning:
onSaveInstanceState and onRestoreSavedInstanceState
For turning and reopening:
Shared preferences

Button2 doesnt work until Button1 is clicked

Hi All!
I'm new here and new to the Android Eclipse/development side and I'm having a bit of a problem with a java script.
I have a small advertising app with 2 buttons (looking to expand to 4 but that's a different thread), one for Facebook (Button1) and one for Twitter (Button2) and Button2 won't work until Button1 is clicked. It works fine except for that.
Any ideas on solutions? Aggravating me a bit lol
Thanks!!
We will need to see your layout XML and java code to help out.
not sure how i'd do that atm cos im a new member? i know that some admin members get pi**y when you dont wrap any code for formatting reasons??
i've got ready and i can imagine a senior member such as yourself will notice the mistake straight away.
Use pastebin http://pastebin.com/
not sure how to use it, just tried and i got the same message about not being able to post things outside links until 10 posts and so on? even tried pasting the raw text and still wouldnt let me
any suggestions?
thanks
Or use the CODE tags: [CODE ] and [/CODE ], but without the extra spaces.
adamj1910 said:
not sure how to use it, just tried and i got the same message about not being able to post things outside links until 10 posts and so on? even tried pasting the raw text and still wouldnt let me
any suggestions?
thanks
Click to expand...
Click to collapse
Take http off or www and just paste it as text
pastebin.com/4Q0g9ryg
pastebin.com/rHvFePNM
hopefully that should work?
thanks!
You had your button definition in the wrong place for your twitter button
Code:
package com.MYAPP.MYAPP;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //Set the screen's view to your xml file
Button facebookbutton = (Button) findViewById(R.id.button1); // Retrieve the button from the XML file
facebookbutton.setOnClickListener(new View.OnClickListener() { //Add a listener for when the button is pressed
[user=439709]@override[/user]
public void onClick(View v) {
sendToFacebook();
}
});
Button twitterbutton = (Button) findViewById(R.id.button2); // Retrieve the button from the XML file
twitterbutton.setOnClickListener(new View.OnClickListener() { //Add a listener for when the button is pressed
[user=439709]@override[/user]
public void onClick(View v) {
sendToTwitter();
}
});
}
protected void sendToFacebook() {
String url = "https://www.facebook.com"; // You could have this at the top of the class as a constant, or pass it in as a method variable, if you wish to send to multiple websites
Intent i = new Intent(Intent.ACTION_VIEW); // Create a new intent - stating you want to 'view something'
i.setData(Uri.parse(url)); // Add the url data (allowing android to realise you want to open the browser)
startActivity(i); // Go go go!
}
protected void sendToTwitter() {
String url = "https://www.twitter.com"; // You could have this at the top of the class as a constant, or pass it in as a method variable, if you wish to send to multiple websites
Intent i = new Intent(Intent.ACTION_VIEW); // Create a new intent - stating you want to 'view something'
i.setData(Uri.parse(url)); // Add the url data (allowing android to realise you want to open the browser)
startActivity(i); // Go go go!
}
}
Thanks for that ill give that a try!!! Really appreciate it
Sent from my GT-I9305 using xda app-developers app
it works!!! would i just repeat that for any additional buttons, same format;
Button onclicklistener etc etc etc
Button onclicklistener etc etc etc
protected void
protected void
and so on
does it work like that?
thanks!
Yes, just besure you place the code in your onCreate method for defining your buttons
Ill remember that haha thanks again really appreciate it!! =D
Sent from my GT-I9305 using xda app-developers app
zalez said:
Yes, just besure you place the code in your onCreate method for defining your buttons
Click to expand...
Click to collapse
Hey zalez
I just tried adding a youtube button in the exact same format obviously changing the button source and so on, eclipse couldn't find any problems so I ran it and it just crashed the app on the avd and on a real device?
Sent from my GT-I9305 using xda app-developers app
There are multiple ways. I like setting a listener, then using an onClick method with switch-case statements for every button.
Sent from my GT-I9300 using Tapatalk 4
you've lost me lol i understand the onclick but switch cases? if you check my .xml and .java from pastebin or the .java that another member posted further up ^ ^ ^ ^ that might show where im going wrong?
edit *** i just googled the switch case thing and ive seen it before, just not sure how i'd implement it into my .java?
thanks
bump?
adamj1910 said:
you've lost me lol i understand the onclick but switch cases? if you check my .xml and .java from pastebin or the .java that another member posted further up ^ ^ ^ ^ that might show where im going wrong?
edit *** i just googled the switch case thing and ive seen it before, just not sure how i'd implement it into my .java?
thanks
Click to expand...
Click to collapse
Sorry, I'm away. I'll look up an example from one of my apps later.
Basically, just make an onClickListener. You are then required to use that interface and implement the onClick method. Do that, you have an empty method, with a parameter like View v.
Then, make a switch statement for v.getId(), and do cases for the buttons (use their XML IDs!) that you have.
Hope that's kind of clear?
Sent from my GT-I9300 using Tapatalk 4
bassie1995 said:
Sorry, I'm away. I'll look up an example from one of my apps later.
Basically, just make an onClickListener. You are then required to use that interface and implement the onClick method. Do that, you have an empty method, with a parameter like View v.
Then, make a switch statement for v.getId(), and do cases for the buttons (use their XML IDs!) that you have.
Hope that's kind of clear?
Sent from my GT-I9300 using Tapatalk 4
Click to expand...
Click to collapse
That's actually starting to make sense! But it's just putting that into a script, not really my strong point yet, I'm more of a designer lol
It would be good if you could find some examples for URL buttons, it'd really help. Thanks!
There shouldn't have been any issues adding more. I would need to see your updated java code. Using switch cases is a good idea but at this point, if I was you, I would avoid it for now until you get the hang of the basics. Also, a log cat would be beneficial in debugging.

the dreaded asynctask

Hi guys,
i've started making an app recently.. and i needed a task to run in the backgound every 2 or 5 minutes.. and i collect the data and i display it when the app is opened.. so am using a sync task.... I'm having a bit of diffculty unerstanding how its used as every example is different..
and FYI am using a seperate .java file to runt he asynctask...
When we go through the android developers page this is the code we see...
They start with
Code:
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
1) whats the deal with the URL Integer Long ????? If i skip it what will happen???
next is this
Code:
protected void onProgressUpdate(Integer... progress) { setProgressPercent(progress[0]);
2) whats the integer doig there?? even if its not used in the function they put it... whats the deal??
3) Also how do we pass values like strings to a class??? i know about functions but the functions used in this class are like a group like so i cant exactly pass values to just one particular function...
Async Task
nvyaniv said:
Hi guys,
i've started making an app recently.. and i needed a task to run in the backgound every 2 or 5 minutes.. and i collect the data and i display it when the app is opened.. so am using a sync task.... I'm having a bit of diffculty unerstanding how its used as every example is different..
and FYI am using a seperate .java file to runt he asynctask...
When we go through the android developers page this is the code we see...
They start with
Code:
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
1) whats the deal with the URL Integer Long ????? If i skip it what will happen???
next is this
Code:
protected void onProgressUpdate(Integer... progress) { setProgressPercent(progress[0]);
2) whats the integer doig there?? even if its not used in the function they put it... whats the deal??
3) Also how do we pass values like strings to a class??? i know about functions but the functions used in this class are like a group like so i cant exactly pass values to just one particular function...
Click to expand...
Click to collapse
Code:
public class async extends AsyncTask<Params , Progress , Result>{
}
here 'params' is the argument that is input to the object of the class...
for eg..
Code:
public class async extends AsyncTask<int , Progress , Result>{
}
then when you will call its object then it will like this.
Code:
public class async extends AsyncTask<int , Progress , Result>{
}
async c;
c.execute(10); // passed int value 10 to execute the async thread in the background...
it has 3 methods that should be implemented
Code:
class load extends AsyncTask<int, Void, Void>{
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// all the ui updation is done here after doing the calculation...
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
// before the starting of calculation if ui needs to be adjusted then it is done here
}
@Override
protected Void doInBackground(int... arg0) {
// TODO Auto-generated method stub
// all calculation stuf is done here
}
}
IF U WANT SOME MORE HELP REGARDING ASYNC TASK THEN PLZZZ ASK AGAIN....
nvyaniv said:
Hi guys,
i've started making an app recently.. and i needed a task to run in the backgound every 2 or 5 minutes.. and i collect the data and i display it when the app is opened.. so am using a sync task.... I'm having a bit of diffculty unerstanding how its used as every example is different..
and FYI am using a seperate .java file to runt he asynctask...
When we go through the android developers page this is the code we see...
They start with
Code:
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
1) whats the deal with the URL Integer Long ????? If i skip it what will happen???
next is this
Code:
protected void onProgressUpdate(Integer... progress) { setProgressPercent(progress[0]);
2) whats the integer doig there?? even if its not used in the function they put it... whats the deal??
3) Also how do we pass values like strings to a class??? i know about functions but the functions used in this class are like a group like so i cant exactly pass values to just one particular function...
Click to expand...
Click to collapse
OK, so you're probably using it in a service, aren't you?
First of all, carefully read the tutorials here and here on vogella, to help you understand what it does.
1) these are the type of variables that are passed to the respective methods:
An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute
Click to expand...
Click to collapse
The Params get passed to the onPreExecute method, the Progress is the one you need to pass calling publishProgress and which is passed to onProgressUpdate. The result one should be returned by your doInBackground method and gets passed to the onPostExecute.
2) the Integer... Is actually an array of the corresponding object to int. Just ignore it and use the progress[0] as if it was a normal int.
3) set your Params variable to String so
AsyncTask <String, Integer, String> if you want to return a string as well
Ok i think i'm getting it... But when we say "Params , Progress , Result" its still a bit confusing..
we first hit pre execute then do iin BG then post execute... But the order in which the params are stated are not the same ...
when i give string first it always takes it for the during BG process... not for the pre execute...
For ex i say asymctask<int, string,void>
so my pre execute should get a int..
then my bg process should get a string..
the post execute should get nothing..
am i right???
nvyaniv said:
Ok i think i'm getting it... But when we say "Params , Progress , Result" its still a bit confusing..
we first hit pre execute then do iin BG then post execute... But the order in which the params are stated are not the same ...
when i give string first it always takes it for the during BG process... not for the pre execute...
For ex i say asymctask<int, string,void>
so my pre execute should get a int..
then my bg process should get a string..
the post execute should get nothing..
am i right???
Click to expand...
Click to collapse
Almost, the Progress variable is passed to the onProgressUpdate. This is something to indicate progress and publish on the UI Thread (for instance update a progress bar), usually an Integer. You can update the Progress from your doInBackground method by calling publishProgress, passing a Progress variable.
The point of this is that the doInBackground method runs in a seperate thread and all other methods run in the UI Thread! So you can't directly pass data between those, only with these values. Consider using a Bundle if you want to pass more than one variable!

Categories

Resources