Browse Source

Added shared preferences, main activity -> launcher & main, login activity called when needed, logout tweaks

pull/24/head
Apostolos Fanakis 8 years ago
parent
commit
82c0605b95
  1. 9
      app/build.gradle
  2. 7
      app/src/main/AndroidManifest.xml
  3. 7
      app/src/main/java/gr/thmmy/mthmmy/activities/BaseActivity.java
  4. 43
      app/src/main/java/gr/thmmy/mthmmy/activities/LoginActivity.java
  5. 80
      app/src/main/java/gr/thmmy/mthmmy/activities/MainActivity.java
  6. 91
      app/src/main/java/gr/thmmy/mthmmy/utils/Thmmy.java
  7. 8
      app/src/main/res/drawable/page_first.xml
  8. 8
      app/src/main/res/drawable/page_last.xml
  9. 8
      app/src/main/res/drawable/page_next.xml
  10. 8
      app/src/main/res/drawable/page_previous.xml

9
app/build.gradle

@ -21,9 +21,10 @@ android {
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:25.0.1'
compile 'com.android.support:design:25.0.1'
compile 'com.squareup.okhttp3:okhttp:3.4.1'
compile 'com.android.support:appcompat-v7:25.0.0'
compile 'com.android.support:design:25.0.0'
compile 'com.squareup.okhttp3:okhttp:3.4.0'
compile 'com.jakewharton:butterknife:7.0.1'
compile 'org.jsoup:jsoup:1.10.1'
compile 'com.android.support:support-v4:25.0.1'
compile 'com.android.support:cardview-v7:25.0.1'
@ -33,6 +34,4 @@ dependencies {
compile('com.mikepenz:materialdrawer:5.7.0@aar') {
transitive = true
}
}

7
app/src/main/AndroidManifest.xml

@ -12,9 +12,11 @@
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".activities.LoginActivity"
android:name=".activities.MainActivity"
android:configChanges="orientation|screenSize"
android:label="@string/app_name"
android:launchMode="singleTop"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
@ -23,9 +25,8 @@
</intent-filter>
</activity>
<activity
android:name=".activities.MainActivity"
android:name=".activities.LoginActivity"
android:configChanges="orientation|screenSize"
android:label="@string/app_name"
android:launchMode="singleTop"
android:theme="@style/AppTheme.NoActionBar">
</activity>

7
app/src/main/java/gr/thmmy/mthmmy/activities/BaseActivity.java

@ -1,5 +1,6 @@
package gr.thmmy.mthmmy.activities;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
@ -19,6 +20,12 @@ public class BaseActivity extends AppCompatActivity {
protected static Thmmy.LoginData loginData;
private static boolean init =false; //To initialize stuff only once per app start
//Shared preferences
public static final String SHARED_PREFS_NAME = "thmmySharedPrefs";
public static final String USER_NAME = "userNameKey";
public static final String GUEST_PREF_USERNAME = "GUEST";
public static final String IS_LOGGED_IN = "isLogedIn";
public static CookieJar getCookieJar()
{
return cookieJar;

43
app/src/main/java/gr/thmmy/mthmmy/activities/LoginActivity.java

@ -2,6 +2,7 @@ package gr.thmmy.mthmmy.activities;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
@ -22,20 +23,15 @@ import static gr.thmmy.mthmmy.utils.Thmmy.login;
public class LoginActivity extends BaseActivity {
private static final String TAG = "LoginActivity";
private static boolean passed=false; //becomes true after (guest) login - to redirect to Main
Button btnLogin;
Button btnGuest;
private EditText inputUsername;
private EditText inputPassword;
private String username;
private String password;
@Override
public void onCreate(Bundle savedInstanceState) {
/*if(passed) //redirect to MainActivity if user passed this one at least once
{
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}*/
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
@ -50,27 +46,31 @@ public class LoginActivity extends BaseActivity {
public void onClick(View view) {
Log.d(TAG, "Login");
username = inputUsername.getText().toString().trim();
password = inputPassword.getText().toString().trim();
// Check for empty data in the form
if (!validate()) {
onLoginFailed();
return;
}
String username = inputUsername.getText().toString().trim();
String password = inputPassword.getText().toString().trim();
// login user
new LoginTask().execute(username,password);
new LoginTask().execute(username, password);
}
});
// Link to Register Screen
// Guest Button Action
btnGuest.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
SharedPreferences.Editor editor = getSharedPreferences(SHARED_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString(USER_NAME, GUEST_PREF_USERNAME);
editor.putBoolean(IS_LOGGED_IN, true);
editor.apply();
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
passed=true;
finish();
overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
}
@ -92,10 +92,7 @@ public class LoginActivity extends BaseActivity {
public boolean validate() {
boolean valid = true;
String email = inputUsername.getText().toString();
String password = inputPassword.getText().toString();
if (email.isEmpty()) {
if (username.isEmpty()) {
inputUsername.setError("Enter a valid username");
valid = false;
} else {
@ -112,13 +109,12 @@ public class LoginActivity extends BaseActivity {
return valid;
}
private class LoginTask extends AsyncTask<String, Void, Integer>
{
private class LoginTask extends AsyncTask<String, Void, Integer> {
ProgressDialog progressDialog;
@Override
protected Integer doInBackground(String... params) {
setLoginData(login(params[0], params[1],"-1"));
setLoginData(login(params[0], params[1], "-1"));
return loginData.getStatus();
}
@ -162,13 +158,16 @@ public class LoginActivity extends BaseActivity {
.show();
break;
case LOGGED_IN:
//progressDialog.dismiss();
SharedPreferences.Editor editor = getSharedPreferences(SHARED_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString(USER_NAME, username);
editor.putBoolean(IS_LOGGED_IN, true);
editor.apply();
Toast.makeText(getApplicationContext(),
"Login successful!", Toast.LENGTH_LONG)
.show();
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
passed=true;
finish();
overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
break;

80
app/src/main/java/gr/thmmy/mthmmy/activities/MainActivity.java

@ -1,6 +1,7 @@
package gr.thmmy.mthmmy.activities;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
@ -11,18 +12,17 @@ import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import org.jsoup.nodes.Document;
import android.widget.Toast;
import gr.thmmy.mthmmy.R;
import gr.thmmy.mthmmy.data.TopicSummary;
import gr.thmmy.mthmmy.sections.recent.RecentFragment;
import gr.thmmy.mthmmy.utils.Thmmy;
public class MainActivity extends BaseActivity implements RecentFragment.OnListFragmentInteractionListener
{
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager; /** The {@link ViewPager} that will host the section contents.*/
public class MainActivity extends BaseActivity implements RecentFragment.OnListFragmentInteractionListener {
/**
* The {@link ViewPager} that will host the section contents.
*/
private Menu menu;
@ -31,14 +31,22 @@ public class MainActivity extends BaseActivity implements RecentFragment.OnListF
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_NAME, MODE_PRIVATE);
if (!prefs.getBoolean(IS_LOGGED_IN, false)) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each section of the activity
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
SectionsPagerAdapter mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
ViewPager mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
@ -55,10 +63,11 @@ public class MainActivity extends BaseActivity implements RecentFragment.OnListF
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
this.menu=menu;
this.menu = menu;
getMenuInflater().inflate(R.menu.menu_main, menu);
if(loginData.getStatus()== Thmmy.LOGGED_IN)
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_NAME, MODE_PRIVATE);
if (prefs.getBoolean(IS_LOGGED_IN, false)
&& prefs.getString(USER_NAME, null) != GUEST_PREF_USERNAME)
hideLogin();
else
hideLogout();
@ -67,20 +76,17 @@ public class MainActivity extends BaseActivity implements RecentFragment.OnListF
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_about)
{
if (id == R.id.action_about) {
Intent i = new Intent(MainActivity.this, AboutActivity.class);
startActivity(i);
return true;
}
else if (id == R.id.action_logout)
} else if (id == R.id.action_logout)
new LogoutTask().execute();
else{
Intent intent = new Intent(MainActivity.this,LoginActivity.class);
else {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
@ -89,26 +95,22 @@ public class MainActivity extends BaseActivity implements RecentFragment.OnListF
return super.onOptionsItemSelected(item);
}
private void hideLogin()
{
private void hideLogin() {
MenuItem login = menu.findItem(R.id.action_login);
MenuItem logout = menu.findItem(R.id.action_logout);
login.setVisible(false);
logout.setVisible(true);
}
private void hideLogout()
{
private void hideLogout() {
MenuItem login = menu.findItem(R.id.action_login);
MenuItem logout = menu.findItem(R.id.action_logout);
login.setVisible(true);
logout.setVisible(false);
}
@Override
public void onFragmentInteraction(TopicSummary topicSummary)
{
public void onFragmentInteraction(TopicSummary topicSummary) {
Intent i = new Intent(MainActivity.this, TopicActivity.class);
i.putExtra("TOPIC_URL", topicSummary.getTopicUrl());
i.putExtra("TOPIC_TITLE", topicSummary.getTitle());
@ -116,6 +118,7 @@ public class MainActivity extends BaseActivity implements RecentFragment.OnListF
}
//---------------------------------FragmentPagerAdapter---------------------------------------------
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages. If it becomes too memory intensive,
@ -154,29 +157,26 @@ public class MainActivity extends BaseActivity implements RecentFragment.OnListF
}
}
private class LogoutTask extends AsyncTask<Void, Void, Integer>
{
protected Integer doInBackground(Void... voids)
{
private class LogoutTask extends AsyncTask<Void, Void, Integer> {
protected Integer doInBackground(Void... voids) {
return Thmmy.logout(loginData);
}
protected void onPreExecute() {
//TODO: a progressbar maybe?
}
protected void onPostExecute(Integer result)
{
if(result==Thmmy.LOGGED_OUT)
protected void onPostExecute(Integer result) {
if (result == Thmmy.LOGGED_OUT) {
SharedPreferences.Editor editor = getSharedPreferences(SHARED_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString(USER_NAME, null);
editor.putBoolean(IS_LOGGED_IN, false);
editor.apply();
Toast.makeText(getBaseContext(), "Logged out successfully!", Toast.LENGTH_LONG).show();
hideLogout();
else
} else
hideLogin();
}
}
}

91
app/src/main/java/gr/thmmy/mthmmy/utils/Thmmy.java

@ -27,32 +27,27 @@ import okhttp3.RequestBody;
import okhttp3.Response;
public class Thmmy
{
public class Thmmy {
private static final HttpUrl loginUrl = HttpUrl.parse("https://www.thmmy.gr/smf/index.php?action=login2");
private static final HttpUrl indexUrl = HttpUrl.parse("https://www.thmmy.gr/smf/index.php");
public static final int LOGGED_OUT = 0;
public static final int LOGGED_IN = 1;
public static final int WRONG_USER= 2;
public static final int WRONG_PASSWORD= 3;
public static final int FAILED= 4;
public static final int WRONG_USER = 2;
public static final int WRONG_PASSWORD = 3;
public static final int FAILED = 4;
public static final int CERTIFICATE_ERROR = 5;
public static final int OTHER_ERROR = 6;
//-------------------------------------------LOGIN--------------------------------------------------
//Two options: (username, password, duration) or nothing - cookies
public static LoginData login(String... strings)
{
Log.d("Login","Logging in...");
public static LoginData login(String... strings) {
Log.d("Login", "Logging in...");
LoginData loginData = new LoginData();
Request request;
if(strings.length==3)
{
if (strings.length == 3) {
String loginName = strings[0];
String password = strings[1];
String duration = strings[2];
@ -68,9 +63,7 @@ public class Thmmy
.url(loginUrl)
.post(formBody)
.build();
}
else
{
} else {
request = new Request.Builder()
.url(loginUrl)
.build();
@ -78,39 +71,33 @@ public class Thmmy
OkHttpClient client = BaseActivity.getClient();
try
{
try {
Response response = client.newCall(request).execute();
Document document = Jsoup.parse(response.body().string());
Element logout = document.getElementById("logoutbtn");
if (logout != null)
{
if (logout != null) {
Log.i("Login", "Login successful");
setPersistentCookieSession();
loginData.setUsername(extractUserName(document));
loginData.setLogoutLink(HttpUrl.parse(logout.attr("href")));
loginData.setStatus(LOGGED_IN);
}
else
{
} else {
Log.w("Login", "Login failed");
loginData.setStatus(FAILED);
//Making error more specific
Elements error = document.select("b:contains(That username does not exist.)");
if (error.size()==1)
{
if (error.size() == 1) {
loginData.setStatus(WRONG_USER);
Log.d("Login","Wrong Username");
Log.d("Login", "Wrong Username");
}
error = document.select("body:contains(Password incorrect)");
if (error.size()==1)
{
Log.d("Login","Wrong Password");
if (error.size() == 1) {
Log.d("Login", "Wrong Password");
loginData.setStatus(WRONG_PASSWORD);
}
@ -126,21 +113,17 @@ public class Thmmy
loginData.setStatus(OTHER_ERROR);
}
return loginData;
}
//To maintain data between activities/ between activity state change (possibly temporary solution)
public static class LoginData implements Parcelable
{
public static class LoginData implements Parcelable {
private int status;
private String username;
private HttpUrl logoutLink;
public LoginData() {}
public LoginData() {
}
public String getUsername() {
return username;
@ -192,18 +175,16 @@ public class Thmmy
private LoginData(Parcel in) {
status = in.readInt();
username=in.readString();
logoutLink=HttpUrl.parse(in.readString());
username = in.readString();
logoutLink = HttpUrl.parse(in.readString());
}
}
private static boolean setPersistentCookieSession()
{
private static boolean setPersistentCookieSession() {
List<Cookie> cookieList = BaseActivity.getCookieJar().loadForRequest(HttpUrl.parse("https://www.thmmy.gr"));
if (cookieList.size() == 2) {
if ((cookieList.get(0).name().equals("THMMYgrC00ki3")) && (cookieList.get(1).name().equals("PHPSESSID")))
{
if ((cookieList.get(0).name().equals("THMMYgrC00ki3")) && (cookieList.get(1).name().equals("PHPSESSID"))) {
Cookie.Builder builder = new Cookie.Builder();
builder.name(cookieList.get(1).name())
.value(cookieList.get(1).value())
@ -221,10 +202,8 @@ public class Thmmy
//-------------------------------------LOGIN ENDS-----------------------------------------------
//--------------------------------------LOGOUT--------------------------------------------------
public static int logout(LoginData loginData)
{
public static int logout(LoginData loginData) {
OkHttpClient client = BaseActivity.getClient();
Request request = new Request.Builder()
.url(loginData.getLogoutLink())
@ -234,16 +213,13 @@ public class Thmmy
Response response = client.newCall(request).execute();
Document document = Jsoup.parse(response.body().string());
Elements login = document.select("[value=Login]");
Elements login = document.select("[value=Login]");
((PersistentCookieJar) BaseActivity.getCookieJar()).clear();
if(!login.isEmpty())
{
if (!login.isEmpty()) {
Log.i("Logout", "Logout successful");
loginData.setStatus(LOGGED_OUT);
return LOGGED_OUT;
}
else
{
} else {
Log.w("Logout", "Logout failed");
return FAILED;
}
@ -260,22 +236,15 @@ public class Thmmy
}
//----------------------------------------LOGOUT ENDS-----------------------------------------------
//-------------------------------------------MISC---------------------------------------------------
public static String extractUserName(Document doc)
{
if(doc!=null)
{
//-------------------------------------------MISC---------------------------------------------------
public static String extractUserName(Document doc) {
if (doc != null) {
Elements user = doc.select("div[id=myuser] > h3");
if (user.size()==1)
{
if (user.size() == 1) {
String txt = user.first().ownText();
Pattern pattern = Pattern.compile(", (.*?),");

8
app/src/main/res/drawable/page_first.xml

@ -1,8 +0,0 @@
<!-- drawable/page_first.xml -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportHeight="24"
android:viewportWidth="24">
<path android:fillColor="#000" android:pathData="M18.41,16.59L13.82,12L18.41,7.41L17,6L11,12L17,18L18.41,16.59M6,6H8V18H6V6Z" />
</vector>

8
app/src/main/res/drawable/page_last.xml

@ -1,8 +0,0 @@
<!-- drawable/page_last.xml -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportHeight="24"
android:viewportWidth="24">
<path android:fillColor="#000" android:pathData="M5.59,7.41L10.18,12L5.59,16.59L7,18L13,12L7,6L5.59,7.41M16,6H18V18H16V6Z" />
</vector>

8
app/src/main/res/drawable/page_next.xml

@ -1,8 +0,0 @@
<!-- drawable/page_next.xml -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportHeight="24"
android:viewportWidth="24">
<path android:fillColor="#000" android:pathData="M16,18H18V6H16M6,18L14.5,12L6,6V18Z" />
</vector>

8
app/src/main/res/drawable/page_previous.xml

@ -1,8 +0,0 @@
<!-- drawable/page_previous.xml -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportHeight="24"
android:viewportWidth="24">
<path android:fillColor="#000" android:pathData="M6,18V6H8V18H6M9.5,12L18,6V18L9.5,12Z" />
</vector>
Loading…
Cancel
Save