Issue
I start to do sync for my app with Android Studio. My code is (timeout code based on this answer by kuester2000):
private class Check_Loguin_Request extends AsyncTask<String,Void,String>{
@Override
protected String doInBackground(String... strings) {
//Declaration of variables
String User = strings[0];
String Pass = strings[1];
DefaultHttpClient httpClient;
HttpPost Request = new HttpPost(url_Loguin);
HttpResponse Response;
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
httpClient = new DefaultHttpClient(httpParameters);
List<NameValuePair> BodyRequest_Elements = new ArrayList<NameValuePair>();
BodyRequest_Elements.add(new BasicNameValuePair("user_name", User));
BodyRequest_Elements.add(new BasicNameValuePair("user_passwd", Pass));
try {
HttpEntity entity = new UrlEncodedFormEntity(BodyRequest_Elements);
Request.setHeader(entity.getContentType());
Request.setEntity(entity);
Response = httpClient.execute(Request);
HttpEntity entity2 = Response.getEntity();
InputStream is = entity2.getContent();
return Response.toString();
}
catch (Exception ex){
Log.getStackTraceString(ex);
return null;
}
}
protected void onPostExecute(String result){
Toast.makeText(this, "Task Finalized: " + result, Toast.LENGTH_SHORT).show();
}
}
This class is a external class(Sync_Class) of my main activity(Loguin_Activity), when i call this in toast ide give me error. Then how can I send Context from my activity? Thanks in advance and sorry for my english!
PD1: If you need more code or info advice me! :D
Solution
In the your Task class, create a constructor and give it your context like this:
private class Check_Loguin_Request
{
Context cx;
public Check_Loguin_Request(Context cx)
{
this.cx=cx;
}
}
Then in the OnPostExecute use this cx
protected void onPostExecute(String result)
{
Toast.makeText(cx, "Task Finalized: " + result, Toast.LENGTH_SHORT).show();
}
The use this class like this:
Check_Loguin_Request login=new Check_Loguin_Request(getBaseContext());
Answered By - Mohi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.