My application skips AsyncTask.execute() and crashes - java

here is my onCreate method the problem is that the app shows the toast "Finish ! " but it dosen't execute li.execute(Email,Password); and it crashes. that's it
I want the app to do what's inside li.execute(Email,Password); first.
PS : loginBackgroundWorker is a class that extends AsyncTask<String,String,String> and it has onPreExecute() and doInBackground() and onPostExecute() methods.
The app dosen't show any errors or warnings but it crashes in the emulator.
here is the code :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
li = new loginBackgroundWorker(LoginActivity.this);
//loginBackgroundWorker is a class that extends AsyncTask
EditTextEmail =(EditText) findViewById(R.id.emailField);
EditTextPassword =(EditText) findViewById(R.id.passwordField);
loginButton = (CardView) findViewById(R.id.loginButton);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Email = EditTextEmail.getText().toString().trim();
Password = EditTextPassword.getText().toString().trim();
li.execute(Email,Password);
Toast.makeText(LoginActivity.this,"Finish !",Toast.LENGTH_LONG).show();
}
});
}
here is AsyncTask Class (I don't think that what is inside those functions is important for you)
public class loginBackgroundWorker extends AsyncTask<String,String,String> {
Context context;
public String email;
public String password;
public static final String login_url="http://192.168.0.104/login.php";
public loginBackgroundWorker(Context context) {
this.context = context;
}
#Override
public void onPreExecute() {
//Toast.makeText(context,"preExecute",Toast.LENGTH_LONG).show();
}
#Override
public String doInBackground(String... params) {
try {
email = params[0];
password = params[1];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("email","UTF-8")+"="+URLEncoder.encode(email,"UTF-8")+"&"
+URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result="";
String line="";
while((line = bufferedReader.readLine())!= null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
public void onPostExecute(String result) {
Toast.makeText(context,"Onpost",Toast.LENGTH_LONG).show();
String r=result.trim();
Boolean aBoolean = true;
if (result.equals("1"))
{
Toast.makeText(context,"Bien Connecté",Toast.LENGTH_LONG).show();
aBoolean = false;
}
else if (result.equals(""))
r = "Login ou mot de passe incorrect";
if (aBoolean)
{
Toast.makeText(context,r,Toast.LENGTH_LONG).show();
}
}
}
here is the StackTrace
--------- beginning of crash
05-26 14:56:24.023 14756-14756/com.example.zaariou.blacklist E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.zaariou.blacklist, PID: 14756
java.lang.IllegalStateException: Cannot execute task: the task is already running.
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:593)
at android.os.AsyncTask.execute(AsyncTask.java:551)
at com.example.zaariou.blacklist.LoginActivity$1.onClick(LoginActivity.java:58)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Instance of AsyncTask can only run once.
If you want to reuse your AsyncTask you must initialize new instance of your loginBackgroundWorker and run it.
Move your loginBackgroundWorker initialization to your OnClickListener.onClick handle

Related

How can I load the new activity after login in android studio?

Basically, I want to start a new activity after login using the database. How can I do that?
This is my login class
public class login extends AppCompatActivity {
EditText username;
EditText password;
Button btn_login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
btn_login = (Button) findViewById(R.id.btn_login);
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String user = username.getText().toString();
String pass = password.getText().toString();
String type = "login";
System.out.println("IN Onclick login");
BackgroundTask backgroundTask = new BackgroundTask(getApplicationContext());
backgroundTask.execute(type,user,pass);
if(backgroundTask.statusOK.equals("true")) {
Intent loginIntent = new Intent(login.this,loggedIn.class);
startActivity(loginIntent);
}
}
});
}
}
You can see in the code above that I am using this code to start my new activity after successful login, but this is not starting a new activity. I don't know why?
if(backgroundTask.statusOK.equals("true")) {
Intent loginIntent = new Intent(login.this,loggedIn.class);
startActivity(loginIntent);
}
This is BackgroundTask class
public class BackgroundTask extends AsyncTask<String, String, String> {
Context context;
public String statusOK="false";
BackgroundTask(Context ctx){
this.context = ctx;
}
#Override
protected String doInBackground(String... strings) {
System.out.println("In doin");
String type = strings[0];
String loginURL = "http://192.168.10.119/log/login.php";
String regURL = "http://192.168.10.119/log/log.php";
if(type.equals("reg")){
String name = strings[1];
String pass = strings[2];
try{
URL url = new URL(regURL);
try {
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream,"UTF-8");
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
String insert_data = URLEncoder.encode("Username","UTF-8")+"="+URLEncoder.encode(name,"UTF-8")+
"&"+URLEncoder.encode("Password","UTF-8")+ "=" +URLEncoder.encode(pass,"UTF-8");
bufferedWriter.write(insert_data);
bufferedWriter.flush();
bufferedWriter.close();
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"ISO-8859-1");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String result="";
String line="";
StringBuilder stringBuilder = new StringBuilder();
while((bufferedReader.readLine())!= null){
stringBuilder.append(line).append("\n");
}
result = stringBuilder.toString();
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
else if(type.equals("login")){
System.out.println("In type = login");
String name1 = strings[1];
String pass1 = strings[2];
try{
URL url = new URL(loginURL);
try {
System.out.println("In type = login try");
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream,"UTF-8");
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
String login_data = URLEncoder.encode("Username","UTF-8")+"="+URLEncoder.encode(name1,"UTF-8")+
"&"+URLEncoder.encode("Password","UTF-8")+ "=" +URLEncoder.encode(pass1,"UTF-8");
bufferedWriter.write(login_data);
bufferedWriter.flush();
bufferedWriter.close();
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"ISO-8859-1");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String result="";
String line="";
StringBuilder stringBuilder = new StringBuilder();
while((bufferedReader.readLine())!= null){
stringBuilder.append(line).append("\n");
}
result = stringBuilder.toString();
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
statusOk="true";
Toast.makeText(context, "Successful", Toast.LENGTH_LONG).show();
//super.onPostExecute(s);
}
}
I have checked the connection between the database and my app is established and the app is running without any error.
You can see in the code above that I have created a public variable statusOk and initialize it with "false". This variable is telling the login class that the user have entered his correct login credentials.
You can see that I have changed the value of statusOk to "true" onPostExexute method.
Now the problem is my new activity is not opening from the login class after successful login. Please give me a solution how can I open a new activity after Login with correct login credentials.
Asynctask is used to execute task in the background thread, (not the main thread from where you have called the execute() ).
Therefore in your code, if statement is executed just after you called the execute(), which still store the variable statusOK as false. Hence the condition is false.
The postExecute() method of asynctask is used to execute code in the main thread,
My suggestion: remove the if condition from the Login class, and check for the if condition in the postExecute(),

Returning result from Asynctask

If I have this background worker file in my android application and it gets data from my database how can I pass the string 'result' to another class?
The background worker connects to my server and then using php it connects to a database.
public class BackgroundWorker extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker (Context ctx) {
context = ctx;
}
#Override
public String doInBackground(String... params) {
String type = params[0];
String specials_url = "";
if(type.equals("venue click")) {
try {
//String user_name = params[1];
URL url = new URL(specials_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
// String post_data = URLEncoder.encode("user_name","UTF-8")+"="+URLEncoder.encode(user_name,"UTF-8");
// bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result="";
String line="";
while((line = bufferedReader.readLine())!= null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Info");
}
#Override
protected void onPostExecute(String result) {
alertDialog.setMessage(result);
alertDialog.show();
// String temp = "login success";
// if (result.equals(temp)) {
// Intent intent = new Intent(context, Register.class);
// context.startActivity(intent);
// }
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
You need a listener. This will allow you to notify back when the AsyncTask is done.
Define the listener by creating an interface, like this:
public interface IListener
{
void onCompletedTask(String result);
}
On the task store a reference to the listener.
private IListener mListener;
// Pass the reference to the constructor.
public BackgroundWorker(IListener listener)
{
mListener = listener;
}
Then you notify the listener like this.
#Override
protected void onPostExecute(String result)
{
mListener.onCompletedTask(result);
}
Best way to get a callback from background thread is to use interfaces as a callback from AsyncTask for example:
create an interface that can be called in onPostExecute()
public interface ResponseCallback {
void onRespond(String result);
}
and before calling asynckTask define it like this:
ResponseCallback cpk = new ResponseCallback() {
#Override
public void onRespond(String result) {
//code to be done after calling it from onPostExecute
}
};
and pass cpk to the constructor of of the asynckTask and call it in onPostExecute like that:
if(cpk!=null){
cpk.onRespond(result);
}
of course you can modify the signature of the interface to what ever you want.

Android - Error During Showing AlertDialog from Fragment

I'm trying to send and receive data, but I have this error:
FATAL EXCEPTION: main
Process: smaa.smaa, PID: 4051
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.Context.getTheme()' on a null object reference
at android.support.v7.app.AlertDialog.resolveDialogTheme(AlertDialog.java:113)
at android.support.v7.app.AlertDialog$Builder.<init>(AlertDialog.java:291)
at smaa.smaa.BackgroundT.onPreExecute(BackgroundT.java:46)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:613)
at android.os.AsyncTask.execute(AsyncTask.java:560)
at smaa.smaa.FirstFragment.onClick(FirstFragment.java:44)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22260)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
This is my fragment:
public class FirstFragment extends Fragment implements View.OnClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_first, container, false);
Button btn1 = (Button)v.findViewById(R.id.btn1);
btn1.setOnClickListener(this);
return v;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn1:
String method = "see";
BackgroundT backgroundT = new BackgroundT(this);
backgroundT.execute(method);
break;
}
}
}
And my BackgroundTask:
public class BackgroundT extends AsyncTask<String,Void,String> {
AlertDialog alertDialog;
Context ctx;
String response = "";
private Context applicationContext;
private Context activity;
public BackgroundT(Context ctx) {
this.ctx = ctx;
}
public BackgroundT(FirstFragment firstFragment) {
this.ctx = ctx;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
alertDialog = new AlertDialog.Builder(ctx).create();
alertDialog.setTitle("Ver Tickets");
}
#Override
protected String doInBackground(String... params) {
String see_url = "https://smaa.000webhostapp.com/androidver.php";
String method = params[0];
if (method.equals("see")) {
String login_name = params[1];
String login_pass = params[2];
String test = "test";
try {
URL url = new URL(see_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String data = URLEncoder.encode("test", "UTF-8") + "=" + URLEncoder.encode(test, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String line = "";
while ((line = bufferedReader.readLine()) != null) {
response += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(ctx, response, Toast.LENGTH_LONG).show();
}
}
I know the problem is in the Context or ctx, but I don't know where, I've used something like this and it worked before so I don't know what is the problem now, here is a working version:
BackgroundTask: http://pastebin.com/UnxaSV2X
MainActivity: http://pastebin.com/rk5jufBc
--- EDIT ---
Thanks to #rafsanahmad007, here's what I fixed:
Fragment code:
String method = "see";
BackgroundT backgroundT = new BackgroundT(getActivity());
backgroundT.execute(method);
break;
BackgroundTask code:
public BackgroundT(FragmentActivity activity) {
this.ctx = activity;
}
There was also another error which I fixed later here:
String login_name = params[1];
String login_pass = params[2];
This was giving me an error because I wasn't using it, thanks everyone.
You need the Activity context to show a AlertDialog in Fragment
instead of;
BackgroundT backgroundT = new BackgroundT(this);
backgroundT.execute(method);
try this:
BackgroundT backgroundT = new BackgroundT(getActivity());
backgroundT.execute(method);
EDIT
Also Edit the constructor:
public BackgroundT(FragmentActivity activity) {
this.ctx = activity;
}
public BackgroundT(FirstFragment firstFragment) {
this.ctx = ctx;
}
pay attention ctx=ctx, so it is null and it fails when you construct the alert

FileNotFoundException encountered when trying to send JSON over network [duplicate]

This question already has answers here:
FileNotFoundException while getting the InputStream object from HttpURLConnection
(8 answers)
Closed 6 years ago.
My code to that sends JSON over the network works until OutputStream is invoked, but when I try actually sending the data, I get the following exception. Can anyone help me figure it out?
java.io.FileNotFoundException: http://hmkcode.appspot.com/jsonservlet
at
com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:238)
at app.test.testapp2.MainActivity$HttpAsyncTask.doInBackground(MainActivity.java:84)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.accept);
textView = (TextView) findViewById(R.id.textView);
editName = (EditText) findViewById(R.id.editName);
editCountry = (EditText) findViewById(R.id.editCountry);
editTwitter = (EditText) findViewById(R.id.editTwitter);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
HttpAsyncTask httpAsyncTask = new HttpAsyncTask(MainActivity.this);
httpAsyncTask.execute("http://hmkcode.appspot.com/jsonservlet", editName.getText().toString(), editCountry.getText().toString(), editTwitter.getText().toString());
}
});
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
private MainActivity mainActivity;
String result = "";
HttpAsyncTask(MainActivity mainActivity) {
this.mainActivity = mainActivity;
}
#Override
protected String doInBackground(String... strings) {
Person person = new Person();
person.setName(strings[1]);
person.setCountry(strings[2]);
person.setTwitter(strings[3]);
try {
URL url = new URL(strings[0]);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
String json = "";
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("name", "!!!");
jsonObject.accumulate("country", "###");
jsonObject.accumulate("twitter", "####");
json = jsonObject.toString();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestProperty("Accept", "application/json");
httpURLConnection.setRequestProperty("content-type", "application/json");
InputStream is = httpURLConnection.getInputStream();
OutputStream os = httpURLConnection.getOutputStream();
os.write(json.getBytes("utf-8"));
os.flush();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String result) {
str = result;
mainActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
JSONArray jsonArray = new JSONArray(str);
mainActivity.textView.setText(jsonArray.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
}
W/System.err: java.io.FileNotFoundException: http://hmkcode.appspot.com/jsonservlet
W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:238)
W/System.err: at app.test.testapp2.MainActivity$HttpAsyncTask.doInBackground(MainActivity.java:84)
.....
This is equivalent to HTTP status 404 - Not Found.

AsyncTask dont show me message from server (HttpUrlConnection)

So I'm trying to read a message from the server by HttpURLConnection in a AsyncTask class. The problem is, when i send the request to read the data from the server, it just keeps displaying the ProgresssDialog, like it doesn't read the data from the server:
public class MainActivity extends Activity{
EditText name, password;
Button login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText) findViewById(R.id.name);
password = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String serverURL = "http://192.168.1.1/my/text.php";
LongOperation longOperation = new LongOperation();
longOperation.execute(serverURL);
}
});
}
private class LongOperation extends AsyncTask<String, Void, Void> {
private String content;
private String error = null;
private ProgressDialog dialog = new ProgressDialog(MainActivity.this);
TextView uiUpdate = (TextView) findViewById(R.id.output);
#Override
protected void onPreExecute() {
uiUpdate.setText("Output : ");
dialog.setMessage("Downloading source..");
dialog.show();
}
#Override
protected Void doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
HttpURLConnection client = (HttpURLConnection)url.openConnection();
client.connect();
InputStream inputStream = client.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
content = bufferedReader.readLine();
bufferedReader.close();
inputStream.close();
client.disconnect();
} catch (IOException e) {
error = e.getMessage();
}
return null;
}
#Override
protected void onPostExecute(Void unused) {
dialog.dismiss();
if (error != null) {
uiUpdate.setText("Output : "+error);
} else {
uiUpdate.setText("Output : "+content);
}
}
I already tryed before the connectivity to server via HttpClient, so thats not the problem.Thanks!
Try debugging it and see if OnPostExecute() method is getting called or not.!
This seems to get stuck in your stream reader code. Also, add a connection timeout of, say, 5-10 seconds for better user experience.!
Moreover, there seems to be an issue with your return type of doInBackground() method and input parameter type of OnPostExecute() method. As per your AsyncTask definition, they both should be string, isnt it?
See this
Try remove client.connect();
try {
URL url = new URL(urls[0]);
HttpURLConnection client = (HttpURLConnection)url.openConnection();
//remove client.connect();
int response = client.getResponse();
if(response == HttpURLConnection.HTTP_OK){
InputStream inputStream = client.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
content = bufferedReader.readLine();
bufferedReader.close();
inputStream.close();
}
finally{
client.disconnect();
}
} catch (IOException e) {
error = e.getMessage();
}
return null;
Make sure your server is running. Also set request time out.
You are not always required to explicitly call the connect method to initiate the connection. Operations that depend on being connected, like getInputStream, getOutputStream will implicitly perform the connection, when necessary.
This link
Try this:
private class LongOperation extends AsyncTask<String, Void, String>
{
private String content;
private String error = null;
private ProgressDialog dialog = new ProgressDialog(MainActivity.this);
TextView uiUpdate = (TextView) findViewById(R.id.output);
#Override
protected void onPreExecute() {
uiUpdate.setText("Output : ");
dialog.setMessage("Downloading source..");
dialog.show();
}
#Override
protected Strinh doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
HttpURLConnection client = (HttpURLConnection)url.openConnection(); client.connect();
InputStream inputStream = client.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
content = bufferedReader.readLine();
bufferedReader.close();
inputStream.close();
//client.discon dialog.dismiss();
}
catch (IOException e)
{
content = e.getMessage();
}
return content ;
}
#Override
protected void onPostExecute(String returnValue) {
if (return value != null) {
uiUpdate.setText("Output : "+error);
}
else {
uiUpdate.setText("Output No Value Returned");
}
dialog.dismiss();
}

Categories

Resources