AsyncTask to Check for new data in every 10 seconds - android

I am using AsyncTask to fetch data from server, what if to check whether any new data available or to update changes in existing data in every 10 seconds
public class MainActivity extends Activity {
CenterLockHorizontalScrollview centerLockHorizontalScrollview;
ArrayList<Actors> actorsList;
ActorAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actorsList = new ArrayList<Actors>();
new JSONAsyncTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
centerLockHorizontalScrollview = (CenterLockHorizontalScrollview) findViewById(R.id.scrollView);
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Actors actor = new Actors();
actor.setName(object.getString("name"));
Log.d("Name:", object.getString("name"));
actor.setImage(object.getString("image"));
Log.d("Image:", object.getString("image"));
actorsList.add(actor);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
if(actorsList != null) {
adapter = new ActorAdapter(getApplicationContext(), R.layout.row, actorsList);
centerLockHorizontalScrollview.setAdapter(MainActivity.this, adapter);
}
}
}

There is several ways on going about this. The most suitable one will depends mostly on the specs, design & architecture decision for you're app.
1) Java's TimerTask.
import java.util.Timer;
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// work
}
}, 0, 10*1000); // 0 - time before first execution, 10*1000 - repeating of all subsequent executions
timer.cancel(); //cancels the timer and all schedules executions
2) Android's Handler. Powerful feature and commonly used for things like what you are asking. But, you must make sure you are not nesting handlers. More info here ; it describes more or less the solution for what you are looking for using Handlers.
3) Android's scheduled alarms. Even though this would work, if you really want to run something every 10 seconds, then, i will say this is probably not the best solution. But anyway, this allows you register for Android's alarms, which gives you a bit of time to run something in a BroadcastReceiver, which is triggered when the alarm is fired. There's a lot into this, but you can learn how to schedule an alarm here : https://developer.android.com/training/scheduling/alarms.html

you can check by using refresh method.
void refresh(boolean b){
if(b){
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
new JSONAsyncTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
refresh(true);
}
}, 10*1000);
}
}
call this method in your oncreate
new JSONAsyncTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
refresh(true);

Related

TimerTask is scheduled for every 15 minutes to refresh the data of app. How can i execute the timertask for once outside the class

TimerTask is scheduled for every 15 minutes to refresh the data of the app. How can i execute the TimerTask for once outside the class without affecting the scheduled timer task as i have to keep updating the data of the app every 15 minutes. There is a scenario where i need to immediately update the data outside the class.
public class SplashActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
}
final Handler handler = new Handler();
timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
if (timer == null) {
cancel();
}
Boolean isInternetPresent = internetCheck.isConnectingToInternet();
if(isInternetPresent)
new MyAsyncTask().execute();
else
System.out.println("Internet connection not presents ");
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 900000);
}
public class MyAsyncTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
long s_time = System.currentTimeMillis();
android.util.Log.i("Start ", " Time value in millisecinds " + s_time);
String xmlDataOverHttp = PostData();
long e_time = System.currentTimeMillis();
android.util.Log.i("End ", " Time value in millisecinds " + e_time);
Myregistry registry= AppRegistry.getInstance();
Serializer serializer = new Persister();
MyObject example = null;
try {
example = serializer.read(MyObject.class, student_xml);
} catch (Exception e) {
e.printStackTrace();
}
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(MyObjectXMl, xmlDataOverHttp);
editor.apply();
registry.setObject(example);
return xmlDataOverHttp;
}
public String PostData() {
Boolean s = false;
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
HttpClient httpClient = new DefaultHttpClient(params);
String url = "http://localhost:8080" +"/get_xml_data?id=" + 1;
System.out.println("url----------" + url);
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(httpPost);
} catch (IOException e) {
e.printStackTrace();
}
HttpEntity httpEntity = httpResponse.getEntity();
String token = readResponse(httpResponse);
return token;
}
Here MyAsyncTask is scheduled in TimerTask which gets called after every 15 minutes. How can i call this MyAsyncTask outside the class without affecting the scheduled TimerTask. I cnnot make MyAsyncTask class as static.

How to Update UI from Non-UI thread in android?

I have a Login Fragment that execute AsynkTask and in onPost() I want to update Login Fragment UI .I am already done that need some correction in That.How can I make non-ui thread.
here is my code:-
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
m_Main = inflater.inflate(R.layout.login_screen, container, false);
((AppCompatActivity) getActivity()).getSupportActionBar().hide();
CMainActivity.m_Drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
m_oLoginSession = new CLoginSessionManagement(getActivity());
init();// initialize controls
return m_Main;
}
public void init() {
m_MainLayout = (LinearLayout) m_Main.findViewById(R.id.mainLayout);
m_InputMobile = (EditText) m_Main.findViewById(R.id.input_mobile);
m_InputPassword = (EditText) m_Main.findViewById(R.id.input_password);
m_LoginBtn = (AppCompatButton) m_Main.findViewById(R.id.btn_Login);
m_ChangePass = (AppCompatButton) m_Main.findViewById(R.id.btn_ChangePass);
m_ChangePass.setBackgroundColor(Color.TRANSPARENT);
m_ChangePass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new CChangePasswordScreen()).commit();
}
});
m_RegisterBtn = (AppCompatButton) m_Main.findViewById(R.id.btn_Register);
m_RegisterBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new CRegistrationScreen()).commit();
}
});
m_LoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new LoginAttempt().execute();
}
});
}
private class LoginAttempt extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setCancelable(false);
pDialog.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
// and now the magic
pDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
pDialog.getWindow().setGravity(Gravity.BOTTOM);
pDialog.getWindow().getAttributes().verticalMargin = 0.5f;
pDialog.show();
// CProgressBar.getInstance().showProgressBar(getActivity(), "Please wait while Logging...");// showing progress ..........
}
#Override
protected String doInBackground(String... params) {
getLoginDetails();// getting login details from editText...........
InputStream inputStream = null;
m_oJsonsResponse = new CJsonsResponse();
isFirstLogin = true;
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(s_szLoginUrl);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.put("agentCode", s_szMobileNumber);
jsonObject.put("pin", s_szPassword);
jsonObject.put("firstloginflag", m_oLoginSession.isLogin());
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
// httpPost.setHeader("Accept", "application/json"); ///not required
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
// 9. receive response as inputStream
inputStream = entity.getContent();
System.out.print("InputStream...." + inputStream.toString());
System.out.print("Response...." + httpResponse.toString());
StatusLine statusLine = httpResponse.getStatusLine();
System.out.print("statusLine......" + statusLine.toString());
////Log.d("resp_body", resp_body.toString());
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
// 10. convert inputstream to string
if (inputStream != null) {
s_szresult = m_oJsonsResponse.convertInputStreamToString(inputStream);
//String resp_body =
EntityUtils.toString(httpResponse.getEntity());
}
} else
s_szresult = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return s_szresult;
}
#Override
protected void onPostExecute(final String response) {
super.onPostExecute(response);
m_Handler = new Handler();
new Thread(new Runnable() {
#Override
public void run() {
m_Handler.post(new Runnable() {
#Override
public void run() {
CProgressBar.getInstance().hideProgressBar();// hide progressbar after getting response from server......
try {
m_oResponseobject = new JSONObject(response);// getting response from server
new Thread() {// making child thread...
public void run() {
Looper.prepare();
try {
getResponse();// getting response from server ........
Looper.loop();
} catch (JSONException e) {
e.printStackTrace();
}
}
}.start();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}).start();
}
public void getResponse() throws JSONException {
if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Transaction Successful")) {
m_oLoginSession.setLoginData(s_szResponseMobile, s_szResponsePassword);
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new CDealMainListing()).commit();
CToastMessage.getInstance().showToast(getActivity(), "You are successfully Logged In");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Agentcode Can Not Be Empty")) {
CToastMessage.getInstance().showToast(getActivity(), "Please Enter Valid Mobile Number");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Pin Can Not Be Empty")) {
CToastMessage.getInstance().showToast(getActivity(), "Please Enter Password");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Invalid PIN")) {
CToastMessage.getInstance().showToast(getActivity(), "Please enter correct Password");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Subscriber/Agent Blocked due to Wrong Attempts")) {
CToastMessage.getInstance().showToast(getActivity(), "You are blocked as You finished your all attempt");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Connection Not Available")) {
CToastMessage.getInstance().showToast(getActivity(), "Connection Lost ! Please Try Again");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Subscriber/Agent Not Found")) {
CToastMessage.getInstance().showToast(getActivity(), "User not found ! Kindly Regiter before Login");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("OTP not verify")) {
CToastMessage.getInstance().showToast(getActivity(), "Otp not Verify ! Kindly Generate Otp on Sign Up");
}
}
public void getLoginDetails() {
s_szMobileNumber = m_InputMobile.getText().toString();
s_szPassword = m_InputPassword.getText().toString();
}
}
}
Move the code that is in a thread in onPostExecute() to doInBackground() because this is running in other thread and them refresh you UI in onPostExecute()
A mock example:
#Override
protected String doInBackground(String... params) {
//RUN ALL THAT YOU WANT IN A DIFFERENT THREAD
}
#Override
protected void onPostExecute(final String response) {
//REFRESH THE UI
}
If you are using AsynkTask, you can have a try on onPreExecute and onPostExecute methods that both runs on the UI thread.
Or you can use a handler to update UI.
In your UI thread create an object of Handler like this
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
//Update UI here
//use msg.obj if you have sent Object from background thread
//use msg.what if you have sent Integer from background thread
//Update UI if you have just trigger the handler using sendEmptyMessage(your UI/View gets data from Global Variable)
}
};
Two ways we can trigger Hanler which is created in UI thread
1)handler.sendMessage(Message);
2)handler.sendEmptyMessage(0);
Inside on postExecute of your AsyncTask write below Code based on your requirement
//Message msg=Message.obtain();
//msg.obj=YourObject;//If you want to pass Object
//msg.what=Integer;//If you want to pass Integer
//handler.sendMessage(msg);//to send Message objectdefined above
handler.sendEmptyMessage(0);//If you simply want to trigger

