working on serial/login/pictogram activity structure

parent 643a50d8
...@@ -36,13 +36,12 @@ import com.yottacode.pictogram.tools.PCBcontext; ...@@ -36,13 +36,12 @@ import com.yottacode.pictogram.tools.PCBcontext;
/** /**
* A login screen that offers login via email/password. * A login screen that offers login via email/password.
*/ */
public class SerialActivity extends Activity implements iRestapiListener { public class SerialActivity extends Activity {
// UI references. // UI references.
private EditText mSerialViewMail; private EditText mSerialViewMail;
private EditText mSerialViewPass; private EditText mSerialViewPass;
Context context;
private static final String TAG_USER = "user"; private static final String TAG_USER = "user";
private static final String TAG_ISSTUDENT = "isStudent"; private static final String TAG_ISSTUDENT = "isStudent";
...@@ -61,44 +60,26 @@ public class SerialActivity extends Activity implements iRestapiListener { ...@@ -61,44 +60,26 @@ public class SerialActivity extends Activity implements iRestapiListener {
// String constant for logs // String constant for logs
private final String LOG_TAG = this.getClass().getSimpleName(); // Or .getCanonicalName() private final String LOG_TAG = this.getClass().getSimpleName(); // Or .getCanonicalName()
private String username = null;
private String password = null;
//A ProgressDialog object //A ProgressDialog object
private ProgressDialog progressDialog; private ProgressDialog progressDialog;
public static final String PREFS_NAME = "MyPrefsFile"; public static final String PREFS_NAME = "MyPrefsFile";
@Override private Intent manageSupervisorLogin(String username, String password, boolean online) {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_serial);
Intent intent=getIntent();
String activityName=intent.getStringExtra("activity_name");
mSerialViewMail = (EditText) findViewById(R.id.serialmail);
mSerialViewPass = (EditText) findViewById(R.id.serialpass);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
username = settings.getString("username", "");
if (activityName.equals("MainActivity")){
password = settings.getString("password", "");
} else{
password = "";
}
// Escribo el último valor indicado de username final Intent loginActivity = new Intent(SerialActivity.this, LoginActivity.class);
mSerialViewMail.setText(username); if (online) {
final String operation = "sup/login";
Hashtable<String, String> postDataParams = new Hashtable<String, String>();
context = this; postDataParams.put("email", username);
postDataParams.put("password", password);
if (!username.equals("") && !password.equals("")){ // Tengo usuario, sigo con este usuario PCBcontext.getRestapiWrapper().ask(operation, postDataParams, "post", new iRestapiListener() {
if (RestapiWrapper.ping(context.getResources().getString(R.string.server),"server/ping", new iRestapiListener() {
@Override @Override
public void preExecute() { public void preExecute() {
progressDialog = ProgressDialog.show(SerialActivity.this, SerialActivity.this.getBaseContext().getString(R.string.userLoadingMsg),
SerialActivity.this.getBaseContext().getString(R.string.userLoadingTxt), false, false);
} }
@Override @Override
...@@ -108,332 +89,204 @@ public class SerialActivity extends Activity implements iRestapiListener { ...@@ -108,332 +89,204 @@ public class SerialActivity extends Activity implements iRestapiListener {
@Override @Override
public void result(JSONObject result) { public void result(JSONObject result) {
if (SerialActivity.this.checkLogin(result)) {
String jsonToken;
JSONObject user;
try {
jsonToken = result.getString(TAG_TOKEN);
user = result.getJSONObject(TAG_USER);
} catch (JSONException e) {
e.printStackTrace();
jsonToken = null;
user = null;
Log.e(LOG_TAG, e.getMessage());
}
Log.d(LOG_TAG, "Es un SUPERVISOR. Sigo...");
Log.d(LOG_TAG, "jsonToken válido:" + jsonToken);
try {
Integer su_id = user.getInt(TAG_ID);
int su_id_int = su_id.intValue();
progressDialog.dismiss();
loginActivity.putExtra("offline", false);
loginActivity.putExtra("sup_id", su_id_int);
loginActivity.putExtra("token", jsonToken);
} catch (JSONException e) {
SerialActivity.this.error(e);
}
}
} }
@Override @Override
public void error(Exception e) { public void error(Exception e) {
SerialActivity.this.error(e); SerialActivity.this.error(e);
} }
})) { });
// Tengo conexión a internet. Modo ONLINE } else{
RestapiWrapper wrapper = PCBcontext.getRestapiWrapper(); loginActivity.putExtra("username", username);
if (username.contains("@")){ loginActivity.putExtra("password", password);
// Es un supervisor }
String operation = "sup/login"; return loginActivity;
Hashtable<String, String> postDataParams = new Hashtable<String, String>(); }
postDataParams.put("email", username);
postDataParams.put("password", password);
/*
postDataParams.put("idFirmware", _ANDROIDID);
postDataParams.put("desc", _MODEL);
postDataParams.put("serial", serial);
*/
wrapper.ask(operation, postDataParams, "post", new iRestapiListener() {
@Override
public void preExecute() {
progressDialog = ProgressDialog.show(SerialActivity.this, SerialActivity.this.getBaseContext().getString(R.string.userLoadingMsg),
SerialActivity.this.getBaseContext().getString(R.string.userLoadingTxt), false, false);
}
@Override private Intent manageStudentLogin(final String username, final String password, boolean online)
public void result(JSONArray result) { {
} final Intent pictogramActivity = new Intent(SerialActivity.this, PictogramActivity.class);
if (online) {
Log.d(LOG_TAG, "Entro con usuario y password");
String operation = "stu/login";
Hashtable<String, String> postDataParams = new Hashtable<String, String>();
@Override postDataParams.put("username", username);
public void result(JSONObject result) { postDataParams.put("password", password);
Log.d(LOG_TAG, "Es un SUPERVISOR. Sigo..."); /*
Log.d(LOG_TAG, "jsonToken válido:" + jsonToken); postDataParams.put("idFirmware", _ANDROIDID);
postDataParams.put("desc", _MODEL);
postDataParams.put("serial", serial);
*/
PCBcontext.getRestapiWrapper().ask(operation, postDataParams, "post", new iRestapiListener() {
@Override
public void preExecute() {
Integer su_id = user.getInt(TAG_ID); }
int su_id_int = su_id.intValue();
//close the progress dialog @Override
if (!username.contains("@") && progressDialog!=null){ public void result(JSONArray result) {
progressDialog.dismiss();
}
}
@Override
public void result(JSONObject result) {
try {
pictogramActivity.putExtra("token", result.getString(TAG_TOKEN));
JSONObject user = result.getJSONObject(TAG_USER);
// Es un estudiante
st_id = user.getInt(TAG_ID);
int st_id_int = st_id.intValue();
String st_name = user.getString(TAG_NAME);
String st_surname = user.getString(TAG_SURNAME);
String st_pic = user.getString(TAG_PIC);
String st_gender = user.getString(TAG_GENDER);
String st_lang = user.getString(TAG_LANG);
String st_attributes = user.getString(TAG_ATTRIBUTES);
// Llamo a LoginActivity
Intent loginActivity = new Intent(SerialActivity.this, LoginActivity.class);
loginActivity.putExtra("offline",false);
loginActivity.putExtra("token", jsonToken);
loginActivity.putExtra("sup_id", su_id_int);
startActivity(loginActivity);
}
@Override User student = new User(st_id_int, username,password, st_name, st_surname, st_pic, st_gender, st_lang, st_attributes,
public void error(Exception e) { User.NO_SUPERVISOR, "", "", "", "", "", "M", "es-es", "");
SerialActivity.this.error(e);
}
});
} else{
// Es un estudiante
Log.d(LOG_TAG, "Entro con usuario y password");
String operation = "stu/login";
Hashtable<String, String> postDataParams = new Hashtable<String, String>();
postDataParams.put("username", username);
postDataParams.put("password", password);
/*
postDataParams.put("idFirmware", _ANDROIDID);
postDataParams.put("desc", _MODEL);
postDataParams.put("serial", serial);
*/
wrapper.ask(operation, postDataParams, "post", (iRestapiListener) context);
}
} else{
// NO Tengo conexión a internet. Modo OFFLINE
if (username.contains("@")) {
// Es un supervisor
// Llamo a LoginActivity y le paso username y password
Intent loginActivity = new Intent(this, LoginActivity.class);
loginActivity.putExtra("offline",true);
loginActivity.putExtra("username",username);
loginActivity.putExtra("password",password);
startActivity(loginActivity);
} else {
// Es un estudiante
try {
Vector<User> localUsers = PCBcontext.getDevice().findUser(username, password);
// set_user, con token nulo y sin listener
PCBcontext.set_user(localUsers.elementAt(0), null, null);
// Llamo a PictogramActivity
/*
if (progressDialog!=null)
progressDialog.dismiss();
*/
Intent pictogramActivity = new Intent(SerialActivity.this, PictogramActivity.class);
startActivity(pictogramActivity);
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); SerialActivity.this.error(e);
} catch (LoginException e) {
AlertDialog.Builder builder = new AlertDialog.Builder(SerialActivity.this);
if (e.knonwn_student()){
// El password no es correcto
builder.setMessage("La contraseña indicada no es correcta. Inténtelo de nuevo.")
.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
} else {
// El usuario no existe
builder.setMessage("El usuario indicado no es correcto. Inténtelo de nuevo.")
.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
}
e.printStackTrace();
} }
} }
}
} else{ // No tengo aún usuario. Espero a que lo indique
Button mEntrarButton = (Button) findViewById(R.id.entrar_button);
mEntrarButton.setOnClickListener(new OnClickListener() {
@Override @Override
public void onClick(View view) { public void error(Exception e) {
String username = mSerialViewMail.getText().toString(); SerialActivity.this.error(e);
String password = mSerialViewPass.getText().toString();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("username", username);
editor.putString("password", password);
editor.commit();
// DE PRUEBA
// Alumno
username = "faf0001";
password = "faf0001";
// Supervisor
//username = "dofer@ujaen.es";
//password = "dofer";
if (RestapiWrapper.ping(context.getResources().getString(R.string.server),"server/ping",null)) {
// Tengo conexión a internet. Modo ONLINE
RestapiWrapper wrapper = PCBcontext.getRestapiWrapper();
if (username.contains("@")){
// Es un supervisor
String operation = "sup/login";
Hashtable<String, String> postDataParams = new Hashtable<String, String>();
postDataParams.put("email", username);
postDataParams.put("password", password);
wrapper.ask(operation, postDataParams, "post", (iRestapiListener) context);
} else{
// Es un estudiante
String operation = "stu/login";
Hashtable<String, String> postDataParams = new Hashtable<String, String>();
postDataParams.put("username", username);
postDataParams.put("password", password);
wrapper.ask(operation, postDataParams, "post", (iRestapiListener) context);
}
} else{
// NO Tengo conexión a internet. Modo OFFLINE
if (username.contains("@")) {
// Es un supervisor
// Llamo a LoginActivity y le paso username y password
Intent loginActivity = new Intent(SerialActivity.this, LoginActivity.class);
loginActivity.putExtra("offline",true);
loginActivity.putExtra("username",username);
loginActivity.putExtra("password",password);
startActivity(loginActivity);
} else {
// Es un estudiante
try {
Vector<User> localUsers = PCBcontext.getDevice().findUser(username, password);
// set_user, con token nulo y sin listener
PCBcontext.set_user(localUsers.elementAt(0), null, null);
// Llamo a PictogramActivity
Intent pictogramActivity = new Intent(SerialActivity.this, PictogramActivity.class);
startActivity(pictogramActivity);
} catch (JSONException e) {
e.printStackTrace();
} catch (LoginException e) {
AlertDialog.Builder builder = new AlertDialog.Builder(SerialActivity.this);
if (e.knonwn_student()){
// El password no es correcto
builder.setMessage("La contraseña indicada no es correcta. Inténtelo de nuevo.")
.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
} else {
// El usuario no existe
builder.setMessage("El usuario indicado no es correcto. Inténtelo de nuevo.")
.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
}
AlertDialog alert = builder.create();
alert.show();
e.printStackTrace();
}
}
}
} }
}); });
} }
} else {
try {
public boolean checkLogin(JSONObject result) { Vector<User> localUsers = PCBcontext.getDevice().findUser(username, password);
// Si llego aquí es porque hay un único valor, no un array PCBcontext.set_user(localUsers.elementAt(0), null, null);
try {
Log.d(LOG_TAG, "JSON en result:"+result.toString()); } catch (JSONException e) {
e.printStackTrace();
if (result.toString().contains("error")){ } catch (LoginException e) {
if (progressDialog!=null) progressDialog.dismiss();
AlertDialog.Builder builder = new AlertDialog.Builder(SerialActivity.this); AlertDialog.Builder builder = new AlertDialog.Builder(SerialActivity.this);
if (e.knonwn_student()){
if (result.toString().contains("Invalid password")){ // El password no es correcto
builder.setMessage("La contraseña indicada no es correcta. Inténtelo de nuevo.") builder.setMessage(getString(R.string.passErrorMsg))
.setCancelable(false) .setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() { .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) { public void onClick(DialogInterface dialog, int id) {
} }
}); });
} else if (result.toString().contains("User not found")){ } else {
builder.setMessage("El usuario indicado no es correcto. Inténtelo de nuevo.") // El usuario no existe
builder.setMessage(getString(R.string.userErrorMsg))
.setCancelable(false) .setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() { .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) { public void onClick(DialogInterface dialog, int id) {
} }
}); });
} }
e.printStackTrace();
}
}
return pictogramActivity;
}
AlertDialog alert = builder.create(); protected void login(String username, String password) {
alert.show(); boolean online=RestapiWrapper.ping(this.getResources().getString(R.string.server),"server/ping", new iRestapiListener() {
@Override
public void preExecute() {
} else{ // No hay error. Sigo }
// Saco el token y los demás valores
Vector<User> users = new Vector<User>(1);
String jsonToken = result.getString(TAG_TOKEN); @Override
JSONObject user = result.getJSONObject(TAG_USER); public void result(JSONArray result) {
try{
Boolean is_student = user.has(TAG_ISSTUDENT);
if (is_student) { }
// Es un estudiante
st_id = user.getInt(TAG_ID);
int st_id_int = st_id.intValue();
String st_name = user.getString(TAG_NAME);
String st_surname = user.getString(TAG_SURNAME);
String st_pic = user.getString(TAG_PIC);
String st_gender = user.getString(TAG_GENDER);
String st_lang = user.getString(TAG_LANG);
String st_attributes = user.getString(TAG_ATTRIBUTES);
//users=PCBcontext.getDevice().getUsers();
//if (users.contains(user)) users.remove(user); @Override
public void result(JSONObject result) {
User student = new User(st_id_int, "nickname_stu","pwd_stu", st_name, st_surname, st_pic, st_gender, st_lang, st_attributes, }
-1, username, password, "", "", "", "M", "es-es", "");
users.add(student);
Log.d(LOG_TAG, "jsonToken válido:" + jsonToken); @Override
public void error(Exception e) {
SerialActivity.this.error(e);
}
});
//User student = PCBcontext.getDevice().findUser(st_id_int, -1); Intent nextActivity=username.contains("@")
//Log.d(LOG_TAG, "student id:" + student.get_id_stu()); ? manageSupervisorLogin(username,password,online)
PCBcontext.set_user(student, jsonToken, new iImgDownloaderListener() { : manageStudentLogin(username,password,online);
@Override nextActivity.putExtra("offline",!online);
public void loadComplete() { startActivity(nextActivity);
if (progressDialog!=null)
progressDialog.dismiss();
Intent pictogramActivity = new Intent(SerialActivity.this, PictogramActivity.class);
startActivity(pictogramActivity);
}
@Override }
public void loadImg(Img image) {
}
});
PCBcontext.getDevice().synchronizeUsers(users, new iImgDownloaderListener() { public boolean checkLogin(JSONObject result) {
@Override
public void loadComplete() {
} Log.d(LOG_TAG, "JSON en result:" + result.toString());
@Override if (result.toString().contains("error")) {
public void loadImg(Img image) { if (progressDialog != null) progressDialog.dismiss();
Log.d(LOG_TAG, "Load a single image with ID: " + image.get_id());
setContentView(R.layout.activity_serial);
}
});
} else{ AlertDialog.Builder builder = new AlertDialog.Builder(SerialActivity.this);
// Es un Supervisor
} if (result.toString().contains("Invalid password")) {
} catch (JSONException ex){ builder.setMessage(this.getString(R.string.passErrorMsg))
//Log.d(LOG_TAG, "ERROR 1"); .setCancelable(false)
ex.printStackTrace(); .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
} else if (result.toString().contains("User not found")) {
builder.setMessage(this.getString(R.string.userErrorMsg))
.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
} }
AlertDialog alert = builder.create();
alert.show();
result = null;
} }
} catch (JSONException e) { return result==null;
//Log.d(LOG_TAG, "ERROR 2");
e.printStackTrace();
}
} }
@Override
public void error(Exception e) { public void error(Exception e) {
Log.e(this.getClass().getName(), " Server restapi error: " + e.getLocalizedMessage()); Log.e(this.getClass().getName(), " Server restapi error: " + e.getLocalizedMessage());
AlertDialog.Builder builder = new AlertDialog.Builder(SerialActivity.this); AlertDialog.Builder builder = new AlertDialog.Builder(SerialActivity.this);
...@@ -448,4 +301,47 @@ public class SerialActivity extends Activity implements iRestapiListener { ...@@ -448,4 +301,47 @@ public class SerialActivity extends Activity implements iRestapiListener {
AlertDialog alert = builder.create(); AlertDialog alert = builder.create();
alert.show(); alert.show();
} }
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_serial);
Intent intent=getIntent();
String activityName=intent.getStringExtra("activity_name");
mSerialViewMail = (EditText) findViewById(R.id.serialmail);
mSerialViewPass = (EditText) findViewById(R.id.serialpass);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String username = settings.getString("username", "");
String password = activityName.equals("MainActivity") ? settings.getString("password", "") : "";
// Escribo el último valor indicado de username
mSerialViewMail.setText(username);
if (username.equals("")) { // No tengo aún usuario. Espero a que lo indique
Button mEntrarButton = (Button) findViewById(R.id.entrar_button);
mEntrarButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
String username = mSerialViewMail.getText().toString();
String password = mSerialViewPass.getText().toString();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("username", username);
editor.putString("password", password);
editor.commit();
SerialActivity.this.login(username, password);
}
});
} else
login(username, password);
}
} }
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment