Advertisement
rystian

asynchttp-usage

Oct 11th, 2016
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 6.84 KB | None | 0 0
  1. package com.stephel.sadix.main;
  2.  
  3. import java.io.UnsupportedEncodingException;
  4. import java.net.URISyntaxException;
  5. import java.text.SimpleDateFormat;
  6. import java.util.Date;
  7.  
  8. import org.json.JSONException;
  9. import org.json.JSONObject;
  10.  
  11. import android.annotation.SuppressLint;
  12. import android.content.Context;
  13. import android.content.DialogInterface;
  14. import android.content.Intent;
  15. import android.content.pm.PackageManager.NameNotFoundException;
  16. import android.graphics.drawable.Drawable;
  17. import android.os.Bundle;
  18. import android.support.v4.app.FragmentActivity;
  19. import android.util.Log;
  20. import android.view.View;
  21. import android.view.View.OnClickListener;
  22. import android.widget.EditText;
  23. import android.widget.ImageButton;
  24. import android.widget.TextView;
  25. import android.widget.Toast;
  26.  
  27. import com.stephel.sadix.R;
  28. import com.stephel.sadix.constants.ActivityType;
  29. import com.stephel.sadix.constants.AppSettings;
  30. import com.stephel.sadix.constants.Url;
  31. import com.stephel.sadix.dao.LogActivity;
  32. import com.stephel.sadix.dao.LogActivityDao;
  33. import com.stephel.sadix.main.dialogs.AlertDialogFragment;
  34. import com.stephel.sadix.utils.AsyncHttpRequest;
  35. import com.stephel.sadix.utils.AsyncTaskCompleteListener;
  36.  
  37. public class LoginActivity extends FragmentActivity implements AsyncTaskCompleteListener<String>, DialogInterface.OnClickListener {
  38.     private EditText txtPassword;
  39.     private EditText txtUserName;
  40.     private TextView txtVersion;
  41.     private ImageButton btnLogin;
  42.     private Drawable loginBtnClicked;
  43.    
  44.     private Context context;
  45.     private App app;
  46.     private static final String logTag = LoginActivity.class.toString();
  47.    
  48.     @Override
  49.     protected void onCreate(Bundle savedInstanceState) {
  50.         //initialize components
  51.         super.onCreate(savedInstanceState);
  52.         setContentView(R.layout.activity_login);
  53.         context = this;
  54.         txtVersion = ((TextView) findViewById(R.id.txtVersion));
  55.         txtUserName = ((EditText) findViewById(R.id.txtUserName));
  56.         txtPassword = ((EditText) findViewById(R.id.txtPassword));
  57.         //set-up view      
  58.         String version = "0";
  59.         try {
  60.             version = context.getPackageManager().getPackageInfo(
  61.                     context.getPackageName(), 0).versionName;
  62.             txtVersion.setText(version);
  63.         } catch (NameNotFoundException e) {
  64.             e.printStackTrace();
  65.         }
  66.         loginBtnClicked = context.getResources().getDrawable(R.drawable.login_btn_clicked);
  67.         btnLogin = ((ImageButton) findViewById(R.id.btnLogin));
  68.         initListener();
  69.     }
  70.    
  71.     @Override
  72.     public void onResume(){
  73.         super.onResume();
  74.         //TODO check if the device time synched with the server
  75.         //TODO after sync, check if he's logged in
  76.         initSession();
  77.     }
  78.    
  79.     private void initSession() {
  80.         app = (App)getApplicationContext();    
  81.         if(app.getSession().isLoggedIn()){
  82.             launchMainActivity();
  83.         }
  84.     }
  85.    
  86.     private void launchMainActivity(){
  87.         Intent mainMenuIntent = new Intent(this.getApplicationContext(),
  88.             HomeActivity.class);
  89.         startActivity(mainMenuIntent);
  90.     }
  91.  
  92.     private void initListener(){
  93.         btnLogin.setOnClickListener(new OnClickListener() {
  94.             @Override
  95.             public void onClick(View v) {
  96.                 btnLogin.setBackgroundDrawable(loginBtnClicked);
  97.                 CharSequence userName = txtUserName.getText();
  98.                 CharSequence password = txtPassword.getText();
  99.                 //TODO use GSON and dto packages!
  100.                 JSONObject jsonLogin = new JSONObject();
  101.                
  102.                 try {
  103.                     jsonLogin.put("UserName", userName);
  104.                     jsonLogin.put("Password", password);
  105.                     jsonLogin.put("SC", AppSettings.SILENT_CODE);
  106.                     jsonLogin.put("AppVersion", AppSettings.APP_VERSION);
  107.                     String request = jsonLogin.toString();
  108.                     AsyncHttpRequest req = new AsyncHttpRequest(context,LoginActivity.this,AsyncHttpRequest.PostMethod,Url.API_POST_LOGIN,request);
  109.                     req.ContentTypeHeader = AsyncHttpRequest.ContentTypeJSON;
  110.                     req.AcceptHeader=AsyncHttpRequest.ContentTypeJSON;
  111.                     //TODO make execute compatible with HONEYCOMB above to maintain concurrent call to API
  112.                     req.execute();
  113.                 } catch (JSONException je) {
  114.                     Log.e(logTag,"Error Creating Json : "+je.getMessage());
  115.                 } catch (URISyntaxException e) {
  116.                     Log.e(logTag,"Invalid URI : "+e.getMessage());
  117.                 } catch (UnsupportedEncodingException e) {
  118.                     Log.e(logTag,"Encoding unsupported : "+e.getMessage());
  119.                 }
  120.             }
  121.         });
  122.     }
  123.    
  124.     @SuppressLint("SimpleDateFormat")
  125.     @Override
  126.     public void onTaskComplete(String result, int Tag) {
  127.         try {
  128.             if(result!=null){
  129.                 JSONObject json= new JSONObject(result);
  130.                 JSONObject jsonSadixException = json.getJSONObject("SadixException");
  131.                 String sdxResult = jsonSadixException.getString("Result");
  132.                
  133.                 if(sdxResult.equals("OK")) {
  134.                     JSONObject jsonSales = json.getJSONObject("Sales");
  135.                     String salesFullName = jsonSales.get("FullName").toString();
  136.                     int salesId = jsonSales.getInt("SalesId");
  137.                     String serverDateTime = jsonSales.getString("ServerDateTime");
  138.                     Log.i(logTag,"Successfully Logging in! Sales Name : "+salesFullName);
  139.                    
  140.                     Date date = new Date();
  141.                     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
  142.                     String currentDateandTime = sdf.format(date);
  143.                     app.getSession().setLoggedIn(true, currentDateandTime, String.valueOf(salesId),
  144.                             salesFullName,serverDateTime);
  145.                    
  146.                     //check if date of device is synched with server to HH level (hence 13 chars taken into account
  147.                     //date part (10 chars) + 'T' (1) + hour part (2))
  148.                     if(!currentDateandTime.substring(0, 13).equals(serverDateTime.substring(0,13))){
  149.                         AlertDialogFragment syncDialog = AlertDialogFragment.getInstance(
  150.                                 getString(R.string.dialog_title_sync_server_datetime),
  151.                                 getString(R.string.dialog_message_sync_server_datetime)+serverDateTime
  152.                                 );
  153.                         syncDialog.show(this.getSupportFragmentManager(),"sync_confirm");
  154.                     } else {
  155.                         //log to database
  156.                         LogActivityDao activityDao = app.getDaoSession().getLogActivityDao();
  157.                         LogActivity activity = new LogActivity(null,ActivityType.LOGIN,"",date);
  158.                         activityDao.insert(activity);
  159.                         Log.d(logTag,"Login activity logged : "+activity.getId());
  160.                         //go to main menu
  161.                         launchMainActivity();
  162.                     }
  163.                    
  164.                 } else {
  165.                     String sdxResultMsg = jsonSadixException.getString("Message");
  166.                     Log.w(logTag,"failed Logging in! "+sdxResultMsg);                  
  167.                     Toast.makeText(this, "Login Failed : " + sdxResult, Toast.LENGTH_LONG).show();
  168.                 }
  169.             }
  170.         } catch (JSONException e) {
  171.             Log.e(logTag,"Failed logging in : "+e.getMessage());
  172.         }
  173.        
  174.     }
  175.    
  176.     //Handle sync time server dialog
  177.     @Override
  178.     public void onClick(DialogInterface dialog, int whichButton) {
  179.         switch (whichButton){
  180.         case    DialogInterface.BUTTON_POSITIVE:
  181.             dialog.dismiss();
  182.             try {
  183.                 startActivity(new Intent(
  184.                         android.provider.Settings.ACTION_DATE_SETTINGS));
  185.             } catch (Exception e) {
  186.                 e.printStackTrace();
  187.             }
  188.             break;
  189.         case DialogInterface.BUTTON_NEGATIVE:
  190.             dialog.dismiss();
  191.             break;
  192.         }
  193.        
  194.     }
  195.  
  196. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement