Commit 6501912a authored by Eryk Leniart's avatar Eryk Leniart

Login feature (only logic)

parent 463f9aeb
...@@ -71,8 +71,11 @@ ...@@ -71,8 +71,11 @@
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex-cache" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex-cache" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/cn.pedant.sweetalert/library/1.3/jars" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/com.android.support/appcompat-v7/23.1.1/jars" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/com.android.support/appcompat-v7/23.1.1/jars" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/com.android.support/support-v4/23.1.1/jars" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/com.android.support/support-v4/23.1.1/jars" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/com.github.medyo/fancybuttons/1.5/jars" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/com.pnikosis/materialish-progress/1.0/jars" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/jacoco" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/jacoco" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaResources" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaResources" />
...@@ -86,11 +89,17 @@ ...@@ -86,11 +89,17 @@
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />
<excludeFolder url="file://$MODULE_DIR$/build/outputs" /> <excludeFolder url="file://$MODULE_DIR$/build/outputs" />
<excludeFolder url="file://$MODULE_DIR$/build/tmp" />
</content> </content>
<orderEntry type="jdk" jdkName="Android API 23 Platform" jdkType="Android SDK" /> <orderEntry type="jdk" jdkName="Android API 23 Platform" jdkType="Android SDK" />
<orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" exported="" name="library-1.3" level="project" />
<orderEntry type="library" exported="" name="support-v4-23.1.1" level="project" /> <orderEntry type="library" exported="" name="support-v4-23.1.1" level="project" />
<orderEntry type="library" exported="" name="fancybuttons-1.5" level="project" />
<orderEntry type="library" exported="" name="httpclient-4.3.6" level="project" />
<orderEntry type="library" exported="" name="support-annotations-23.1.1" level="project" /> <orderEntry type="library" exported="" name="support-annotations-23.1.1" level="project" />
<orderEntry type="library" exported="" name="appcompat-v7-23.1.1" level="project" /> <orderEntry type="library" exported="" name="appcompat-v7-23.1.1" level="project" />
<orderEntry type="library" exported="" name="android-async-http-1.4.9" level="project" />
<orderEntry type="library" exported="" name="materialish-progress-1.0" level="project" />
</component> </component>
</module> </module>
\ No newline at end of file
...@@ -22,4 +22,7 @@ android { ...@@ -22,4 +22,7 @@ android {
dependencies { dependencies {
compile fileTree(dir: 'libs', include: ['*.jar']) compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.1.1' compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.loopj.android:android-async-http:1.4.9'
compile 'cn.pedant.sweetalert:library:1.3'
compile 'com.github.medyo:fancybuttons:1.5@aar'
} }
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" <manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="anotherlineofcode.com.jointhecityapp" > package="anotherlineofcode.com.jointhecityapp" >
<uses-permission android:name="android.permission.INTERNET" />
<application <application
android:allowBackup="true" android:allowBackup="true"
android:icon="@mipmap/ic_launcher" android:icon="@mipmap/ic_launcher"
android:label="@string/app_name" android:label="@string/app_name"
android:theme="@style/AppTheme" > android:theme="@style/AppTheme"
tools:replace="android:icon" >
<activity <activity
android:name=".MainActivity" android:name=".MainActivity"
android:label="@string/app_name" > android:label="@string/app_name"
android:screenOrientation="portrait" >
<intent-filter> <intent-filter>
<action android:name="android.intent.action.MAIN" /> <action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter> </intent-filter>
</activity> </activity>
<activity
android:name=".LoginAndRegistrationActivity"
android:label="@string/title_activity_login_and_registration" >
</activity>
</application> </application>
</manifest> </manifest>
package anotherlineofcode.com.jointhecityapp;
import org.json.JSONObject;
public class JSONParser {
public static JSONObject parseObject(byte[] response) {
JSONObject jsonObj = null;
try {
String json = new String(response, "UTF-8");
jsonObj = new JSONObject(json);
} catch (Exception e) {
e.printStackTrace();
}
return jsonObj;
}
}
package anotherlineofcode.com.jointhecityapp;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.json.JSONException;
import org.json.JSONObject;
import cn.pedant.SweetAlert.SweetAlertDialog;
import cz.msebera.android.httpclient.Header;
public class LoginAndRegistrationActivity extends AppCompatActivity {
private AsyncHttpClient client;
private SharedPreferences sharedPreferences;
private Button mLoginButton;
private EditText mUsername, mPassword;
private View focusView;
private Context context = this;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_and_registration);
sharedPreferences = getSharedPreferences("JoinTheCityPreferences", Context.MODE_PRIVATE);
mLoginButton = (Button) findViewById(R.id.login_button);
mUsername = (EditText) findViewById(R.id.username);
mPassword = (EditText) findViewById(R.id.password);
mPassword.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == R.id.password_ime || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
mLoginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
attemptLogin();
}
});
}
private void attemptLogin(){
if (client != null) {
return;
}
// Reset errors.
mUsername.setError(null);
mPassword.setError(null);
// Store values at the time of the login attempt.
String username = mUsername.getText().toString();
String password = mPassword.getText().toString();
boolean cancel = false;
focusView = null;
// Check for a valid password, if the user entered one.
if (TextUtils.isEmpty(password)) {
mPassword.setError(getString(R.string.error_field_required));
focusView = mPassword;
cancel = true;
}
// Check for a valid email address.
if (TextUtils.isEmpty(username)) {
mUsername.setError(getString(R.string.error_field_required));
focusView = mUsername;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
loginUser(username, password);
}
}
private void loginUser(final String username, final String password){
client = new AsyncHttpClient();
// Put request params
RequestParams params = new RequestParams();
params.put("username", username);
params.put("password", password);
// Display progress bar
final SweetAlertDialog pDialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE);
pDialog.getProgressHelper().setBarColor(Color.parseColor("#9FC967"));
pDialog.setTitleText("Logowanie...");
pDialog.setCancelable(false);
pDialog.show();
// Make post request with username/password credentials in order to obtain access token
client.post(getString(R.string.api_url) + "api-token-auth/", params, new AsyncHttpResponseHandler(){
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
client = null;
pDialog.dismiss();
// Retrieve server response
JSONObject jsonResponse = JSONParser.parseObject(responseBody);
try {
String token = jsonResponse.getString("token");
// Store received variables to shared preferences
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("token", token);
editor.commit();
} catch (JSONException e) {
e.printStackTrace();
}
// Display success dialog
SweetAlertDialog sDialog = new SweetAlertDialog(context, SweetAlertDialog.SUCCESS_TYPE)
.setTitleText("Logowanie pomyślne!")
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sDialog) {
sDialog.dismissWithAnimation();
// Finish activity with RESULT_OK status code
setResult(Activity.RESULT_OK);
finish();
}
});
sDialog.setCancelable(false);
sDialog.show();
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
client = null;
pDialog.dismiss();
// Display error dialog
new SweetAlertDialog(context, SweetAlertDialog.ERROR_TYPE)
.setTitleText("Błąd logowania")
.setContentText(getString(R.string.error_wrong_credentials))
.show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_login_and_registration, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
package anotherlineofcode.com.jointhecityapp; package anotherlineofcode.com.jointhecityapp;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity; import android.support.v7.app.AppCompatActivity;
import android.os.Bundle; import android.os.Bundle;
import android.view.Menu; import android.view.Menu;
...@@ -7,10 +10,34 @@ import android.view.MenuItem; ...@@ -7,10 +10,34 @@ import android.view.MenuItem;
public class MainActivity extends AppCompatActivity { public class MainActivity extends AppCompatActivity {
public final static int LOGIN_REQUEST = 1;
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); setContentView(R.layout.activity_main);
// Check if user is logged in, if not open login activity
if (!isLoggedIn()) {
Intent intent = new Intent(this, LoginAndRegistrationActivity.class);
startActivityForResult(intent, LOGIN_REQUEST);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == LOGIN_REQUEST){
if (resultCode != RESULT_OK) {
// Finish activity when user did not sign in/up
finish();
}
}
}
private boolean isLoggedIn() {
SharedPreferences sharedPreferences = getSharedPreferences("JoinTheCityPreferences", Context.MODE_PRIVATE);
return !sharedPreferences.getString("token", "").isEmpty();
} }
@Override @Override
......
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="anotherlineofcode.com.jointhecityapp.LoginAndRegistrationActivity">
<EditText android:id="@+id/username"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:gravity="center"
android:hint="Nazwa użytkownika"
android:maxLines="1"
android:singleLine="true"/>
<EditText android:id="@+id/password"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:gravity="center"
android:hint="Hasło"
android:imeActionId="@+id/password_ime"
android:imeActionLabel="@string/action_sign_in"
android:imeOptions="actionUnspecified"
android:maxLines="1"
android:singleLine="true"
android:layout_marginTop="30dp"/>
<Button android:id="@+id/login_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Zaloguj"
android:gravity="center"
android:layout_marginTop="200dp"/>
</LinearLayout>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="anotherlineofcode.com.jointhecityapp.LoginAndRegistrationActivity">
<item android:id="@+id/action_settings" android:title="@string/action_settings"
android:orderInCategory="100" app:showAsAction="never" />
</menu>
<resources> <resources>
<string name="app_name">JoinTheCityAPP</string> <string name="app_name">JoinTheCity</string>
<string name="hello_world">Hello world!</string> <string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string> <string name="action_settings">Settings</string>
<string name="title_activity_login_and_registration">Sign in/up</string>
<string name="error_field_required">To pole jest wymagane!</string>
<string name="error_wrong_credentials">Podane dane są nieprawidłowe!</string>
<string name="api_url">http://jointhecity.telemabk.pl/</string>
<string name="action_sign_in">Zaloguj się</string>
</resources> </resources>
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 to comment