Start activity is slow - android

I'm write a music application online.But i'm meet a problem... A new activity starts slowly when I select an item in listview...
I don't know resolve, please help me ! :(
Sorry. I'm speak English very bad :(
This is my code:
public class startNewActivity extends AsyncTask<String, Void, String> {
private Activity activity;
private String selectDoc = "div.gen img";
private String attr = "title";
private String result;
public String Quality;
public startNewActivity(Activity activity) {
this.activity = activity;
}
#Override
protected String doInBackground(String... arg0) {
nameSong = (String) lvSong.getItemAtPosition(positionId);
link = linkSong.get(Integer.valueOf(obj.toString()));
Quality = Utils.getQuality(link, selectDoc, attr, result);
Log.i("Quality", Quality);
changeLink = link.replace(".html", "_download.html").substring(15)
.replaceFirst("", "http://download")
.replace("nhac-hot", "mp3".concat("/vietnam/v-pop"));
Log.i("Change link", changeLink);
try {
//Connect internet
linkIntent = Utils.getLinkPlay(selectLinkPlay, changeLink,
afterChangeLink);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"Server has problem... Please while for minutes",
Toast.LENGTH_SHORT).show();
}
return linkIntent;
}
#Override
protected void onPostExecute(String result) {
//i'm want help here
Intent i = new Intent(SongActivity.this, PlayMusicActivity.class);
i.putExtra("song", linkIntent);
i.putExtra("namesong", nameSong);
i.putExtra("Quality", Quality);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(i);
pDialog.dismiss();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
pDialog = ProgressDialog.show(SongActivity.this, "",
"Please wait...");
}
}

You're starting the new activity inside onPostExecute() which executes only after you've completed doInBackground(). Hence, the time delay.
Ideally, you should start the activity just after you execute your AsyncTask. The AsyncTask will continue in the background while your activity changes.

Related

Android ProgressDialog not dismissing from Thread

i'm developing an android App.
The user registration process calls a service that sends an email so it takes several seconds, like 5 or 6 seconds,that's why I execute that task within a thread. The problem is, the Dialog is never dismissing. It stays rolling and the user can do nothing. Here's my code:
try
{
final ProgressDialog progDailog = new ProgressDialog(ActividadAltaUsuario.this);
new Thread(new Runnable()
{
#Override
public void run()
{
try
{
URL url = new URL("slowWS");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
InputStream in = new BufferedInputStream(conn.getInputStream());
String response = IOUtils.toString(in, "UTF-8");
final JSONObject jsonPrincipal = new JSONObject(response);
Boolean success = jsonPrincipal.get("status").toString() == "true";
if (success)
{
ActividadAltaUsuario.this.runOnUiThread(new Runnable() {
#Override
public void run() {
progDailog.show(ActividadAltaUsuario.this, "Sendind email");
}
});
final String idUsuario = jsonPrincipal.get("idUsuario").toString();
URL url2 = new URL("anotherSlowWS");
HttpURLConnection conn2 = (HttpURLConnection) url2.openConnection();
conn2.setRequestMethod("POST");
InputStream in2 = new BufferedInputStream(conn2.getInputStream());
String response2 = IOUtils.toString(in2, "UTF-8");
JSONObject jsonRtaMail = new JSONObject(response2);
//finish();
}
else
{
//finish();
showToast(jsonPrincipal.get("message").toString());
}
ActividadAltaUsuario.this.runOnUiThread(new Runnable() {
#Override
public void run() {
progDailog.dismiss();
}
});
}
catch (Exception e)
{
e.printStackTrace();
}
}
}).start();
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection" + e.toString());
}
Can anybody help me?
Thanks!
AsyncTask would be a better approach instead of thread, Replace your network call from thread to use AsyncTask. You can use something like this
private class LongOperation extends AsyncTask<Void, Void, Void> {
#Override
protected String doInBackground(Void... params) {
//Main stuff that needs to be done in background
}
#Override
protected void onPostExecute(Void result) {
//Post Execution this method will be called, handle result accordingly
//You can dismiss your dialog here
}
#Override
protected void onPreExecute() {
//Do initialization relative stuff here
// Initialize your dialog here.
}
}
As both onPostExecute() and onPreExecute() work on main thread you can show and dismiss your dialog in this methods.
The UI controls have to be accessed only from the UI thread.
Usually I do this in class that extends AsyncTask
Something like:
public class MyTask extends AsyncTask {
protected void onPreExecute() {
//create and display your alert here
progDialog = ProgressDialog.show(MyActivity.this,"Please wait...", "Logging ...", true);
}
protected Void doInBackground(Void... unused) {
// here is the thread's work ( what is on your method run()
...
// if we want to show some progress in UI, then call
publishProgress(item)
}
protected void onProgressUpdate(Item... item) {
// theoretically you can show the progress here
}
protected void onPostExecute(Void unused) {
//dismiss dialog here where the thread has finished his work
progDialog.dismiss();
}
}
LE:
More detalis about AsyncTask https://developer.android.com/reference/android/os/AsyncTask
check especially the Protected Methods

