You are on page 1of 7

package br.com.crafti.

helpti;
import
import
import
import
import
import
import
import
import
import
import
import
import

android.app.Activity;
android.app.ProgressDialog;
android.content.Context;
android.content.Intent;
android.content.SharedPreferences;
android.os.AsyncTask;
android.os.Bundle;
android.os.Handler;
android.util.Log;
android.view.View;
android.widget.Button;
android.widget.EditText;
android.widget.Toast;

import
import
import
import
import
import
import

com.android.volley.Request.Method;
com.android.volley.Response;
com.android.volley.VolleyError;
com.android.volley.toolbox.StringRequest;
com.google.android.gms.common.ConnectionResult;
com.google.android.gms.common.GooglePlayServicesUtil;
com.google.android.gms.gcm.GoogleCloudMessaging;

import org.json.JSONException;
import org.json.JSONObject;
import
import
import
import
import
import
import
import
import

java.io.IOException;
java.io.OutputStream;
java.net.HttpURLConnection;
java.net.MalformedURLException;
java.net.ProtocolException;
java.net.URL;
java.util.HashMap;
java.util.Iterator;
java.util.Map;

import
import
import
import

br.com.crafti.helpti.config.AppConfig;
br.com.crafti.helpti.config.SessionManager;
br.com.crafti.helpti.controller.AppController;
br.com.crafti.helpti.dao.SQLiteHandler;

public class RegisterActivity extends Activity {


private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnRegister;
private Button btnLinkToLogin;
private EditText inputFullName;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
private String name;
private String email;
private String password;
//-- GCM
// Resgistration Id from GCM
private static final String PREF_GCM_REG_ID = "PREF_GCM_REG_ID";
private SharedPreferences prefs;

// Your project number and web server url. Please change below.
private static final String GCM_SENDER_ID = "533478508797";
private static final String WEB_SERVER_URL = "YOUR_WER_SERVER_URL";
GoogleCloudMessaging gcm;
Button registerBtn;
//TextView regIdView;
private static final int ACTION_PLAY_SERVICES_DIALOG = 100;
protected static final int MSG_REGISTER_WITH_GCM = 101;
protected static final int MSG_REGISTER_WEB_SERVER = 102;
protected static final int MSG_REGISTER_WEB_SERVER_SUCCESS = 103;
protected static final int MSG_REGISTER_WEB_SERVER_FAILURE = 104;
private String gcmRegId;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
inputFullName = (EditText) findViewById(R.id.name);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// Session manager
session = new SessionManager(getApplicationContext());
// SQLite database handler
db = new SQLiteHandler(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(RegisterActivity.this,
MainActivity.class);
startActivity(intent);
finish();
}
// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
name = inputFullName.getText().toString().trim();
email = inputEmail.getText().toString().trim();
password = inputPassword.getText().toString().trim();
if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty())
{
if (isGoogelPlayInstalled()) {
gcm = GoogleCloudMessaging.getInstance(getApplicationCon
text());
// Read saved registration id from shared preferences.
gcmRegId = getSharedPreferences().getString(PREF_GCM_REG

_ID, "");
//if (TextUtils.isEmpty(gcmRegId)) {
handler.sendEmptyMessage(MSG_REGISTER_WITH_GCM);
//}
}
//registerUser(name, email, password);
} else {
Toast.makeText(getApplicationContext(),
"Por favor, entre com suas informaes!", Toast.LENGTH_L
ONG)
.show();
}
}
});
// Link to Login Screen
btnLinkToLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
LoginActivity.class);
startActivity(i);
finish();
}
});
//regIdView = (TextView) findViewById(R.id.regId);
}
/**
* Function to store user in MySQL database will post params(tag, name,
* email, password) to register url
* */
private void registerUser(final String name, final String email,
final String password) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Registrando ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
// User successfully stored in MySQL
// Now store the user in sqlite
String uid = jObj.getString("uid");

JSONObject user = jObj.getJSONObject("user");


