Delivering AsyncTask result to an other activty - android

I am trying to retrieve my data from Parse.com during splash screen.
I'm making the query in the DoInBackground method and add all objects retrieved in an object vector (which is in an other class).
when moving to the MainActivty all data get loss.
Here's my code:
private class loadDataTask extends AsyncTask<Void, Void, Vector<PartyObj>>{
#Override
protected Vector<PartyObj> doInBackground(Void... params)
{
ParseQuery query = new ParseQuery("partyObj");
query.whereExists("Name");
query.findInBackground(new FindCallback() {
#Override
public void done(List<ParseObject> mNameList, ParseException e) {
if (e == null) {
adapter.partyVector = new Vector<PartyObj>();
for(int i=0; i<mNameList.size(); i++){
PartyObject party = new PartyObject();
party.setIndex(i);
party.setmName(mNameList.get(i).getString("Name").toString());
adapter.partyVector.add(party);
}
}else {
Log.d("mNameList", "Error: " + e.getMessage());
}
}
});
return adpater.partyVector;
}
#Override
protected void onPostExecute(Vector<PartyObj> result) {
progressDialog.dismiss();
setContentView(R.layout.activity_main_menu);
}
}

It seems like you're using the AsyncTask all wrong. query.findInBackground() is as far as I can tell an asynchronous call so you're essentially wrapping one async call in another. The problem with this is that code execution continues immediately after query.findInBackground(), thus ending the doInBackground() method. Since you move to the main activity immediately when the async task is finished it may be that query.findInBackground() hasn't finished yet (thus resulting in an empty/partial list).
Are you really sure you need to wrap everything in an async call? Does either of
ParseQuery query = new ParseQuery("partyObj");
query.whereExists("Name");
take time to execute or is the bulk of the work already in the async findInBackground() call? If so, I'd say skip the AsyncTask and do the view transition in the done() method of the FindCallback.
UPDATE: I've read up on ParseQuery and it clearly says:
Using the callback methods is usually preferred because the network
operation will not block the calling thread. However, in some cases it
may be easier to use the find, get or count calls, which do block the
calling thread. For example, if your application has already spawned a
background task to perform work, that background task could use the
blocking calls and avoid the code complexity of callbacks.
And in findInBackground() it clearly states that:
Retrieves a list of ParseObjects that satisfy this query from the
server in a background thread. This is preferable to using find(),
unless your code is already running in a background thread.
Since you are already wrapping everything in an AsyncTask you should either skip the async task completely since findInBackground( is already running in a background thread or switch to the blocking find() method.
Example without AsyncTask but using async findInBackground():
ParseQuery query = new ParseQuery("partyObj");
query.whereExists("Name");
query.findInBackground(new FindCallback() {
#Override
public void done(List<ParseObject> mNameList, ParseException e) {
if (e == null) {
adapter.partyVector = new Vector<PartyObj>();
for(int i=0; i<mNameList.size(); i++){
PartyObject party = new PartyObject();
party.setIndex(i);
party.setmName(mNameList.get(i).getString("Name").toString());
adapter.partyVector.add(party);
}
progressDialog.dismiss();
setContentView(R.layout.activity_main_menu);
}
else {
Log.d("mNameList", "Error: " + e.getMessage());
}
}
});
Example with AsyncTask and blocking find()
private class loadDataTask extends AsyncTask<Void, Void, Vector<PartyObj>>{
#Override
protected Vector<PartyObj> doInBackground(Void... params)
{
ParseQuery query = new ParseQuery("partyObj");
query.whereExists("Name");
Vector<PartyObject> v = new Vector<PartyObject();
try {
List<ParseObject> queryResult = query.find();
for(ParseObject po : queryResult) {
PartyObject party = new PartyObject();
party.setIndex(partyVector.size());
party.setmName(po.getString("Name").toString());
v.add(party);
}
}
catch(ParseException e) {
Log.d("mNameList", "Error: " + e.getMessage());
}
return v;
}
#Override
protected void onPostExecute(Vector<PartyObj> result) {
adapter.partyVector.addAll(result);
progressDialog.dismiss();
setContentView(R.layout.activity_main_menu);
}
}

I have implemented similar async class for getting parse server data
private class Getneworders_list extends AsyncTask<Void, Void, List<ParseObject>> {
ArrayList<HashMap<String, String>> neworders_hashmap;
#Override
protected void onPreExecute() {
super.onPreExecute();
neworders_recyclerView.getRecycledViewPool().clear();
}
#Override
protected List<ParseObject> doInBackground(Void... params) {
// Create the array
try {
ParseQuery<ParseObject> query = ParseQuery.getQuery("Orders");
ParseObject obj = ParseObject.createWithoutData("ShopLocations", idd);
query.whereEqualTo("shop", obj);
query.whereEqualTo("orderStatus",0);
query.setCachePolicy(ParseQuery.CachePolicy.IGNORE_CACHE);
query.orderByDescending("updatedAt");
object11 = query.find();
} catch (ParseException e) {
Log.d("Error", e.getMessage());
e.printStackTrace();
}
return object11;
}
#Override
protected void onPostExecute(List<ParseObject> result) {
neworders_hashmap = new ArrayList<HashMap<String, String>>();
if(result != null) {
if (result.size() > 0) {
chec(result.size());
m_Runnable.run();
}
}
}
}
use full for some one

Related

how to fetch data from parse database and use it in different function

I'm new to android studio and in learning phase.
I'm able to get current user location and store it in Parse server. Now i have also stored the Geo location of some super markets in Parse database in a class "Hospitals". Now i'm trying to retrieve the Geo location of specific hospital and trying to compare the distance between current user and the hospital.
When i'm trying to fetch the value from Parse database, it is calculated in background, so i'm unable to use it in different function to get the difference in distance as the return value will be null.
Below code is used:
class RemoteDataTask extends AsyncTask<Void, Void, Void> {
ProgressDialog mProgressDialog;
private Context context;
List<ParseUser> object = new ArrayList<>();
final ParseGeoPoint[] parlourUser = new ParseGeoPoint[1];
RemoteDataTask(Context context) {
Log.i("info", "Enetred RemoteDataTask");
this.context = context;
}
#Override protected Void doInBackground(Void... params) {
Log.i("info", "Entered doInbackground");
ParseQuery<ParseUser> query = ParseUser.getQuery();
try{
Log.i("info", "value is " + query.get("aifg14PNKz"));
object.set(1, query.get("aifg14PNKz"));
Log.i("info", "Object value" + object.get(1));
parlourUser[0] = object.get(0).getParseGeoPoint("Location");
Log.i("info", "Location of parlour user " + parlourUser[0]);
} catch (ParseException e) {
e.printStackTrace();
}
}
First of all, this is a very wrong practice to make a function which depends on the background thread.
query.getInBackground
It will work on the background thread and
After Background Query completed, this callback method communicates with UI thread
new GetCallback<ParseObject>() {
#Override
public void done(ParseObject object, ParseException e) {
}
Your function will not work if query.getInBackground take some time.
Solution to your problem in 2 steps
1) You can call this in AsyncTask and handle the Query in background
// RemoteDataTask AsyncTask
ProgressDialog mProgressDialog;
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
private Context context;
List<ParseObject> object;
final ParseGeoPoint[] hospitalUser = new ParseGeoPoint[1];
RemoteDataTask(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(context);
// Set progressdialog title
mProgressDialog.setTitle("Title...");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create the array
try {
ParseQuery<ParseObject> query = ParseQuery.getQuery("Lakme");
object = query.find();
if (ob != null) {
hospitalUser[0] = object.getParseGeoPoint("Location");
//calculate distance
}
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Close the progressdialog
mProgressDialog.dismiss();
// You can use "hospitalUser" Object here.
}
}
Call it from where you call this method
new RemoteDataTask(YourActivity.this).execute();
2) Calculate Distance once got a result from query
if it does not involve UI thread then you can calculate it in
"doInBackground" or
if it does involve UI thread you should use it in "onPostExecute" or
if you want to get notified after AsyncTask completed then you can
implement interface like this.