doInBackgroundTask - AsyncTask - Android

I am currently using an AsyncTask to fetch the JSON array when pressing a button. After that i have another button called ParseJson which opens a new activity in which a list is shown with the JSONArray.
What i would like, is to have one button instead of 2, but since the getJSON button (first button above) is starting a backgroundtask which needs to be finnished first, before launching the other activity (ParseJSON button), this doesnt work in one button right now.
I heard something about using a loading dialog, but i am quite new to this and have no idea how to solve it.
This is the code i use, but i also need the the value from the Textview in the background task. I will send the value of the textview to a php file (by POST) which fetches the data from the database.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void getJSON(View view) {
TextView txv = (TextView) findViewById(R.id.orderID);
txv.getText().toString;
//I need this value in the backgroundtask later
new BackgroundTask().execute();
}
class BackgroundTask extends AsyncTask<Void, Void, String>
{
String json_url = "MYJSONURL";
String JSON_STRING;
#Override
protected String doInBackground(Void... params) {
try {
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((JSON_STRING = bufferedReader.readLine())!=null)
{
stringBuilder.append(JSON_STRING+"\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
json_string = result;
}
}
public void parseJSON(View view)
{
if(json_string==null)
{
Toast.makeText(getApplicationContext(), "First Get JSON", Toast.LENGTH_LONG).show();
}
else
{
Intent intent = new Intent(this, DisplayListView.class);
intent.putExtra("json_data", json_string);
startActivity(intent);
}
}
Instead of starting the AsyncTask by a button press you code in a way by which it can be started as soon as your main activity is launched. Use onProgressUpdate method of the AsyncTask which will show some progress, once that method is finished your data is loaded. Then you use one button to parse and display the data in the list.
You may refer this to know more about AsyncTask methods
You can have a look at the below code to understand how communication can happen between an activity and AsyncTask. For simplicity I have a count loop running inside AsyncTask which will update the progress on the activity.
Please be warned that this code communicates with the same activity which started the AsyncTask. So, if you would like to perform any such background task, you should be having the AsyncTask attached to your second activity.
public class MainActivity extends Activity {
private ProgressBar mProgress;
private int mProgressStatus = 0;
TextView percentage = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mProgress = (ProgressBar) findViewById(R.id.progress_bar);
percentage = (TextView) findViewById(R.id.percentage);
new CountProgress().execute();
}
class CountProgress extends AsyncTask<Void, Integer, Void> {
#Override
protected void onPreExecute() {
mProgress.setProgress(0);
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... unused) {
for (int i=0; i<101;i++ ) {
if (isCancelled())
break;
publishProgress(i);
SystemClock.sleep(200);
}
return(null);
}
#Override
protected void onProgressUpdate(Integer... progress) {
if (!isCancelled()) {
mProgress.setVisibility(View.VISIBLE);
// updating progress bar value
mProgress.setProgress(progress[0]);
// updating progess percentage text
percentage.setText(progress[0].toString() + "%");
}
}
#Override
protected void onPostExecute(Void unused) {
Toast.makeText(getApplicationContext(), R.string.done, Toast.LENGTH_SHORT).show();
}
}
}
A full working app code can be downloaded from here and you can extend it further for your needs.

Calling static Async task from other fragment

I am trying to call Async task in some other activity from a fragment. I tried to call various way but none of it worked. I just want to know whats the best way to call static AsyncTask .Here is my Async task:
static class MyAsync extends AsyncTask<Void, Void, Void> {
Context context;
String username, password;
private MyAsync(Context context, String username, String password) {
this.context = context;
this.username = username;
this.password = password;
}
ProgressDialog dialog;
private String response;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = ProgressDialog.show(context, "Connecting to Server","Getting Credentials"
, true);
}
#Override
protected Void doInBackground(Void... arg0) {
try {
ContentDownload download = new ContentDownload();
response = download.loginApi(agentId, password);
if(response.contains("Success")){
if(SettingHelper.getFirstCall(context)){
ContentDownload.CallApi(context);
SettingHelper.setFirstCall(context, false);
}
if(SettingHelper.getFirstLaunch(context)){
ContentDownload load = new ContentDownload();
load.callItemApi(context);
load.callActionApi(context);
SettingHelper.setFirstLaunch(context, false);
}
}
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if(response.contains("Success")){
context.startActivity(new Intent(context, AllActivity.class));
}else{
Toast.makeText(context, "Got back", Toast.LENGTH_SHORT).show();
}
dialog.dismiss();
}}
I am trying to call it this way:
LoginActivity.new MyAsync(getActivity).execute();
but its giving error
It you want to use this class from your Fragment, give it public visibility, also a public constructor and then you can call it:
new LoginActivity.MyAsync(getActivity())

the class extends AsyncTask won't start

I'm new at this site, and i'm new at android programing, so you have to be a litle patient whith me.
I start an app to connect with a mysql database, but the asynctask won't start, the app just stop right before the class, and i really don't know why. so could you help me?
This is my code:
public class Logar extends Activity {
EditText etUsuario, etSenha;
Button btLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.logar);
etUsuario=(EditText) findViewById(R.id.editUsuario);
etSenha=(EditText) findViewById(R.id.editSenha);
btLogin=(Button) findViewById(R.id.button1);
btLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("logar", "entrou no evento");
ArrayList<NameValuePair> parametrosPost = new ArrayList<NameValuePair>();
parametrosPost.add(new BasicNameValuePair("usuario",etUsuario.getText().toString()));
parametrosPost.add(new BasicNameValuePair("senha",etSenha.getText().toString()));
Log.i("logar", "parametrosPost.add");
}
class LoginTask extends AsyncTask<Void,Void,Void>{
ArrayList<NameValuePair> parametrosPost = new ArrayList<NameValuePair>();
String urlPost="http://192.168.1.131/android/logar.php";
String urlGet="http://192.168.1.131/android/logar.php?usuario="+etUsuario.getText().toString()+"&senha="+etSenha.getText().toString();
String respostaRetornada = null;
#Override
protected Void doInBackground(Void... args){
Log.i("logar", "vai entrar no try");
try {
respostaRetornada = ConexaoHttpClient.executaHttpPost(urlPost, parametrosPost);
//respostaRetornada = ConexaoHttpClient.executaHttpGet(urlGet);
String resposta = respostaRetornada.toString();
Log.i("logar", "resposta = "+resposta);
resposta = resposta.replaceAll("\\s+", "");
if (resposta.equals("1"))
startActivity(new Intent(Logar.this,MenuPrincipal.class));
//mensagemExibir("Login", "Usuario Válido PARABÉNS ");
else
mensagemExibir("Login", "Usuario Inválido ????");
}
catch(Exception erro)
{
Log.i("erro", "erro = "+erro);
Toast.makeText(Logar.this, "Erro.: "+erro, Toast.LENGTH_LONG).show();
}
return null;
}
}
public void mensagemExibir(String titulo, String texto)
{
AlertDialog.Builder mensagem = new AlertDialog.Builder(Logar.this);
mensagem.setTitle(titulo);
mensagem.setMessage(texto);
mensagem.setNeutralButton("OK",null);
mensagem.show();
}
});
}
}
I will apreciate all the help. Thank You.
You have to call
new LoginTask().execute();
somewhere.
To start the AsyncTask you need to call its execute() method (or maybe executeOnExecutor), which is not visible in the code you have shown.
You cannot show an AlertDialog from inside the doInBackground method.
Showing an alert dialog needs to be done on the UI thread, so you should return a result from your doInBackground method, and handle the result (and show the alert dialog) in the onPostExecute method.