String name = user.getString("name");
String email = user.getString("email");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
Toast.makeText(getApplicationContext(), "Usurio registrad
o com sucesso. Tente logar agora!", Toast.LENGTH_LONG).show();
// Launch login activity
Intent intent = new Intent(
RegisterActivity.this,
LoginActivity.class);
startActivity(intent);
finish();
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Erro ao registrar: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
@Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("name", name);
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {

if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
//-- GCM
private boolean isGoogelPlayInstalled() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
ACTION_PLAY_SERVICES_DIALOG).show();
} else {
Toast.makeText(getApplicationContext(),
"Google Play Service is not installed",
Toast.LENGTH_SHORT).show();
finish();
}
return false;
}
return true;
}
private SharedPreferences getSharedPreferences() {
if (prefs == null) {
prefs = getApplicationContext().getSharedPreferences(
"HelpTI", Context.MODE_PRIVATE);
}
return prefs;
}
public void saveInSharedPref(String result) {
// TODO Auto-generated method stub
SharedPreferences.Editor editor = getSharedPreferences().edit();
editor.putString(PREF_GCM_REG_ID, result);
editor.commit();
}
Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case MSG_REGISTER_WITH_GCM:
new GCMRegistrationTask().execute();
break;
case MSG_REGISTER_WEB_SERVER:
new WebServerRegistrationTask().execute();
break;
case MSG_REGISTER_WEB_SERVER_SUCCESS:
Toast.makeText(getApplicationContext(), "Usurio registrado co
m sucesso. Tente logar agora!", Toast.LENGTH_LONG).show();
// Launch login activity
Intent intent = new Intent(
RegisterActivity.this,

LoginActivity.class);
startActivity(intent);
finish();
break;
case MSG_REGISTER_WEB_SERVER_FAILURE:
Toast.makeText(getApplicationContext(),
"Erro ao registrar usurio, favor, tentar novamente!",
Toast.LENGTH_LONG).show();
break;
}
};
};
private class GCMRegistrationTask extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
if (gcm == null && isGoogelPlayInstalled()) {
gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
}
try {
gcmRegId = gcm.register(GCM_SENDER_ID);
} catch (IOException e) {
e.printStackTrace();
}
return gcmRegId;
}
@Override
protected void onPostExecute(String result) {
if (result != null) {
saveInSharedPref(result);
handler.sendEmptyMessage(MSG_REGISTER_WEB_SERVER);
}
}
}
private class WebServerRegistrationTask extends AsyncTask<Void, Void, Void>
{
@Override
protected Void doInBackground(Void... params) {
URL url = null;
try {
url = new URL(AppConfig.GCM_REGISTER);
} catch (MalformedURLException e) {
e.printStackTrace();
handler.sendEmptyMessage(MSG_REGISTER_WEB_SERVER_FAILURE);
}
Map<String, String> dataMap = new HashMap<String, String>();
dataMap.put("regId", gcmRegId);
dataMap.put("name", name);
dataMap.put("email", email);
dataMap.put("password", password);
StringBuilder postBody = new StringBuilder();
Iterator iterator = dataMap.entrySet().iterator();

while (iterator.hasNext()) {
Map.Entry param = (Map.Entry) iterator.next();
postBody.append(param.getKey()).append('=')
.append(param.getValue());
if (iterator.hasNext()) {
postBody.append('&');
}
}
String body = postBody.toString();
byte[] bytes = body.getBytes();
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
OutputStream out = conn.getOutputStream();
out.write(bytes);
out.close();
int status = conn.getResponseCode();
if (status == 200) {
// Request success
handler.sendEmptyMessage(MSG_REGISTER_WEB_SERVER_SUCCESS);
} else {
throw new IOException("Request failed with error code "
+ status);
}
} catch (ProtocolException pe) {
pe.printStackTrace();
handler.sendEmptyMessage(MSG_REGISTER_WEB_SERVER_FAILURE);
} catch (IOException io) {
io.printStackTrace();
handler.sendEmptyMessage(MSG_REGISTER_WEB_SERVER_FAILURE);
} finally {
if (conn != null) {
conn.disconnect();
}
}
return null;
}
}
}

You might also like