SQL query with listview

I am busy with an application where i am getting data from my azure database with sql and storing it in an array. I created a separate class where i get my data and my main activity connects to this class and then displays it.
Here is my getData class:
public class GetData {
Connection connect;
String ConnectionResult = "";
Boolean isSuccess = false;
public List<Map<String,String>> doInBackground() {
List<Map<String, String>> data = null;
data = new ArrayList<Map<String, String>>();
try {
ConnectionHelper conStr=new ConnectionHelper();
connect =conStr.connectionclass(); // Connect to database
if (connect == null) {
ConnectionResult = "Check Your Internet Access!";
} else {
// Change below query according to your own database.
String query = "select * from cc_rail";
Statement stmt = connect.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
Map<String,String> datanum=new HashMap<String,String>();
datanum.put("NAME",rs.getString("RAIL_NAME"));
datanum.put("PRICE",rs.getString("RAIL_UNIT_PRICE"));
datanum.put("RANGE",rs.getString("RAIL_RANGE"));
datanum.put("SUPPLIER",rs.getString("RAIL_SUPPLIER"));
datanum.put("SIZE",rs.getString("RAIL_SIZE"));
data.add(datanum);
}
ConnectionResult = " successful";
isSuccess=true;
connect.close();
}
} catch (Exception ex) {
isSuccess = false;
ConnectionResult = ex.getMessage();
}
return data;
}
}
And in my Fragmentactivity.java I simply just call the class as shown here:
List<Map<String,String>> MyData = null;
GetValence mydata =new GetValence();
MyData= mydata.doInBackground();
String[] fromwhere = { "NAME","PRICE","RANGE","SUPPLIER","SIZE" };
int[] viewswhere = {R.id.Name_txtView , R.id.price_txtView,R.id.Range_txtView,R.id.size_txtView,R.id.supplier_txtView};
ADAhere = new SimpleAdapter(getActivity(), MyData,R.layout.list_valence, fromwhere, viewswhere);
list.setAdapter(ADAhere);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
HashMap<String,Object> obj=(HashMap<String,Object>)ADAhere.getItem(position);
String ID=(String)obj.get("A");
Toast.makeText(getActivity(), ID, Toast.LENGTH_SHORT).show();
}
});
My problem comes when I want to include the onPreExecute and onPostExecute because I am relatively new to android studio and I do not know where to put the following lines of code:
#Override
protected void onPreExecute() {
ProgressDialog progress;
progress = ProgressDialog.show(MainActivity.this, "Synchronising", "Listview Loading! Please Wait...", true);
}
#Override
protected void onPostExecute(String msg) {
progress.dismiss();
}
You need to get the data from your azure database using a background service or AsyncTask. However, you are defining a class GetData which does not extend AsyncTask and hence the whole operation is not asynchronous. And I saw you have implemented doInBackground method which is not applicable here as you are not extending AsyncTask. I would suggest an implementation like the following.
You want to get some data from your azure database and want to show them in your application. In these kind of situations, you need to do this using an AsyncTask to call the server api to get the data and pass the data to the calling activity using an interface. Let us have an interface like the following.
public interface HttpResponseListener {
void httpResponseReceiver(String result);
}
Now from your Activity while you want to get the data through an web service call, i.e. AsyncTask, just the pass the interface from the activity class to the AsyncTask. Remember that your AsyncTask should have an instance variable of that listener as well. So the overall implementation should look like the following.
public abstract class HttpRequestAsyncTask extends AsyncTask<Void, Void, String> {
public HttpResponseListener mHttpResponseListener;
private final Context mContext;
HttpRequestAsyncTask(Context mContext, HttpResponseListener listener) {
this.mContext = mContext;
this.mHttpResponseListener = listener;
}
#Override
protected String doInBackground(Void... params) {
String result = null;
try {
// Your implementation of getting data from your server
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(final String result) {
mHttpResponseListener.httpResponseReceiver(result);
}
#Override
protected void onCancelled() {
mHttpResponseListener.httpResponseReceiver(null);
}
}
Now you need to have the httpResponseReceiver function implemented in the calling Activity. So the sample activity should look like.
public class YourActivity extends AppCompatActivity implements HttpResponseListener {
// ... Other code and overriden functions
public void callAsyncTaskForGettingData() {
// Pass the listener here
HttpRequestAsyncTask getDataTask = new HttpRequestGetAsyncTask(
YourActivity.this, this);
getDataTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
#Override
public void httpResponseReceiver(String result) {
// Get the response callback here
// Do your changes in UI elements here.
}
}
To read more about how to use AsyncTask, you might consider having a look at here.

Making an app Truly Async (Android)

I am building an application that is pretty dependent on async requests to function.
I have the main Activity called MainActivity. This really doesn't do much apart from contain layouts, however it does have a recycleviewer.
I then have a couple of http requests that are done to populate the recycle viewer.
To do this I have wrote a java class as follows:
public class dataforUi extends AsyncTask<String, String, JsonObject> {
private ArrayList<UiElements> els;
protected void onPreExecute() {
progressDialog.setMessage("Downloading your data...");
progressDialog.show();
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface arg0) {
RedditRequests.this.cancel(true);
}
});
}
protected JsonObject doInBackground(String... params) {
Do the http request here, get the result and populate uiElements with it
}
#Override
protected void onPostExecute(JsonObject jsonObject) {
super.onPostExecute(jsonObject);
progressDialog.hide();
}
I have a few more classes like this but hopefully it serves as an example of what I'm trying to do.
Then back in Main Activity, I have this code:
public void getUiElements() {
dataforUi ui = new dataforUi(findViewById(android.R.id.content));
try {
ui.execute("https://t").get();
ArrayList<UiElements> r = ui.getEls();
Log.d("MainFeedScreen", "Size of r is:" + r.size());
UiAdapter = new UiAdapter(r);
mRecyclerView.setAdapter(UiAdapter);
} catch (Exception e) {
}
}
This works fine, but it is very jolty due to the use of .get() on execute to make it blocking. If i remove .get() the progress bar shows up and disappears when the task is done, but my ui thread has progressed past this and ha tried to populate my view with an Empty Array and therefore nothing shows.
I have done a bit of looking into it but cant find a conclusive way of managing the notification of the UI thread that an activity is done.
Would really appericiate any advice on this one.
You need to fix your design.
On post execute, use local broadcast to notify your MainActivity that the AsyncTask is done.
Try using a separate thread to process your data. I use a ListView in stead of a RecyclerView, but the principle is the same.
I have no problems with jolting views.
protected void onPostExecute(String result) {
final String value = result;
// dismiss the dialog after getting all data
progressDialog.dismiss();
if (!value.isEmpty()) {
// updating UI from a new thread
runOnUiThread(new Runnable() {
public void run() {
// ListData is my custom class that holds my data
ArrayList<ListData> arrayDriverListData = new ArrayList<ListData>();
ListDataAdapter adapter = new ListDataAdapter(ListActivity.this, arrayListData);
ListData data;
boolean b = true;
try {
// My data is from a Json source from node 'history'
JSONObject object = new JSONObject(value);
JSONArray array = object.getJSONArray("history");
int len = array.length();
if (len > 0) {
for (int i = 0; i < len; i++) {
final JSONObject o = array.getJSONObject(i);
// Parse my data and add it to my adapter
adapter.add(data);
}
}
} catch (JSONException jex) {
Log.e(TAG, "" + jex.getMessage());
}
// setListAdapter is my call to update my list view
setListAdapter(adapter);
}
});
}
}
Now just update the UI thread
private void setListAdapter(ListDataAdapter adapter){
// my ListView
lvHistory.setAdapter(adapter);
}

Freezing app when using AsyncTask

I download a high amount of data from API and want to make it efficient so I get first 100 record in one asyncTask and then in another asyncTask get another several thousands(in 500 hundred portions) The loadListAsynchronously(); looks identicall as loadData function without content,progress,loadContent(); function but this functions are not the problem - without loadListAsynchronously(); app runs smoothly after frezee when download first data. I tried add transaction but that does not help me.
private void loadData() {
DottedProgressBar progressBar = (DottedProgressBar) findViewById(R.id.loadIngDots);
progressBar.startProgress();
content = (LinearLayout)findViewById(R.id.activity_main) ;
progress = (RelativeLayout) findViewById(R.id.progressPage) ;
AsyncTask<String, Void, String> read =new AsyncTask<String, Void, String>() {
SharedPreferences keyValues;
#Override
protected void onPreExecute() {
content.setVisibility(View.GONE);
keyValues = getSharedPreferences(Settings.MODEL_LAST_CALL, Context.MODE_PRIVATE);
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
height = displaymetrics.heightPixels;
width = displaymetrics.widthPixels;
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
modelList = new ArrayList<>();
Map<String,String> options= new HashMap<>();
options.put("limit",String.valueOf(AMOUNT_OF_LOADED_modelS));
ApiHelper.getModelWithParams(new Callback<ModelApiEnvelope>() {
#Override
public void onResponse(Call<ModelApiEnvelope> call, Response<ModelApiEnvelope> response) {
Log.i(TAG,"First call model Get response");
final ModelApiEnvelope envelope = response.body();
if(envelope==null)
Toast.makeText(MainActivity.this,getString(R.string.server_down_explanation),Toast.LENGTH_SHORT).show();
else{
try {
final Dao<Model,Integer> modelDAO = getHelper().getmodelDAO();
final Dao<Submodel,Integer> submodelDAO=getHelper().getsubmodelDAO();
TransactionManager.callInTransaction(getHelper().getConnectionSource(),
new Callable<Void>() {
public Void call() throws Exception {
modelList=envelope.getData();
Log.i(TAG,"LoadData loop Start");
for( final model m: modelList){
m.setLogo(m.getLogo()+"?width="+width/2+"&height="+height);
m.setLanguage(m.getLanguage().substring(0,2));
if(m.getLanguage().equals("uk"))
m.setLanguage("ua");
if(m.getsubmodels().size()!=0){
for(final submodel e: m.getsubmodels()){
e.setLanguage(m.getLanguage());
submodelDAO.createOrUpdate(e);
}
}
try {
modelDAO.createOrUpdate(m);
}catch (SQLException e) {e.printStackTrace();}
}
return null;}
});
if(envelope.getData().isEmpty()){
SharedPreferences.Editor editor = sharedPreferences.edit();
long time = System.currentTimeMillis();
editor.putString(Settings.model_LAST_CALL , Long.toString(time));
editor.apply();
}
else
loadListAsynchronously();
} catch (SQLException e) {
Log.i(TAG," message "+e.getMessage()) ; e.printStackTrace();
}}
loadContent();
content.setVisibility(View.VISIBLE);
progress.setVisibility(View.GONE);
}
#Override
public void onFailure(Call<modelApiEnvelope> call, Throwable t) {
Log.i(TAG,"ERROR"+ t.getMessage());
Toast.makeText(MainActivity.this,getString(R.string.server_down_explanation),Toast.LENGTH_LONG).show();
loadContent();
}
},MainActivity.this,options, keyValues.getString(lang,"0"));
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
};
read.execute();
}
UPDATE: Method Trace added
UPDATE 2: Removing the transaction solve my problem. It seems that the making transaction for thousands saveings into database freeze Ui.
Callback in Retrofit1 and AsyncTask are not compatible. You have to modify your API interface from something like this :
public interface Api {
void getModelWithParams(Callback<Something> callback);
}
To this :
public interface Api {
Something getModelWithParams();
}
Then Retrofit will not provide async execution support and you can execute that row method inside AsyncTask.doInBackground method.
Other option is to stay with that interface definition and just call Retrofit method directly (without AsyncTask wrapping). The question is if your further logic is not heavy, because onResponse will be executed on UI Thread which cause your freezes and in general is root cause of your problem.

Best approach to make a login screen

I am writing here because this is my last solution of understanding this type of programming.The problem is that I got stuck on what to use to handle the connection to a server and log-in. Should I use async task, handler or thread ? I didn't find a concrete answer stating which one to use, only found that async task is used to download images or other download stuffs.
Until now I have used a thread to connect to the server. The problem I encountered was when I catch the exception ( Putting invalid username/password ) and try to log-in again. ( I needed to "close" the last thread and start one again )
After this I started to use async task but I don't really understand how it should work and I am stuck on a toast of invalid username/password.
private class connectStorage extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
api = DefaultClientFactory.create(host, getUser, getPassword);
if (api.getAuthToken().trim().length() > 3) {
//TO DO LAYOUT CHANGE;
}
} catch (StorageApiException e) {
e.printStackTrace();
Log.i("TEST", "" + e.getMessage());
}
return null;
}
Also, I am 100% sure that calling inflate in the doInBackground method won't work too ( there I wanted to change the activity ).
I am starting the async task on a button press.
When you are using asynctask
You have doInBackground and onPostExecute
So basically get a json or string or boolean as a result from doinbackground
and in onpostexecute check if the login in succesful or not if its succesful save the data from server and start an intent to go to another activity or toast the user that that user login details are wrong and try again.
So your asynctask can be an inner class of your activity class which is login and onClickSubmit button call the asynctask class and on post execute parse the json and according to the result decide what to do
Example:
public class SignInAsycTask extends AsyncTask<RequestParams, Void, String> {
#Override
protected String doInBackground(RequestParams... params) {
return new HttpManager().sendUserData(params[0]);
}
#Override
protected void onPostExecute(String result) {
String[] details = parseJsonObject(result);
if (details != null) {
user.setUser_id(Integer.valueOf(details[0]));
user.setName(details[1]);
if (details.length > 2) {
user.setProfilePic(details[2]);
}
setSharedPreferences();
startActivity(new Intent(Signin.this, MainActivity.class));
finish();
} else {
Toast.makeText(Signin.this, "please try again",
Toast.LENGTH_LONG).show();
}
}
}
public String[] parseJsonObject(String result) {
JSONObject obj = null;
try {
obj = new JSONObject(result);
if (obj.has("success")) {
if (obj.getInt("success") == 1) {
if (obj.has("user_pic")) {
return new String[] {
String.valueOf(obj.getInt("user_id")),
obj.getString("user_name"),
obj.getString("user_pic") };
} else {
return new String[] {
String.valueOf(obj.getInt("user_id")),
obj.getString("user_name"), };
}
} else {
return null;
}
} else {
return null;
}
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
here my RequestParams are just a object where I stored all the details like url parameters to send etc and the output of the doinbackground is a String and I am parsing it in my postexecute method

Categories

Resources