How to get Json object using UrlConnection in android?

Hi I am very for android just one week ago I come into this technology and in my app I am integrating services.
Here I have used HttpClient for that, but in android 6 I was deprecated.
That's why we have to use URlconnection, but how can we use this Url connection instead of HttpClient?
My code is below.
Please help me.
my code:-
public class MainActivity extends Activity {
ArrayList<Actors> actorsList;
ActorAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actorsList = new ArrayList<Actors>();
new JSONAsyncTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
ListView listview = (ListView)findViewById(R.id.list);
adapter = new ActorAdapter(getApplicationContext(), R.layout.row, actorsList);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), actorsList.get(position).getName(), Toast.LENGTH_LONG).show();
}
});
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Actors actor = new Actors();
actor.setName(object.getString("name"));
actor.setDescription(object.getString("description"));
actor.setDob(object.getString("dob"));
actor.setCountry(object.getString("country"));
actor.setHeight(object.getString("height"));
actor.setSpouse(object.getString("spouse"));
actor.setChildren(object.getString("children"));
actor.setImage(object.getString("image"));
actorsList.add(actor);
}
return true;
}
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}
Use Volley instead. Volley is compatible with almost all APIs.
See here on how to do this.

How to run AsyncTask every X second in Android Studio?

I'm executing AsyncTask that fetch data from my web host. In order for me to retrieve data, I need to re-open my app. How can I fetch data every second? I know that AsyncTask could only be executed once, but I needed it not only for my app but also to learn about this problem. Hope to learn from you guys.
By the way this is my code:
class AsyncDataClass2 extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... params) {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost(params[0]);
String jsonResult = "";
try
{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", params[1]));
nameValuePairs.add(new BasicNameValuePair("password", params[2]));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return jsonResult;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
if (result.equals("") || result == null)
{
Toast msg = Toast.makeText(MapsActivity.this, "connection failed", Toast.LENGTH_LONG);
msg.setGravity(Gravity.CENTER, 0, 0);
msg.show();
}
else
{
Toast msg = Toast.makeText(MapsActivity.this, "connected", Toast.LENGTH_LONG);
msg.setGravity(Gravity.CENTER,0,0);
msg.show();
}
try {
JSONArray json = new JSONArray(result);
for (int i = 0; i < json.length(); i++) {
JSONObject e = json.getJSONObject(i);
String point = e.getString("Point");
String[] point2 = point.split(",");
String devStatus = e.getString("Status"); //now, let's process the Status...
String strOwner = e.getString("Owner"); //now, let's process the owner...
//==============================================================================
if (devStatus.equals("fire")) {
IsThereFire=true;
}
} //---End of FOR LOOP---//
}//---end of TRY---//
catch (JSONException e)
{
e.printStackTrace();
}
}
private StringBuilder inputStreamToString(InputStream is)
{
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try
{
while ((rLine = br.readLine()) != null)
{
answer.append(rLine);
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return answer;
}
}
EDIT:
Sir, this is the timer I used..
///---CODE for the TIMER that ticks every second and synch to database to update status---///
Thread t = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
// HERE IS THE ACTUAL CODE WHERE I CALL THE ASYNCDATACLASS2
AsyncDataClass2 performBackgroundTask = new AsyncDataClass2();
// PerformBackgroundTask this class is the class that extends AsynchTask
performBackgroundTask.execute();
}
});
}
} catch (InterruptedException e) {
}
}
};
t.start();
//---------------------------------------------------------------//
if you need to execute a task at fixed interval of time you can use a Timer with a TimerTask. It runs on different thread than the UI thread, meaning that you can run your http call directly in it. You can find the documentation here
I think you should try to use TimerTask or a job scheduler.
Lots of information about job schedulers can be found here and here.
Check this:
Timer timer;
private void startTimer() {
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
new AsyncDataClass2 adc = new AsyncDataClass2("u","p");
adc.execute();
}
}, 0, 1000);
}
Then in onCreate() you write:
startTimer();
Although, you should consider others comments, they're meaningful, requesting updates from web server every second in AsyncTask, it's not so good thing to do.
I do not think that's a really good idea to proceed like this but you can do it, of course with an simple TimerTask (tutorial there)
Basically, it would look like this:
public class MyTimerTask extends TimerTask {
#Override
public void run() {
// Just start your AsyncTask and proceed, I didn't adapt the code to your task
new AsyncDataClass2().execute()
}
}
Your Logic calls it:
TimerTask timerTask = new MyTimerTask();
// They're ms: 1000ms = 1s
timer.scheduleAtFixedRate(timerTask, 0, 1000);
timer.start();
You cancel it when you destroy your Fragment/Activity
timer.cancel();

