Android: ProgressDialog in external async class (sth block async thread) - android

I have main activity:
public class ChooseWriteSentenceActivity extends ActionBarActivity{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String userName = "Zdzisiu";
String password = "Ziemniak";
MainServie service = new MainService(this);
boolean isExsist = service.findUser(String userName, String password);
//more code...
}
}
In my app service uses repositories and jsonconsumers but for simpler code I'm skipping them.
public class MyService{
private Context context;
public MyService(Context context){
this.context = context
}
public boolean findUser(String userName, String password){
String resultS = null;
try{
resultS = new QueryExecutorFindUser(context).execute(userName,password).get();
}
catch(Exception ex){
ex.printStackTrace();
}
boolean realRes = jsonConsumer(resultS).getFindUser();
return realRes;
}
}
public class QueryExecutorFindUser extends AsyncTask<String,Void,String> {
protected final String connectionUrl = "http://myWebService:44302/Service.svc/";
protected ProgressDialog progressDialog;
protected Context curContext;
public QueryExecutor(Context context){
curContext = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = ProgressDialog.show(curContext,"Loading...",
"Loading application View, please wait...", false, false);
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
progressDialog.dismiss();
}
protected String doInBackground(String... args){
String result = null;
String url = connectionUrl + args[0] + "/" + args[1];
HttpResponse response = null;
HttpClient httpclient = this.getNewHttpClient();
HttpGet get = new HttpGet(url);
get.setHeader("Accept", "application/json");
get.setHeader("Content-type", "application/json");
try{
response = httpclient.execute(get);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
if(response != null){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
result = out.toString();
}
} else{
throw new IOException(statusLine.getReasonPhrase());
}
} catch(Exception ex){
ex.getMessage();
} finally{
if(response != null){
try{
response.getEntity().getContent().close();
} catch(Exception ex){
}
}
}
return result;
}
}
And progress dialog is show but only after all code in onCreatre in ChooseWriteSentenceActivity including doInBacground(...) from QueryExecutor is finished (so it disappears practically at the same time). It looks like sth waiting for thread with QueryExecutorFindUser.doInBackground() and it is runs like synchronously (?), I think that because when I debug code onPreExecute() is running correctly (and start before doInBackground(...)) and progressDialog.isShowing() == true (but not on the screen :( ).
If I remove extends AsyncTask from QueryExecutorFindUser and make private class with this extension in main activity (and run all code from onCreated() including service.findUser() in thisPrivateClass.doInBackground(...)) it works okey.
I prefer to have progressDialog in one place no in all main activities (of cource in practise I use QueryExecutor for all queries not only findUser) but I don't have idea what i am doing wrong. I spent all day on it with no result :(

Dialogs are tied to an Activity and ultimately must be hosted by one. So until your app's activity gets created, the dialog will not display.

Related

How can I get filleUploaded URL as string from async task in android

I am uploading an image on server by using async task and in the end I want to return value of uploaded file url. How can I do that
I am calling asynctask as
new Config.UploadFileToServer(loginUserInfoId, uploadedFileURL).execute();
and my asynctask function is as:
public static final class UploadFileToServer extends AsyncTask<Void, Integer, String> {
String loginUserInfoId = "";
String filePath = "";
long totalSize = 0;
public UploadFileToServer(String userInfoId, String url){
loginUserInfoId = userInfoId;
filePath = url;
}
#Override
protected void onPreExecute() {
// setting progress bar to zero
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
// updating progress bar value
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.HOST_NAME + "/AndroidApp/AddMessageFile/"+loginUserInfoId);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(filePath);
// Adding file data to http body
entity.addPart("file", new FileBody(sourceFile));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
responseString = responseString.replace("\"","");
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
Try my code as given below.
public Result CallServer(String params)
{
try
{
MainAynscTask task = new MainAynscTask();
task.execute(params);
Result aResultM = task.get(); //Add this
}
catch(Exception ex)
{
ex.printStackTrace();
}
return aResultM;//Need to get back the result
}
You've almost got it, you should do only one step. As I can see, you are returning the result at the doInBackground method (as a result of calling uploadFile). Now, this value is passed to the onPostExecute method, which is executed on the main thread. In its body you should notify components, which are waiting for result, that result is arrived. There are a lot of methods to do it, but if you don't want to used 3rd party libs, the simplest one should be to inject listener at the AsyncTask constructor and call it at the onPostExecute. For example, you can declare the following interface:
public interface MyListener {
void onDataArrived(String data);
}
And inject an instance implementing it at the AsyncTask constructor:
public UploadFileToServer(String userInfoId, String url, MyListener listener){
loginUserInfoId = userInfoId;
filePath = url;
mListener = listener;
}
Now, you can simply use it at the onPostExecute:
#Override
protected void onPostExecute(String result) {
listener.onDataArrived(result);
super.onPostExecute(result); //actually `onPostExecute` in base class does nothing, so this line can be removed safely
}
If you are looking for a more complex solutions, you can start from reading this article.

DoInBackground in service android

I am calling a webservice using doInBackgroung methode in a service using this code
public class LoginService {
public int status;
private String _login;
private String _pass;
public HttpResponse response;
public LoginService(String log, String pass) {
_login = log;
_pass= pass;
authenticate();
}
private void authenticate() {
new RequestTask().execute("http://safedrive.url.ph/v1/login?email="+_login+"&password="+_pass);
}class RequestTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... uri) {
Log.e("Login","******Login Started************");
HttpClient httpclient = new DefaultHttpClient();
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
status = statusLine.getStatusCode();
} else {
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (Exception e) {
e.printStackTrace();
}
Log.e("reponse", responseString);
return responseString;
}
#Override
protected void onPostExecute(String responseString) {
Log.e("status",""+ status);
//when i execute my code with right values of password and address,status gets the right value (200) and i can loggout it
super.onPostExecute(responseString);
}
Then I call the service in my main activity after a click button
connectButton.setOnClickListener(
new OnClickListener() {
public void onClick(View v) {
address = ADDRESS.getText().toString();
pwd = PASS.getText().toString();
LoginService logService = new LoginService(address,pwd);
Log.e("service", logService.getStatus()+"");// here the value of logService.getStatus() is 0 !!
if (logService.getStatus()==200 )
{
Intent intent = new Intent(MainActivity.this,WelcomeActivity.class);
startActivity(intent);
}
else {Toast.makeText(getApplicationContext(), "no", Toast.LENGTH_LONG).show();}
}
});
The value of status is not changed in the main activity so I can't pass to the other activity.
You could start your AsyncTask in your Activity and go to the other Activity from onPostExecute
Anyways leave that comment as you said service I thought your using AsyncTask inside android's Service.
First Create an interface in your project for listening finish of your service
LoginServiceListener.java
public class LoginService {
public int status;
public HttpResponse response;
private String _login;
private String _pass;
private LoginServiceListener mListener = null;
// Update your constructor
public LoginService(String log, String pass, LoginServiceListener iListener) {
_login = log;
_pass = pass;
mListener = iListener;
authenticate();
}
private void authenticate() {
new RequestTask().execute("http://safedrive.url.ph/v1/login?email=" + _login + "&password=" + _pass);
}
class RequestTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... uri) {
Log.e("Login", "******Login Started************");
HttpClient httpclient = new DefaultHttpClient();
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
status = statusLine.getStatusCode();
} else {
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (Exception e) {
e.printStackTrace();
}
Log.e("reponse", responseString);
return responseString;
}
#Override
protected void onPostExecute(String responseString) {
Log.e("status", "" + status);
// On service completion you result will be posted back to the activity
mListener.loginFinished(responseString);
}
}
}
Make your activity to register with LoginServiceListener to listen for the service completion events by implementing interface LoginServiceListener
Make your service call as :
LoginService service = new LoginService("user", "pass", this);
This will ask you to implement the interface LoginServiceListener and hence add the method
#Override
public void loginFinished(String iResponse)
{
// This is you response. Now do whatever you want to do.
}

