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.
Related
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
I am working on a registration based project that uses asyncTask. But I am getting errors on its params and the background usage tasks.
Snippet -
public class signupActivity extends AppCompatActivity {
EditText edit_name;
EditText edit_usn;
EditText edit_addnum;
EditText edit_pass;
EditText edit_repass;
Button btn_sign;
private static final String REGISTER_URL="http://abcd.000webhostapp.com/signup.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
edit_name=(EditText)findViewById(R.id.id_name);
edit_usn=(EditText)findViewById(R.id.id_usn);
edit_addnum=(EditText)findViewById(R.id.id_add);
edit_pass=(EditText)findViewById(R.id.id_pass);
edit_repass=(EditText)findViewById(R.id.id_repass);
btn_sign=(Button)findViewById(R.id.btn_signup);
btn_sign.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
registerUser();
}
});
}
private void registerUser() {
String name=edit_name.getText().toString().trim().toLowerCase();
String usn=edit_usn.getText().toString().trim().toLowerCase();
String addnum=edit_addnum.getText().toString();
String pass=edit_pass.getText().toString().trim().toLowerCase();
String repass=edit_repass.getText().toString().trim().toLowerCase();
register(name, usn, addnum, pass, repass);
}
private void register(String name,String usn,String addnum,String pass,String repass) {
String urlsuffix = "?name=" + name + "&usn=" + usn + "&ddnum=" + addnum + "&pass=" + pass + "&repass=" + repass;
//Getting **illegal start of type** for void keyword here
class RegisterUser extends AsyncTask <String, void, String> implements abcd.project2.RegisterUser {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(signupActivity.this, "please wait", null, true, true);
}
//Getting **method does not override or implement a method from a supertype** for override here
#Override
protected void onPostExecute() {
super.onPreExecute();
Toast.makeText(getApplicationContext(), "Internet not found", Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(String... params) {
String s = params[0];
BufferedReader bufferReader = null;
try {
URL url = new URL(REGISTER_URL + s);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String result;
result = bufferReader.readLine();
return result;
} catch (Exception e) {
return null;
}
}
}
RegisterUser ur = new RegisterUser();
ur.execute(urlsuffix);
}
public void openCreateList(View view) {
Intent i = new Intent(this, createActivity.class);
startActivity(i);
}}
Error messages -
Error:(56, 50) error: illegal start of type Error:(65, 9) error:
method does not override or implement a method from a supertype
How do I solve these?
I tried changing the return type in params but still I am unable to solve the error.
Try this
Its Void not void in parameter of AsyncTask
You need to change your onPostExecute() method just pass String parameter in onPostExecute() method
Change your code like below code
SAMPLE CODE
private void register(String name,String usn,String addnum,String pass,String repass) {
String urlsuffix = "?name=" + name + "&usn=" + usn + "&ddnum=" + addnum + "&pass=" + pass + "&repass=" + repass;
//Getting **illegal start of type** for void keyword here
class RegisterUser extends AsyncTask<String, Void, String> implements abcd.project2.RegisterUser {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(signupActivity.this, "please wait", null, true, true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
#Override
protected String doInBackground(String... params) {
String s = params[0];
BufferedReader bufferReader = null;
try {
URL url = new URL(REGISTER_URL + s);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String result;
result = bufferReader.readLine();
return result;
} catch (Exception e) {
return null;
}
}
}
RegisterUser ur = new RegisterUser();
ur.execute(urlsuffix);
}
You can read more about AsyncTask
change word "void" to Void in the line of class RegisterUser extends AsyncTask <String, void, String> implements abcd.project2.RegisterUser
The three types used by an asynchronous task are the following:
Params, the type of the parameters sent to the task upon execution.
Progress, the type of the progress units published during the background computation.
Result, the type of the result of the background computation.
Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type Void:
private class MyTask extends AsyncTask { ... }
refer this Official document site :
1.Change void to Void
2.change your onPostExecute()
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Toast.makeText(getApplicationContext(), "Internet not found", Toast.LENGTH_SHORT).show();
}
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.
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.
I have an one android application. Here I have to create the login page with mysql connection using soap webservices.
My code is working well on android 2.2 version.but its not working in android 4.0.
So here i have to use asynchronousTask .But i didn't know the asynchronousTask.please help me to resolve these problems.
EDIT:
i have using following code:
public class AndroidLoginExampleActivity extends Activity {
private final String NAMESPACE = "http://ws.userlogin.com";
private final String URL = "http://111.223.128.10:8085/AndroidLogin/services/Login?wsdl";
private final String SOAP_ACTION = "http://ws.userlogin.com/authentication";
private final String METHOD_NAME = "authentication";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button login = (Button) findViewById(R.id.btn_login);
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
new LongOperation().execute();
}
} );
}
class LongOperation extends AsyncTask<String, Void, String> {
private ProgressDialog Dialog = new ProgressDialog(LoginActivity.this);
#Override
protected String doInBackground(String... aurl) {
// TODO Auto-generated method stub
loginAction();
return null;
}
protected void onPreExecute() {
Dialog.setMessage("Loading...");
Dialog.show();
}
protected void onPostExecute(String resultGot) {
Dialog.dismiss();
}
}
private void loginAction(){
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
EditText userName = (EditText) findViewById(R.id.tf_userName);
String user_Name = userName.getText().toString();
EditText userPassword = (EditText) findViewById(R.id.tf_password);
String user_Password = userPassword.getText().toString();
//Pass value for userName variable of the web service
PropertyInfo unameProp =new PropertyInfo();
unameProp.setName("userName");//Define the variable name in the web service method
unameProp.setValue(user_Name);//set value for userName variable
unameProp.setType(String.class);//Define the type of the variable
request.addProperty(unameProp);//Pass properties to the variable
//Pass value for Password variable of the web service
PropertyInfo passwordProp =new PropertyInfo();
passwordProp.setName("password");
passwordProp.setValue(user_Password);
passwordProp.setType(String.class);
request.addProperty(passwordProp);
envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
androidHttpTransport = new HttpTransportSE(URL);
runOnUiThread(new Runnable() {
#Override
public void run() {
try{
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
TextView result = (TextView) findViewById(R.id.tv_status);
result.setText(response.toString());
}
catch(Exception e){
}
});
}
}
now also am getting the same error:
Before that:
Now i have to create the application on target version android 4.0 means its working well on android 2.2.but it didn't work on android 4.0 version.please check my code and give me solution .
Step 1. Please make a class that extends AsyncTask in your existing AndroidLoginExampleActivity like below :
class LongOperation extends AsyncTask<String, Void, String> {
private ProgressDialog Dialog = new ProgressDialog(OffersActivity.this);
#Override
protected String doInBackground(String... aurl) {
// TODO Auto-generated method stub
loginAction();
return null;
}
protected void onPreExecute() {
Dialog.setMessage("Loading...");
Dialog.show();
}
protected void onPostExecute(String resultGot) {
Dialog.dismiss();
}
}
step 2. Make a call of your method loginAction(); in which you have implemented your server implementation code.
Step 3. Execute LongOperation class from your activity's AndroidLoginExampleActivity onCreate() method like below :
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new LongOperation().execute();
}
Step 4. Just you want to know that you cant make any UI task in directly in doInBackground() in your case you are implementing text view here, for this issue you have to make runOnUiThread(new Runnable() and then make code of all UI (in your case TextView)..See below code...
runOnUiThread(new Runnable() {
#Override
public void run() {
try{
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
TextView result = (TextView) findViewById(R.id.tv_status);
result.setText(response.toString());
}
catch(Exception e){
}
}
});
you can directly paste this code portion inside your loginAction() method....
Let me know if any confusion...
Hope, now you can run your app in ICS and JellyBean too... :)
Try With Below Code :
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button login = (Button) findViewById(R.id.btn_login);
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
AsyncCallWS task = new AsyncCallWS();
task.execute();
}
});
}
private class AsyncCallWS extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
Log.i(TAG, "doInBackground");
loginAction();
return null;
}
#Override
protected void onPostExecute(Void result) {
Log.i(TAG, "onPostExecute");
}
#Override
protected void onPreExecute() {
Log.i(TAG, "onPreExecute");
}
#Override
protected void onProgressUpdate(Void... values) {
Log.i(TAG, "onProgressUpdate");
}
}
private void loginAction(){
....
...
}