Error creating an AsyncTask

I'm creating a login form. When the user logs in, it will lead to the home page.
I create an activity that has an AsyncTask. Here's the relevant part of my code:
public class iniTask extends AsyncTask<String, Void, String> {
private ProgressDialog Dialog = new ProgressDialog(GPSTracerActivity.this);
protected void onPreExecute() {
Dialog.setMessage("Connect to server...");
Dialog.show();
}
protected String doInBackground(String... url_req) {
String url = url_req[0];
try {
Log.v("doing background", executeHttpGet(url));
return executeHttpGet(url);
} catch(Exception e) {
Log.v("Exception doing background","Exception:"+e.getMessage());
return "";
}
}
protected void onPostExecute(String result) {
try {
Dialog.dismiss();
// here when thing go wrong
startNewAction(result);
} catch(Exception e) {
Log.v("Exception process response","Exception:"+e.getMessage());
}
}
}
Here's startNewAction(result):
public void startNewAction(String result){
if (result.substring(0, 6) == "300 OK"){
Intent i = new Intent(GPSTracerActivity.this, Home.class);
startActivity(i);
}
}
The task starts correctly, but when I call startNewAction(result),
it does not call a new activity. Why?
NOTE : when i enable if structure to test string == 300 OK it is not work ! why
I see this in logcat:
07-16 14:57:23.345: WARN/InputManagerService(37): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy#40777ee0
In your onPostExecute dismiss the dialog first.
Dialog.dismiss();
I just found the solution,there is an error because of the way i compare the string,
It should be,
if (result.substring(0, 6).equals("300 OK") ){
Intent i = new Intent(GPSTracerActivity.this, Home.class);
startActivity(i);
}
Anyway, Thanks for ideas !!!

Categories

Resources