How to set instance variable of activity in onPostExecute?

I have an AsyncTask in my activity class and when I check some data in doInBackground(), I just want to change/set an instance variable of my activity class, but somehow there is nothing what is changing! :(
And if the variable is changed another AsyncTask should start.
Now here is the code:
public class LogIn extends Activity {
private boolean emailNotAvalaible;
private void setemailNotAvalaible(boolean emailNotAvalaible) {
this.emailNotAvalaible= emailNotAvalaible;
}
private Button loginBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_activity);
loginBtn = (Button) findViewById(R.id.login_btn);
loginBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new Register().execute("");
if (emailNotAvalaible== true) {
new Installation().execute("");
}
}// end of onClick()
});// end of setOnClickListener
}// end of onCreate();
public class Register extends AsyncTask<String,Integer,String>{
#Override
protected void onPreExecute() {
...
}//end of onPreExecute()
#Override
protected String doInBackground(String... params) {
ArrayList<NameValuePair> postParamsEmail = new ArrayList<NameValuePair>();
postParamsEmail.add(new BasicNameValuePair("email", email));
try {
String emailCheck = executeHttpPost("http://.../doubleEmail.php", postParamsEmail);
try {
JSONArray jsonarr = new JSONArray( emailCheck );
String emailAvalaible = jsonarr.getString(0);
if( emailAvalaible.equals("no") ){ doubleEmail = "no"; }else{ doubleEmail = "yes"; }
} catch (JSONException e) {
e.printStackTrace();
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
return "String";
}// end of doInBackground()
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
if (doubleEmail.equals("no")){
LogIn.this.setEmailNotAvalaible(true);
}
}
}//end of AsyncTask class
private static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}//end of getHttpClient()
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}//end of executeHttpPost()
}//end of activity class
Some code is not shown, but this code isn't important for the solution.
The php-file just checks if the entered email does exist in the database.
So, the major question is how can I easily change the variable 'emailNotAvalaible' in doInBackground or in onPostExecute?
Thanks for your help!!!
EDIT:
Hello again, thanks for everybodys help, to change the variable works fine, but I guess my problem is, that before my Register AsyncTask is allready finished, the new AsyncTask proofs the variable and wants to start, but just a second after that the variable is set. So, How can I ensure that the second AsyncTask only starts when the first AsyncTask is Allready finished? thanks for your help guys!!!
There are several ways but the postExecute method can solve your problem look this: how to pass the result of asynctask onpostexecute method into the parent activity android
this should not be an issue. here is an example that works fine:
public class Register extends AsyncTask<String,Integer,String>{
#Override
protected void onPreExecute() {
Log.d("", "on pre bool: " + bool);
}//end of onPreExecute()
#Override
protected String doInBackground(String... params) {
bool = true;
return "";
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
Log.d("", "on post, bool: " + bool);
}
}
where bool = private boolean in your main activity. here is the logcat:
07-19 11:57:25.943: D/(21843): on pre bool: false
07-19 11:57:29.736: D/(21843): on post, bool: true
my guess is that your variable, doubleEmail, is not getting set to "no".
So, I think I have found at least one solution for my problem, this is maybe not the best one, but it works fine.
Now, for those who are interested in my solution.
I have found it here : multithreading , thanks to Boris Strandjev
I have chosen the 'get' - option : new Register().execute("").get(2000, TimeUnit.MILLISECONDS);
If there is any better solution, please tell me, otherwise thanks for trying to help me!