Convert android AsyncTask call to a separate class and call from all activities

I am new to android development. I have a AsyncTask function in my application. Calling http request from all activities. Now in each activity I am using the following class to connect to server, in some activities I even called twice !!.
Basically I am a web developer and in such cases we use a single class which can be accessed from entire application(web) and use the common function to do the same activity. The only difference is input and out put will be changed.
My doubt is in this case can I use ( convert) this to such a function or class ?
My assume is
Create an android class ( which can be accessed from all the activities )
Just make the JSON string we need with specific server ( for process in server )
Just pass the created json to the created class and then made the http connect )
Process the returned data from server
Pass that to the corresponding activity
So that I can use the same function for all the activities and I can avoid duplicate query
Can I convert this code to such a manner ?
My Code
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
LogIN loginUser = new LogIN();
LoginUser.execute("");
}
private class LogIN extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... sUrl) {
try {
String path = "http://www.domain_name.com/app/checkSession.php";
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpResponse response;
JSONObject json = new JSONObject();
try {
HttpPost post = new HttpPost(path);
json.put("access_token", "123456");
post.setHeader("json", json.toString());
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding((Header) new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
/* Checking response */
if (response != null) {
InputStream in = response.getEntity().getContent();
String a = convertStreamToString(in);
JSONObject jsono = stringToJsonobj(a);
String passedStringValue = jsono.getString("result");
if(passedStringValue.equals("1")){
flags=1;
//Log.v("TAGG", "Success");
}
else {
flags=0;
//Log.v("TAGG", "Failed !");
}
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialogue("Login Processing", "Loading");
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
}
#Override
protected void onPostExecute(String result) {
if(flags.equals(1)){
Itent homepage = new Intent(MainActivity.this, RegisterDevice.class);
startActivity(homepage);
finish();
}
else {
Intent homepage = new Intent(MainActivity.this, LoginActivity.class);
startActivity(homepage);
finish();
}
super.onPostExecute(result);
}
}
}
Please any one help/advise
Thanks in advance
Extract your class to a different file and make it public
public class LogIN extends AsyncTask<Object, Integer, String> {
private ILoginListener listener;
#Override
protected String doInBackground(Object... arg0) {
try {
this.listener = (ILoginListener) arg0[0];
//You can also send the url in the obj array
String theUrl = (String) arg0[1];
String path = "http://www.domain_name.com/app/checkSession.php";
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpResponse response;
JSONObject json = new JSONObject();
try {
HttpPost post = new HttpPost(path);
json.put("access_token", "123456");
post.setHeader("json", json.toString());
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding((Header) new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
/* Checking response */
if (response != null) {
InputStream in = response.getEntity().getContent();
String a = convertStreamToString(in);
JSONObject jsono = stringToJsonobj(a);
String passedStringValue = jsono.getString("result");
if(passedStringValue.equals("1")){
flags=1;
//Log.v("TAGG", "Success");
}
else {
flags=0;
//Log.v("TAGG", "Failed !");
}
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialogue("Login Processing", "Loading");
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
}
#Override
protected void onPostExecute(String result) {
listener.logInSessionCheckListener(flag.equals(1));
super.onPostExecute(result);
}
}
Regarding your other question, I normally have an interface for that, something like this:
public interface ILoginListener {
public void logInSessionCheckListener(SomeNeeded Value);
}
I implement the interface in the class where i need the postExecute result and in the overriden method you can to what you want with the result of your task.
Your class where you user it will look something like this:
public class SomeClass implements ILoginListener {
//Call it like this from any class:
LogIN loginTask = new LogIn();
Object[] someParams = new Object[2];
//add the listener
someParams[0] = SomeClass.this
//add the url
someParams[1] = someUrlString;
loginTask.execute(someParams);
#Override
public void logInSessionCheckListener(SomeNeeded Value){
//do Stuff with your results
}
}
You can do it like make separate class for everything inside doInBackground() method and called it in all activity with passing parameter to
LogIN loginUser = new LogIN(yourparameter);
LoginUser.execute("");
and check parameter in AsyncTask Class constructor like
public LogIN(Myparameter){
// Your data
}
On the other hand you can use this great framework for android : android-query and the async API.
It allows you to perform asynchroneous network tasks from activities and easily work with the results of your requests.
You should use interfaces to implement a callback to your ui activity.
Have a look at this thread, it might be useful:
android asynctask sending callbacks to ui
And your asyntask class should be in a seperate java file with public acces.
And to pass the parametres you simply have to call a new LogIN async Task like this:
new LogIN().execute(urls);
Hope it helped :)
Remember that you can never know when AsyncTask is going to finish. So if you're using this to authenticate users and then perform task X, task Y, or task Z,
then maybe it's better to create a Login helper class
public class LoginHelper {
public boolean login(params){
// Authenticate user and return true if successfull
}
}
and then have in your Activity classes
private class X extends AsyncTask {
#Override
protected String doInBackground(String... sUrl) {
...
boolean authenticated = LoginHelper.login(params...);
if(authenticated == true) {
// Perform task X here...
} else {
// Inform the user that the login failed...
}
}
First of all
You have to pass the context in which you are calling your async task
Sample Code
Login loginTask = new Long(getContext());
loginTask.execute();
You class Login should have a constructor that accepts the Context
Sample Code
public class Login extends AsyncTask<String, Integer, String> {
private Context mContext ;
private ProgressDialog pd;
private Handler handler = new Handler { };
public Login (Context context){
mContext = context ;
}
.....
Then make sure to create the method showDialog inside Login class to show the progress dialog
Note
You can add what ever Constructors you need to customize the behaviour of your Login task
for example : pass boolean parameter to tell that the Login Task is cancelable....
Hope that help you :)

Categories

Resources