AsyncTask - Accessing variable from doInBackground in different class - android

Basically I am wanting to get access to a variable that has been assigned in doInBackground in a different class but I am not sure how to do this here. Below is my relevant class structure. This is for an android application. Thanks.
public class CreateNewPlayers extends AsyncTask<String, String, String> {
public String doInBackground(String... args) {
String playerid = playerid1.getText().toString();

you can get access to intrim data using publishProgress() and onProgressUpdate()
public class CreateNewPlayers extends AsyncTask<String, String, String> {
public SomeOtherClass soc = null;
#Override
public String doInBackground(String... args) {
String playerid = playerid1.getText().toString();
publishProgress(playerid);
#Override
public String onProgressUpdate(String... args) {
super.onProgressUpdate(args);
soc.setPlayerID(args[0]);
soc.DoSomething();
}
Edit
more complete
public class SomeOtherClass {
protected String thisPlayerID = null;
public setPlayerID (String pid) {
thisPlayerID = pid;
}
public DoSomthing () {
// act on data
}
}
public class mainActivity extend Activity {
public CreateNewPlayers cnp = new CreateNewPlayers();
public SomeOtherClass soc = new SomeOtherClass();
#Override
protected void onCreate(Bundle data) {
super.onCreate(data);
cnp.soc = soc;
cnp.exectue("")
}
}

Related

Android - Room Repository and AsyncTask, how to use query to get back data from table

How do you get data from your Room entity using AsyncTask? I've been looking through the answers regarding AsyncTask but I don't get it.
This is my Dao:
#Dao
public interface BudgetDao {
#Insert
public void insert (Budget budget);
#Update
public void update (Budget budget);
#Query("SELECT id FROM budget_table WHERE category = :category AND date = :date")
int getId(String category, String date);
#Query("SELECT * FROM budget_table")
LiveData<List<Budget>> getAllBudgets();
#Query("SELECT category FROM budget_table")
List<String> getAllCategories();
}
How do I get the AsyncTask in my repository to return a list of strings? Right now the code is public void getAllCategories() {new getAllCatsAsyncTask(mBudgetDao).execute(); When I change the void to List, an error shows that I can't return a list of strings
My Repository:
public class BudgetRepository {
private BudgetDao mBudgetDao;
private LiveData<List<Budget>> mAllBudgets;
BudgetRepository(Application application) {
BudgetRoomDatabase db = BudgetRoomDatabase.getDatabase(application);
mBudgetDao = db.budgetDao();
mAllBudgets = mBudgetDao.getAllBudgets();
}
LiveData<List<Budget>> getAllBudgets() {return mAllBudgets;}
public void insert (Budget budget) {new insertAsyncTask(mBudgetDao).execute(budget);}
public void getAllCategories() {new getAllCatsAsyncTask(mBudgetDao).execute();}
//How do I return a list of strings?
private static class insertAsyncTask extends AsyncTask<Budget, Void, Void> {
//code
}
private class getAllCatsAsyncTask extends AsyncTask<Void, Void, List<String>> {
private BudgetDao mAsyncTaskDao;
getAllCatsAsyncTask(BudgetDao dao) {mAsyncTaskDao = dao;}
#Override
protected List<String> doInBackground(Void... voids) {
return mAsyncTaskDao.getAllCategories();
}
}
}
In my ViewModel:
public class BudgetViewModel extends AndroidViewModel {
private BudgetRepository mRepository;
private LiveData<List<Budget>> mAllBudgets;
public BudgetViewModel(#NonNull Application application) {
super(application);
mRepository = new BudgetRepository(application);
mAllBudgets = mRepository.getAllBudgets();
}
LiveData<List<Budget>> getAllBudgets() {return mAllBudgets;}
public void insert(Budget budget) {mRepository.insert(budget);}
public List<String> getAllCats() { return mRepository.getAllCategories();}
//Android Studios show incompatible types (Void vs List<String>)
Right now, in my ViewModel, mRepository.getAllCategories does not return a list of strings.
Do I have to call onPostExecute in my AsyncTask? How do I link the results from onPostExecute so that getAllCategories can return a list of strings in my AsyncTask? Or is there a better way to call for queries from my Dao?
Try this code..
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DisplayData displayData=new DisplayData(studentDatabase);
displayData.execute();
}
/**
* this method display student.
*/
private void DisplayStudent() {
mStudentList.addAll(studentDatabase.studentDao().getStudent());
}
private class DisplayData extends AsyncTask<Void,Void,Void>
{
private StudentDatabase studentDatabase;
public DisplayData(StudentDatabase studentDatabase) {
this.studentDatabase = studentDatabase;
}
#Override
protected Void doInBackground(Void... params) {
DisplayStudent();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
mDialog.dismiss();
mStu_adapter=new StudentAdapter(mStudentList,getApplicationContext());
mStu_adapter.notifyDataSetChanged();
mRvStudent.setAdapter(mStu_adapter);
DividerItemDecoration divider=new DividerItemDecoration(getApplicationContext(),LinearLayout.VERTICAL);
divider.setDrawable(ContextCompat.getDrawable(getApplicationContext(),R.drawable.divider));
mRvStudent.addItemDecoration(divider);
}
}
if you want to allow on mainThread then set this line.
db = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "database-name").allowMainThreadQueries().build();

How to pass a value to AsyncTask?

What is the proper way in the following code (it's a bit complicated structure to me) to get url from the method gotUrl() to the doInBackground() method of AsyncTask in order to use it in onPostExecute(), after the doInBackground() method has completed its task?
public class PlayerActivity extends CustomActivity implements
ProblemListener{
public class PlayChannel extends
AsyncTask<CustomChangeChannel, String, String> {
#Override
protected String doInBackground(CustomChangeChannel... params) {
initOctoshapeSystem();
return url;
}
#Override
protected void onPostExecute(String url){
}
}
public void initOctoshapeSystem() {
os = OctoStatic.create(this, this, null);
os.setOctoshapeSystemListener(new OctoshapeSystemListener() {
#Override
public void onConnect() {
mStreamPlayer = setupStream(OCTOLINK);
mStreamPlayer.requestPlay();
}
});
}
public StreamPlayer setupStream(final String stream) {
StreamPlayer sp = os.createStreamPlayer(stream);
sp.setStatusChangedListener(new StatusChangedListener() {
#Override
public void statusChanged(byte oldStatus,
final byte newStatus) {
runOnUiThread(new Runnable() {
#Override
public void run() {
//todo
}
});
}
});
sp.setListener(new StreamPlayerListener() {
#Override
public void gotUrl(String url) {
//String to be passed
}
});
return sp;
}
}
AsyncTask<Param1, Param2, Param3>
Param 1 is the param that you pass into your doInBackground method.
Param 2 is what you want to get while the AsyncTask working.
Param 3 is what you want to get as result.
You can declare all them as Void.
AsyncTask<Void, Void, Void>
In your case you want to pass String URL to your doInBackground, so:
AsyncTask<String, Void, Void>
Pass your URL String when you call the execute.
mAsyncTask.execute("your url");
Then get it in the doInBackground:
protected Void doInBackground(String... params) {
String yourURL = params[0];
return null;
}
change this
public class PlayChannel extends
AsyncTask<CustomChangeChannel, String, String>
to this
public class PlayChannel extends
AsyncTask<String, String, String>
and then use
PlayChannel channel = new PlayChannel(url);

RoboSpice + Google HTTP Client + GSON = failed to parse JSON to object

I'm using RoboSpice with Google HTTP Client & GSON this way:
ApiSpiceService:
public class ApiSpiceService extends GoogleHttpClientSpiceService {
private static final int THREAD_COUNT = 3;
#Override
public CacheManager createCacheManager(Application application) throws CacheCreationException {
CacheManager cacheManager = new CacheManager();
GsonObjectPersisterFactory gsonObjectPersisterFactory = new GsonObjectPersisterFactory(application);
cacheManager.addPersister(gsonObjectPersisterFactory);
return cacheManager;
}
#Override
public int getThreadCount() {
return THREAD_COUNT;
}
}
Request:
public class InfoRequest extends GoogleHttpClientSpiceRequest<Contact> {
private final String url;
public InfoRequest() {
super(Contact.class);
this.url = "some-url/path.json";
}
#Override
public Contact loadDataFromNetwork() throws Exception {
HttpTransport httpTransport = new NetHttpTransport();
HttpRequestFactory httpRequestFactory = httpTransport.createRequestFactory(new InfoHttpRequestInitializer());
HttpRequest httpRequest = httpRequestFactory.buildGetRequest(new GenericUrl(url));
httpRequest.setParser(new GsonFactory().createJsonObjectParser());
return httpRequest.execute().parseAs(Contact.class);
}
private class InfoHttpRequestInitializer implements HttpRequestInitializer {
#Override
public void initialize(HttpRequest request) throws IOException {
}
}
}
Model (Contact.java):
public class Contact {
private String data;
}
BaseActivity:
public abstract class BaseActivity extends ActionBarActivity {
protected SpiceManager spiceManager = new SpiceManager(ApiSpiceService.class);
#Override
protected void onStart() {
super.onStart();
spiceManager.start(this);
}
#Override
protected void onStop() {
spiceManager.shouldStop();
super.onStop();
}
}
And MainActivity:
public class MainActivity extends BaseActivity {
private InfoRequest infoRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
infoRequest = new InfoRequest();
}
#Override
protected void onStart() {
super.onStart();
spiceManager.execute(infoRequest, "txt", DurationInMillis.ALWAYS_EXPIRED, new TextRequestListener());
}
private class TextRequestListener implements RequestListener<Contact> {
#Override
public void onRequestFailure(SpiceException spiceException) {
//
}
#Override
public void onRequestSuccess(Contact s) {
//
}
}
It seems to be valid code, but, unfortunately, when it finish the request execution, field data in returned Contact instance is null.
There are no errors in logcat.
The requested content is 100% valid JSON. Why it is not being parsed?
Ok, I've found the solution. I need to add #Key annotation to fields in model. It's strange, because pure Gson does not require this.
public class Contact {
#Key
private String data;
}

Android Asynctask passing a single string

I would like to pass a single string into an asynctask. Could anyone show me how it is done? my getEntity needs The method getEntity(Activity, String, EntityGetListener) but I keep passing this String[]
String pass= story.get(position).getEntity();
new RemoteDataTask().execute(pass);
private class RemoteDataTask extends AsyncTask<String, String, Long> {
#Override
protected Long doInBackground(String... params) {
// TODO Auto-generated method stub
EntityUtils.getEntity(activity, params, new EntityGetListener() {
#Override
public void onGet(Entity entity) {
viewcount = entity.getEntityStats().getViews();
}
#Override
public void onError(SocializeException error) {
}
});
return null;
}
}
You already have this
new RemoteDataTask().execute(pass); // assuming pass is a string
In doInbackground
#Override
protected Long doInBackground(String... params) {
String s = params[0]; // here's youre string
... //rest of the code.
}
You can find more info #
http://developer.android.com/reference/android/os/AsyncTask.html
Update
Asynctask is depecated. Should be using kotlin coroutines or rxjava or any other threading mechanism as alternatives.
You can build AsyncTask with a constructor.
public class RemoteDataTask extends AsyncTask<String, String, Long> {
private String data;
public RemoteDataTask(String passedData) {
data = passedData;
}
#Override
protected String doInBackground(Context... params) {
// you can access "data" variable here.
EntityUtils.getEntity(activity, params, new EntityGetListener() {
#Override
public void onGet(Entity entity) {
viewcount = entity.getEntityStats().getViews();
}
#Override
public void onError(SocializeException error) {
}
});
return null;
}
}
In the application (Activity, Service etc), you can use;
private RemoteDataTask mTask;
private void doStuff(){
String pass = "meow"; // story.get(position).getEntity();
mTask = new RemoteDataTask(pass);
mTask.execute();
}

How to use one AsyncTask Class to apply different Activity in Android

I have a AsyncTask class that connect to web service to get something and then print to the screen.
Here is my code:
public class GetCreditAsyncTask extends AsyncTask<Object, Boolean, String>{
private MainActivity callerActivity;
private String credit;
public GetCreditAsyncTask(Context context){
callerActivity = (MainActivity )context;
}
#Override
protected String doInBackground(Object... params) {
.....//do something and get the credit
}
#Override
protected void onPostExecute(String response) {
callerActivity.txtView.setText(credit);
}
}
It works perfect but now, I have one more Activity ProfileActivity
which also want to use GetCreditAsyncTask to get the credit and print it to the txtView,
but at the begining of GetCreditAsyncTask, I cast the callerActivity to MainActivity.
The question is how to just use one AsyncTask class so that I can call it and get the credit.
You can define an interface that both activities implement. Instead of casting to MainActivity, you must cast to this interface.
public interface ActivityListener {
public void setText(String text);
}
public class MainActivity extends Activity implements ActivityListener {
...
public void setText(String text) {
TextView tv = findViewById(R.id.main_text);
tv.setText(text);
}
}
public class SecondActivity extends Activity implements ActivityListener {
...
public void setText(String text) {
TextView tv = findViewById(R.id.secondary_text);
tv.setText(text);
}
}
public class GetCreditAsyncTask extends AsyncTask<Object, Boolean, String>{
private ActivityListener callerActivity;
private String credit;
public GetCreditAsyncTask(Context context){
callerActivity = (ActivityListener) context;
}
#Override
protected String doInBackground(Object... params) {
.....//do something and get the credit
}
#Override
protected void onPostExecute(String response) {
callerActivity.setText(credit);
}
}

Categories

Resources