Properly Using AsyncTask get()

I am running into a problem. I need to use asynctask to retrieve JSON data and I need that data before I moved to the next part of the program. However, when using the get() method of AsyncTask I have 5 to 8 sec black screen before I see the data is displayed. I would like to display a progress dialog during the data retrieval but I cannot do this due to the black screen. Is there a way to put into another thread? here is some code
AsyncTask
public class DataResponse extends AsyncTask<String, Integer, Data> {
AdverData delegate;
Data datas= new Data();
Reader reader;
Context myContext;
ProgressDialog dialog;
String temp1;
public DataResponse(Context appcontext) {
myContext=appcontext;
}
#Override
protected void onPreExecute()
{
dialog= new ProgressDialog(myContext);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setCancelable(false);
dialog.setMessage("Retrieving...");
dialog.show();
};
#Override
protected Data doInBackground(String... params) {
temp1=params[0];
try
{
InputStream source = retrieveStream(temp1);
reader = new InputStreamReader(source);
}
catch (Exception e)
{
e.printStackTrace();
}
Gson gson= new Gson();
datas= gson.fromJson(reader, Data.class);
return datas;
}
#Override
protected void onPostExecute(Data data)
{
if(dialog.isShowing())
{
dialog.dismiss();
}
}
private InputStream retrieveStream(String url) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(url);
try {
HttpResponse getResponse = client.execute(getRequest);
final int statusCode = getResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w(getClass().getSimpleName(),
"Error " + statusCode + " for URL " + url);
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
return getResponseEntity.getContent();
}
catch (IOException e) {
getRequest.abort();
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
}
return null;
}
}
DisplayInfo
public class DisplayInfo extends Activity implements AdverData {
public static Data data;
public ProjectedData attup;
public ProjectedData attdown;
public ProjectedData sprintup;
public ProjectedData sprintdown;
public ProjectedData verizionup;
public ProjectedData veriziondown;
public ProjectedData tmobileup;
public ProjectedData tmobiledown;
public ProjectedAll transfer;
private ProgressDialog dialog;
public DataResponse dataR;
Intent myIntent; // gets the previously created intent
double x; // will return "x"
double y; // will return "y"
int spatial; // will return "spatial"
//public static Context appContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
dialog= new ProgressDialog(DisplayInfo.this);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setCancelable(false);
dialog.setMessage("Retrieving...");
dialog.show();
myIntent= getIntent(); // gets the previously created intent
x = myIntent.getDoubleExtra("x",0); // will return "x"
y = myIntent.getDoubleExtra("y", 0); // will return "y"
spatial= myIntent.getIntExtra("spatial", 0); // will return "spatial"
String URL = "Some URL"
dataR=new DataResponse().execute(attUp).get();
#Override
public void onStart()
{more code}
When you are using get, using Async Task doesn't make any sense. Because get() will block the UI Thread, Thats why are facing 3 to 5 secs of blank screen as you have mentioned above.
Don't use get() instead use AsyncTask with Call Back check this AsyncTask with callback interface

Read data from database located at server in android

I have one database file whose name is menu.db and this file is located at server now i want to read data from this database.
i also have registration page on the application i am working on, as user press submit button then all the user information should be store on that database at server.
if anyone solved this problem then please help me.
if any one knows then please help me.
I have the following code. It authenticates the user password. you should call this method inside doBackground() of AsyncTask extended Class.
public boolean authenticate(String strUsername, String strPassword)
{
boolean bReturn = false;
InputStream pInputStream = null;
ArrayList<NameValuePair> pNameValuePairs = new ArrayList<NameValuePair>();
pNameValuePairs.add(new BasicNameValuePair("userid", strUsername));
pNameValuePairs.add(new BasicNameValuePair("password", strPassword));
try
{
HttpClient pHttpClient = new DefaultHttpClient();
String strURL = p_strServerIP + "Login.php";
HttpPost pHttpPost = new HttpPost(strURL);
pHttpPost.setEntity(new UrlEncodedFormEntity(pNameValuePairs));
HttpResponse pHttpResponse = pHttpClient.execute(pHttpPost);
HttpEntity pHttpEntity = pHttpResponse.getEntity();
pInputStream = pHttpEntity.getContent();
BufferedReader pBufferedReader = new BufferedReader(new InputStreamReader(pInputStream,"iso-8859-1"),8);
StringBuilder pStringBuilder = new StringBuilder();
String strLine = pBufferedReader.readLine();
pInputStream.close();
if(strLine != null)
{
if((strLine).equals("permit"))
{
bReturn = true;
}
}
}
catch (Exception e)
{
Log.e("log_tag", "Caught Exception # authenticate(String strUsername, String strPassword):" + e.toString());
}
return bReturn;
}
The class you extend from AsyncTask should be something like
class ConnectionTask extends AsyncTask<String, Void, Boolean>
{
private SharedPreferences mSettings;
private Context mContext;
ConnectionTask(SharedPreferences settings, Context context)
{
mSettings = settings;
mContext = context;
}
protected void onProgressUpdate(Integer... progress)
{
}
protected void onPostExecute(Boolean result)
{
Toast.makeText(mContext, "Authentication over.", Toast.LENGTH_LONG).show();
}
#Override
protected Boolean doInBackground(String... params)
{
pVerifier.authenticate(params[0], params[1]);
return true;
}
}

Categories

Resources