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();
}
Related
I am having problem with AsyncTask class inside ViewPager's Fragment.
I have added code like below inside ViewPager's 3rd Fragment:
private View.OnClickListener finishClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
UserIdAsyncTask userIdAsyncTask = new UserIdAsyncTask( getActivity(), "URL", "Test", "Value" );
userIdAsyncTask.execute();
Her is my UserIdAsyncTask class:
private class UserIdAsyncTask extends AsyncTask<Void, Void, String> {
String url = "";
String oldpass = "";
String newpass = "";
private Context mContext = null;
private ProgressDialog dialog;
public UserIdAsyncTask( Context context, String url, String oldPass, String newPass ) {
this.mContext = context;
this.url = url;
this.oldpass = oldPass;
this.newpass = newPass;
}
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(this.mContext, "", "Please wait...");
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
#Override
protected String doInBackground(Void... params) {
String str = "";
try {
return str;
} catch (Exception e) {
Log.e(ThirdFrag.class.toString(), e.getMessage(), e);
}
return str;
}
#Override
protected void onPostExecute(String response) {
dialog.dismiss();
Intent i = new Intent(getActivity(), ABC.class);
startActivity(i);
getActivity().finish();
}
}
In the given code, onPreExecute() called but doInBackground() never called.
Any ideas anyone? I'm really struggling with this one.
I have a GoogleTranslate.java file that has a class, GoogleTranslate, that extends AsyncTask. The purpose of this task is to perform Google translations.
I have another class, MyVocab, that allows the user to input a word to translate in an alert dialog. So on a click to the alert dialog button, the word will be translated to the desired language by calling on the GoogleTranslate class. However, when I pass a progress bar from MyVocab to GoogleTranslate it doesn't work. When the operation is running (for an observable amount of time), the progress bar doesn't show. I set the progress bar as VISIBLE in onPreExecute and set it as GONE in onPostExecute.
I'm wondering if it's because I have GoogleTranslate and MyVocab in two different java files since most of the examples I see have async class and the class that calls it in the same java file. Please let me know if there's anything I'm doing wrong that's causing this problem.
Here's the related code:
GoogleTranslate.java
public class GoogleTranslate extends AsyncTask<String, Void, String>{
private ProgressBar mProgressBar;
public GoogleTranslate(ProgressBar progressBar) {
super();
mProgressBar = progressBar;
}
#Override
protected void onPreExecute() {
mProgressBar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String s) {
mProgressBar.setVisibility(View.GONE);
}
#Override
protected String doInBackground(String... params) {
String vocab = params[0];
String source = params[1];
String target = params[2];
String sourceQuery = "";
String targetQuery = "&target=" + target;
// "" means its
if (!source.equals("Detect Language")) {
sourceQuery = "&source=" + source;
}
try {
String APIKey = "MY_API_KEY";
String encodedQuery = URLEncoder.encode(vocab, "UTF-8");
URL url = new URL("https://www.googleapis.com/language/translate/v2?key=" +
APIKey +
"&q=" +
encodedQuery +
sourceQuery +
targetQuery);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
finally {
urlConnection.disconnect();
}
}
catch (Exception e) {
return null;
}
}
}
Parts of method from MyVocab:
protected void addVocabAlertDialog(final VocabDbHelper dbHelper, final String category,
final VocabCursorAdapter cursorAdapter) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Add Vocab");
LayoutInflater li = LayoutInflater.from(CategoryItem.this);
View promptsView = li.inflate(R.layout.alert_dialog_add_vocab, null);
final EditText vocabInput = (EditText) promptsView.findViewById(R.id.vocabInput);
final EditText definitionInput = (EditText) promptsView.findViewById(R.id.definitionInput);
final ProgressBar progressBar = (ProgressBar) promptsView.findViewById(R.id.progressBar);
builder.setView(promptsView);
final GoogleTranslate googleTranslate = new GoogleTranslate(progressBar);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String vocab = vocabInput.getText().toString();
String definition = definitionInput.getText().toString();
dbHelper.insertVocab(category, vocab, definition, 0);
if (!category.equals(VocabDbContract.CATEGORY_NAME_MY_WORD_BANK)) {
dbHelper.insertVocab(VocabDbContract.CATEGORY_NAME_MY_WORD_BANK, vocab, definition, 0);
}
// Update Cursor
Cursor cursor = dbHelper.getVocabCursor(category);
cursorAdapter.changeCursor(cursor);
}
});
final AlertDialog dialog = builder.create();
dialog.show();
dialog.getButton(AlertDialog.BUTTON_NEUTRAL).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String vocab = vocabInput.getText().toString();
SharedPreferences sharedPreferences = getSharedPreferences("Translation", MODE_PRIVATE);
int sourcePos = sharedPreferences.getInt("Source", 0); // 0 is for Detect Language
int targetPos = sharedPreferences.getInt("Target", 19); // 19 is for English
String source = LanguageOptions.FROM_LANGUAGE_CODE[sourcePos];
String target = LanguageOptions.TO_LANGUAGE_CODE[targetPos];
final AlertDialog.Builder builder = new AlertDialog.Builder(CategoryItem.this);
builder.setMessage("Network is unavailable. Please try again later.");
builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog dialog = builder.create();
if (isNetworkAvailable()) {
AsyncTask<String, Void, String> asyncTask = googleTranslate.execute(vocab, source, target);
try {
String translatedJSON = asyncTask.get();
JSONParser jsonParser = new JSONParser();
String translatedText = jsonParser.parseJSONForTranslation(translatedJSON);
definitionInput.setText(translatedText);
} catch (Exception e) {
dialog.show();
}
}
else {
dialog.show();
}
}
});
}
XML file that contains progress bar:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Vocab"
android:id="#+id/vocabInput"
android:inputType="textAutoComplete"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Definition"
android:id="#+id/definitionInput"
android:inputType="textAutoComplete"
android:layout_below="#+id/vocabInput"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone"
android:indeterminate="true"
android:id="#+id/progressBar"/>
I'd suggest using ProgressDialog instead.
I switched from ProgressBar because I faced a similar issue, even after programmatically creating one in the default constructor of my AsyncTask.
public class GoogleTranslate extends AsyncTask<String, Void, String> {
private ProgressDialog mProgressDialog;
private Context mContext;
public GoogleTranslate(Context context) {
mContext = context;
}
#Override
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(
mContext,
"Please wait", // Title
"Translating", // Message
true // Indeteriminate flag
);
}
#Override
protected String doInBackground(String... params) {
...
}
#Override
protected void onPostExecute(String s) {
if (mProgressDialog != null) {
mProgressDialog.dismiss();
}
...
}
}
Call this AsyncTask like this:
new GoogleTranslate(getActivity() /* or getContext() */).execute(vocab, source, target);
Try to avoid the AsyncTask get() method and use a listener instead.
You should update your code this way:
1) In your googleTranslate class, add a listener:
private Listener listener;
public interface Listener{
void onTaskResult(String string);
}
public void setListener(Listener listener){
this.listener = listener;
}
and call it in your onPostExecute:
#Override
protected void onPostExecute(String s) {
if (listener!=null){ listener.onTaskResult(s); }
mProgressBar.setVisibility(View.GONE);
}
2) update your main class replacing the get with the listener management, replacing this:
AsyncTask<String, Void, String> asyncTask = googleTranslate.execute(vocab, source, target);
try {
String translatedJSON = asyncTask.get();
JSONParser jsonParser = new JSONParser();
String translatedText = jsonParser.parseJSONForTranslation(translatedJSON);
definitionInput.setText(translatedText);
} catch (Exception e) {
dialog.show();
}
with this:
googleTranslate.setListener(new GoogleTranslate.Listener() {
#Override
public void onTaskResult(String string) {
String translatedJSON = string;
JSONParser jsonParser = new JSONParser();
String translatedText = jsonParser.parseJSONForTranslation(translatedJSON);
definitionInput.setText(translatedText);
}
});
googleTranslate.execute(vocab, source, target);
I hope it helped.
add this before executing the googleTranslate :
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress(0);
AsyncTask<String, Void, String> asyncTask = googleTranslate.execute(vocab,source, target);
and also implement the onProgressUpdate in googleTranslate.
this link may help :
http://www.concretepage.com/android/android-asynctask-example-with-progress-bar
Try passing ProgressBar as constructor argument of GoogleTranslate class.
Add progress bar in your onPreExecute method and hide it in onPostExecute.
private class MyAsyncThread extends AsyncTask<Void, Void, String>
{
#SuppressWarnings("finally")
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
// your code
}
catch (Exception e) {
// TODO: handle exception
}
finally
{
return "OK";
}
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (progressDialog != null) {
progressDialog.dismiss();
progressDialog = null;
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(this, null, "Please wait....");
}
That's because you are blocking Main Thread by asyncTask.get() call, so no UI operations can run until asyncTask completes.
Remove this call and process the asyncTask's results in its onPostExecute(String s) and onCancelled() callbacks instead.
I have this AsyncTask:
public static void login(final String email, final String password,
final String token, final SocketHandler handler) {
execute(new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(final Void... params) {
Log.d("ACEPTAR", "DOINBACKGROUND");
String url = handler.servidor.getUrl();
url += "/login-usuario";
String str;
try {
str = postResponseFromServer(url, "mail", email, "pass",
password, "tipo", "1", "token", token);
Log.d("ACEPTAR", str);
final CustomJSONObject object = new CustomJSONObject(str);
final CustomJSONObject object2 = new CustomJSONObject();
object2.put("datos", object);
final CustomJSONArray array = new CustomJSONArray();
array.put(object2);
handler.on("resultado-login", array);
} catch (final Exception ex) {
ex.printStackTrace();
handler.on("error-login", new CustomJSONArray());
}
return null;
}
});
}
#SuppressLint("InlinedApi")
private static void execute(final AsyncTask<Void, Void, Void> task) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
task.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
} else {
task.execute();
}
}
I try to do it on 3G, always works. Then I connect to Wi-Fi. The AsyncTask gets called on 4.0+, but not in 2.3.7-.
Am I missing something?
Try creating a separate Thread and do your stuff in there, post your results with Activity.runInUiThread(). See if there's any problem with that. If there's no problem, then it's perhaps because of some AsyncTask bug.
I use this code inorder to get the content of some website.
the textview stay empty. What I am doing wrong?
I added the jar into librires and also add internet permission to manifest.
public class MainActivity extends Activity {
MyTask mt;
TextView tvInfo;
String URL="http://www.example.com/";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvInfo = (TextView) findViewById(R.id.textView1);
}
public void onclick(View v) {
mt = new MyTask();
mt.execute(URL);
}
class MyTask extends AsyncTask<String, Void, String> {
Document doc;
String title=null;
#Override
protected void onPreExecute() {
super.onPreExecute();
tvInfo.setText("Please wait");
}
#Override
protected String doInBackground(String... params) {
try {
TimeUnit.SECONDS.sleep(2);
// doc = Jsoup.connect(params[0]).get();
// String title = doc.title();
doc = Jsoup.connect("http://www.example.com/").get();
Element content = doc.select("a").first();
title = content.text();
Log.d("AsyncTask doInBackground","URL: " + params[0]);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return title;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
tvInfo.setText(title);
}
}
}
I also not understand excaly when each method here is called
THANKS A LOT!
EDIT - the code after what was suggested in answer. Still not working:
public class MainActivity extends Activity implements OnClickListener{
MyTask mt;
TextView tvInfo;
String URL="http://www.example.com/";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvInfo = (TextView) findViewById(R.id.textView1);
tvInfo.setOnClickListener(this);
}
private class MyTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String title = "hh";
try{
Document doc = Jsoup.connect("http://google.com").userAgent("Mozilla").get();
title = doc.title();
System.out.println("title : " + title);
// get all links
Elements links = doc.select("a[href]");
for (Element link : links) {
// get the value from href attribute
System.out.println("\nlink : " + link.attr("href"));
System.out.println("text : " + link.text());
}
}
catch (IOException e) {
e.printStackTrace();
}
return title;
}
#Override
protected void onPostExecute(String result) {
tvInfo.setText(result);
}
#Override
protected void onPreExecute() {
tvInfo.setText("Please wait");
}
}
#Override
public void onClick(View v) {
mt = new MyTask();
mt.execute(URL);
}
}
The AsyncTask executes everything in doInBackground() inside of another thread, which does not have access to the GUI where your views are.
preExecute() and postExecute() offer you access to GUI before and after the heavy lifting occurs in this new thread, you can even pass the result of the long operation to postExecute() to then show any results of processing.
private class MyTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try{
Document doc = Jsoup.connect("http://google.com").userAgent("Mozilla").get();
String title = doc.title();
System.out.println("title : " + title);
// get all links
Elements links = doc.select("a[href]");
for (Element link : links) {
// get the value from href attribute
System.out.println("\nlink : " + link.attr("href"));
System.out.println("text : " + link.text());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {
super.onPreExecute();
tvInfo.setText("Please wait");
}
}
An Activity (SignInActivity) is calling a method in FunkcjeAPI which execute an AsyncTask.
My AsyncTask should show a ProgressDialog using an calling Activity. I don't know how to give it an correct Activity to the constructor. I tried a lot of thing, read a lot of tutorials and questions on SO, but I can't find solution. FunkcjeAPI isn't an Activity so I can't write new Logowanie(this).execute(argumenty);
AsyncTask calling code :
public class FunkcjeAPI {
static String dozwrotu = null;
public static String zalogujSie(final String nick, final String haslo)
{
String[] argumenty = {nick, haslo};
new Logowanie(/* WHAT HERE ? */).execute(argumenty); // HELP ME IN THAT LINE !!!!!!!!!!!!!
return dozwrotu;
}
My AsyncTask class code (it is in FunkcjeAPI class):
private class Logowanie extends AsyncTask<String, Void, String>
{
Activity wywolujaceActivity;
public Logowanie(Activity wywolujaceActivity) {
this.wywolujaceActivity = wywolujaceActivity;
}
#SuppressWarnings("deprecation")
#Override
protected void onPreExecute() {
wywolujaceActivity.showDialog(SignInActivit.PLEASE_WAIT_DIALOG);
}
#Override
protected String doInBackground(final String... argi) {
final JSONParser jParser = new JSONParser();
new Thread(new Runnable() {
public void run() {
final String json = jParser.getJSONFromUrl("http://tymonradzik.pl/THUNDER_HUNTER/thapi.php?q=login&username=" + argi[0] + "&password=" + argi[1] + "&imei=");
Handler mainHandler = new Handler(Looper.getMainLooper());
mainHandler.post(new Runnable() {
#Override
public void run() {
JSONObject jObject;
try {
jObject = new JSONObject(json);
Log.wtf("Link", "http://tymonradzik.pl/THUNDER_HUNTER/thapi.php?q=login&username=" + argi[0] + "&password=" + argi[1] + "&imei=");
Log.wtf("Link", json);
String error = jObject.getString("error");
if(error == "You reached daily query limit !") { nadajWartosc("You reached daily query limit !"); }
if(error == "0") {nadajWartosc(jObject.getString("token"));}
if(error == "1") {nadajWartosc("1");}
if(error == "Invalid username") {nadajWartosc("Invalid username");}
if(error == "Invalid password") {nadajWartosc("Invalid password");}
if(error == "This user is already logged in !") {nadajWartosc("This user is already logged in !");}
} catch (JSONException e1) {
e1.printStackTrace();
}
catch (NullPointerException e)
{
e.printStackTrace();
}
}
});
}}).start();
return dozwrotu;
}
#Override
protected void onPostExecute(String result) {
wywolujaceActivity.removeDialog(SignInActivit.PLEASE_WAIT_DIALOG);
}
}
Add one more parameter to zalogujSie() method that takes an Activity, and then use this parameter to start the AsyncTask:
public static String zalogujSie(Activity activity, final String nick, final String haslo)
{
// .....
new Logowanie(activity).execute(argumenty);
return dozwrotu;
}
Then you would call this method from the activity like this:
FunkcjeAPI.zalogujSie(this, "Nick", "Haslo");