Created User Class.

User is now saved on Login. and then passed as serialised String to the Class.

MainActivity Has getUser()
This commit is contained in:
Sagi Dayan 2016-07-07 23:40:25 +03:00
parent 00f361ce79
commit 01de134c7a
8 changed files with 353 additions and 173 deletions

View file

@ -15,14 +15,19 @@ import android.widget.EditText;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.TextView; import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
import com.android.volley.Response; import com.android.volley.Response;
import com.android.volley.VolleyError; import com.android.volley.VolleyError;
import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
import java.util.Vector;
/** /**
* A login screen that offers login via email/password. * A login screen that offers login via email/password.
*/ */
public class LoginActivity extends AppCompatActivity implements View.OnClickListener, TextWatcher{ public class LoginActivity extends AppCompatActivity implements View.OnClickListener, TextWatcher {
// UI references. // UI references.
@ -35,6 +40,7 @@ public class LoginActivity extends AppCompatActivity implements View.OnClickList
private final String LOGIN_PATH = "/login"; private final String LOGIN_PATH = "/login";
private LoginActivity self; //this private LoginActivity self; //this
protected LinearLayout layout; protected LinearLayout layout;
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
@ -75,12 +81,13 @@ public class LoginActivity extends AppCompatActivity implements View.OnClickList
Log.d(TAG, "user: " + username); Log.d(TAG, "user: " + username);
Log.d(TAG, "pwd: " + password); Log.d(TAG, "pwd: " + password);
if(TextUtils.isEmpty(username) || !isUsernameValid(username) || TextUtils.isEmpty(password) || !isPasswordValid(password)) { if (TextUtils.isEmpty(username) || !isUsernameValid(username) || TextUtils.isEmpty(password) || !isPasswordValid(password)) {
return false; return false;
} else{ } else {
return true; return true;
} }
} }
private void attemptLogin() { private void attemptLogin() {
MainActivity.showLoadingDialog(this, "Connecting", "Authenticating data"); MainActivity.showLoadingDialog(this, "Connecting", "Authenticating data");
mPasswordView.setError(null); mPasswordView.setError(null);
@ -110,15 +117,30 @@ public class LoginActivity extends AppCompatActivity implements View.OnClickList
@Override @Override
public void onResponse(JSONObject response) { public void onResponse(JSONObject response) {
try { try {
if(!response.isNull("user")) { if (!response.isNull("user")) {
Log.e(TAG, "onLoginSuccess => user exist"); // TODO: REMOVE console Log.e(TAG, "onLoginSuccess => user exist"); // TODO: REMOVE console
SharedPreferences sharedPref = self.getSharedPreferences(MainActivity.LOCAL_DATA_TSN, Context.MODE_PRIVATE); SharedPreferences sharedPref = self.getSharedPreferences(MainActivity.LOCAL_DATA_TSN, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit(); SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("UserId", response.getJSONObject("user").getString("id")); String id, password, email, avatar, username, likedNotes = "";
JSONArray likedNotes_JSON;
id = response.getJSONObject("user").getString("id");
password = response.getJSONObject("user").getString("password");
username = response.getJSONObject("user").getString("username");
avatar = response.getJSONObject("user").getString("avatar");
email = response.getJSONObject("user").getString("email");
likedNotes_JSON = response.getJSONObject("user").getJSONArray("liked_notes_id");
for (int i = 0; i < likedNotes_JSON.length(); i++) {
likedNotes += likedNotes_JSON.get(i);
if (i != likedNotes_JSON.length() - 1) {
likedNotes += User.LIKED_NOTES_DELIMETER;
}
}
editor.putString("UserData", id+User.ATTARS_DELIMETER+username+User.ATTARS_DELIMETER+password+User.ATTARS_DELIMETER+email+User.ATTARS_DELIMETER+avatar+User.ATTARS_DELIMETER+likedNotes);
editor.commit(); editor.commit();
Intent personalSpaceActivity = new Intent(LoginActivity.this, MainActivity.class); Intent personalSpaceActivity = new Intent(LoginActivity.this, MainActivity.class);
Bundle loginUserBundle = new Bundle(); Bundle loginUserBundle = new Bundle();
loginUserBundle.putString("user_id", response.getJSONObject("user").getString("id")); loginUserBundle.putString("UserData", id+User.ATTARS_DELIMETER+username+User.ATTARS_DELIMETER+password+User.ATTARS_DELIMETER+email+User.ATTARS_DELIMETER+avatar+User.ATTARS_DELIMETER+likedNotes);
personalSpaceActivity.putExtras(loginUserBundle); personalSpaceActivity.putExtras(loginUserBundle);
MainActivity.dismissLoadingDialog(); MainActivity.dismissLoadingDialog();
startActivity(personalSpaceActivity); startActivity(personalSpaceActivity);
@ -128,11 +150,11 @@ public class LoginActivity extends AppCompatActivity implements View.OnClickList
self.mUsernameView.getText().clear(); self.mUsernameView.getText().clear();
self.mPasswordView.getText().clear(); self.mPasswordView.getText().clear();
self.removeFocuse(); self.removeFocuse();
((TextView)findViewById(R.id.textView2)).setVisibility(View.INVISIBLE); ((TextView) findViewById(R.id.textView2)).setVisibility(View.INVISIBLE);
Log.d(TAG, "No such user, " + response.get("user")); Log.d(TAG, "No such user, " + response.get("user"));
} }
}catch (Exception e) { } catch (Exception e) {
Log.e(TAG, "onLoginSuccess:" + e.getMessage()); Log.e(TAG, "onLoginSuccess:" + e.getMessage());
} }
} }
@ -142,7 +164,7 @@ public class LoginActivity extends AppCompatActivity implements View.OnClickList
@Override @Override
public void onErrorResponse(VolleyError error) { public void onErrorResponse(VolleyError error) {
MainActivity.dismissLoadingDialog(); MainActivity.dismissLoadingDialog();
Toast.makeText(self , "Username Or Password Incorrect", Toast.LENGTH_LONG).show(); Toast.makeText(self, "Username Or Password Incorrect", Toast.LENGTH_LONG).show();
//Clean texts //Clean texts
self.mUsernameView.getText().clear(); self.mUsernameView.getText().clear();
self.mPasswordView.getText().clear(); self.mPasswordView.getText().clear();
@ -163,7 +185,7 @@ public class LoginActivity extends AppCompatActivity implements View.OnClickList
@Override @Override
public void onClick(View view) { public void onClick(View view) {
switch(view.getId()){ switch (view.getId()) {
case R.id.al_login_button: case R.id.al_login_button:
//Do Login //Do Login
Log.d(TAG, "Login......."); Log.d(TAG, "Login.......");
@ -185,12 +207,11 @@ public class LoginActivity extends AppCompatActivity implements View.OnClickList
@Override @Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if(isParamsValid(mUsernameView.getText().toString(), mPasswordView.getText().toString())) { if (isParamsValid(mUsernameView.getText().toString(), mPasswordView.getText().toString())) {
((TextView)findViewById(R.id.textView2)).setVisibility(View.INVISIBLE); ((TextView) findViewById(R.id.textView2)).setVisibility(View.INVISIBLE);
mLoginButton.setEnabled(true); mLoginButton.setEnabled(true);
} } else {
else{ ((TextView) findViewById(R.id.textView2)).setVisibility(View.VISIBLE);
((TextView)findViewById(R.id.textView2)).setVisibility(View.VISIBLE);
mLoginButton.setEnabled(false); mLoginButton.setEnabled(false);
} }
} }

View file

@ -4,6 +4,9 @@ import android.app.ProgressDialog;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle; import android.os.Bundle;
import android.support.design.widget.FloatingActionButton; import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar; import android.support.design.widget.Snackbar;
@ -18,6 +21,7 @@ import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar; import android.support.v7.widget.Toolbar;
import android.view.Menu; import android.view.Menu;
import android.view.MenuItem; import android.view.MenuItem;
import android.widget.ImageView;
import com.android.volley.Response; import com.android.volley.Response;
import com.android.volley.VolleyError; import com.android.volley.VolleyError;
@ -26,6 +30,7 @@ import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import java.io.InputStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
@ -34,7 +39,7 @@ public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener { implements NavigationView.OnNavigationItemSelectedListener {
public static final String LOCAL_DATA_TSN = "TSN_DATA_STORE"; public static final String LOCAL_DATA_TSN = "TSN_DATA_STORE";
protected final String TAG = "[TSN / MainActivity]"; protected final String TAG = "[TSN / MainActivity]";
protected String userId; protected User user;
private GPSUtils gpsUtils; private GPSUtils gpsUtils;
private boolean locationPermission; private boolean locationPermission;
public static ProgressDialog progress; public static ProgressDialog progress;
@ -42,6 +47,7 @@ public class MainActivity extends AppCompatActivity
private PersonalFragment personalFragment; private PersonalFragment personalFragment;
private Toolbar toolbar; private Toolbar toolbar;
public static final String BASE_URL = "http://thesocialnotework-api.appspot.com/api"; public static final String BASE_URL = "http://thesocialnotework-api.appspot.com/api";
private ImageView menu_avatar;
@Override @Override
@ -66,9 +72,12 @@ public class MainActivity extends AppCompatActivity
navigationView.setNavigationItemSelectedListener(this); navigationView.setNavigationItemSelectedListener(this);
//get Bundle data (Userid) //get Bundle data (UserString)
Bundle b = getIntent().getExtras(); Bundle b = getIntent().getExtras();
userId = b.getString("user_id"); this.user = new User(b.getString("UserData"));
menu_avatar = (ImageView)findViewById(R.id.user_avatar);
//TODO - Change the menu_avatar to user.getAvatar()
//Change Layout //Change Layout
Log.d(TAG, "Changing Fragment to Personal Activity"); Log.d(TAG, "Changing Fragment to Personal Activity");
@ -225,6 +234,10 @@ public class MainActivity extends AppCompatActivity
return stringArray; return stringArray;
} }
public String getUserId(){return userId;} public User getUser(){
return user;
}
public String getUserId(){return user.getId();}
} }

View file

@ -55,6 +55,7 @@ public class PersonalFragment extends Fragment {
private ListAdapter noteListAdapter; private ListAdapter noteListAdapter;
private String userId; private String userId;
private final String TAG = "[TSN/PersonalFragment]"; private final String TAG = "[TSN/PersonalFragment]";
private MainActivity activity;
public PersonalFragment() { public PersonalFragment() {
// Required empty public constructor // Required empty public constructor
@ -66,21 +67,22 @@ public class PersonalFragment extends Fragment {
Bundle savedInstanceState) { Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_personal, container, false); View view = inflater.inflate(R.layout.fragment_personal, container, false);
// Inflate the layout for this fragment // Inflate the layout for this fragment
activity = (MainActivity) getActivity();
Bundle bundle = getArguments(); Bundle bundle = getArguments();
this.userId = bundle.getString("user_id"); this.userId = activity.getUserId();
Log.d(TAG, "onCreateView: userID: " + userId); Log.d(TAG, "onCreateView: userID: " + userId);
//check for permission //check for permission
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, FINE_PERM); ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, FINE_PERM);
this.noteList = (ListView) view.findViewById(R.id.ps_list_listview); this.noteList = (ListView) view.findViewById(R.id.ps_list_listview);
gpsUtils = ((MainActivity) getActivity()).getGPSUtils(); gpsUtils = activity.getGPSUtils();
gpsUtils.getLocation(); gpsUtils.getLocation();
listOfNotes = new ArrayList<>(); listOfNotes = new ArrayList<>();
noteListAdapter = new ListAdapter(getContext(), listOfNotes); noteListAdapter = new ListAdapter(getContext(), listOfNotes);
noteList.setAdapter(noteListAdapter); noteList.setAdapter(noteListAdapter);
noteList.setOnItemClickListener(new ItemClickedListener()); noteList.setOnItemClickListener(new ItemClickedListener());
MainActivity.showLoadingDialog(getActivity(), "Fetching..", "getting your notes"); MainActivity.showLoadingDialog(activity, "Fetching..", "getting your notes");
getAllNotes(); getAllNotes();
//https://thesocialnotework-api.appspot.com/api/note/all?uid=<USER_ID> //https://thesocialnotework-api.appspot.com/api/note/all?uid=<USER_ID>

View file

@ -34,7 +34,7 @@ public class SplashActivity extends AppCompatActivity {
background.setImageDrawable( getResources().getDrawable(rand_splash())); background.setImageDrawable( getResources().getDrawable(rand_splash()));
} }
SharedPreferences sharedPref = this.getSharedPreferences(MainActivity.LOCAL_DATA_TSN, Context.MODE_PRIVATE); SharedPreferences sharedPref = this.getSharedPreferences(MainActivity.LOCAL_DATA_TSN, Context.MODE_PRIVATE);
final String userId = sharedPref.getString("UserId", null); final String userData = sharedPref.getString("UserData", null);
Thread timerThread = new Thread(){ Thread timerThread = new Thread(){
public void run(){ public void run(){
@ -43,12 +43,12 @@ public class SplashActivity extends AppCompatActivity {
}catch(InterruptedException e){ }catch(InterruptedException e){
e.printStackTrace(); e.printStackTrace();
}finally{ }finally{
if(userId == null){ if(userData == null){
startActivity(new Intent(SplashActivity.this, LoginActivity.class)); startActivity(new Intent(SplashActivity.this, LoginActivity.class));
}else{ }else{
Intent personalSpaceActivity = new Intent(SplashActivity.this, MainActivity.class); Intent personalSpaceActivity = new Intent(SplashActivity.this, MainActivity.class);
Bundle loginUserBundle = new Bundle(); Bundle loginUserBundle = new Bundle();
loginUserBundle.putString("user_id", userId); loginUserBundle.putString("UserData", userData);
personalSpaceActivity.putExtras(loginUserBundle); personalSpaceActivity.putExtras(loginUserBundle);
startActivity(personalSpaceActivity); startActivity(personalSpaceActivity);
} }

View file

@ -0,0 +1,134 @@
package com.android_app.matan.ara.sagi.thesocialnotework;
import android.util.Log;
import java.util.Vector;
/**
* Created by sagi on 7/7/16. - A Basic User Class
* "user": {
"id": 5733311175458816,
"username": "s",
"password": "1234",
"email": "sagi@dayan.com",
"creation_time": 1467814417313,
"avatar": "http://www.aljazeera.com/mritems/images/site/DefaultAvatar.jpg",
"liked_notes_id": []
}
*/
public class User {
public static final int INDEX_ID = 0, INDEX_USERNAME = 1, INDEX_PASSWORD = 2, INDEX_EMAIL = 3, INDEX_AVATAR = 4, INDEX_LIKES_NOTES = 5;
public static final String TAG = "[TSN/User]", ATTARS_DELIMETER="||" , LIKED_NOTES_DELIMETER="|";
protected String id, password, email, avatar, username;
protected Vector<String> liked_notes;
public User(String serializedUserData){
liked_notes = new Vector<>();
String[] array = serializedUserData.split("\\|\\|");
for (int i = 0 ; i < array.length ; i ++){
switch (i){
case INDEX_ID:
this.id = array[i];
break;
case INDEX_AVATAR:
this.avatar = array[i];
break;
case INDEX_EMAIL:
this.email = array[i];
break;
case INDEX_LIKES_NOTES:
createArrayNotes(array[i]);
break;
case INDEX_PASSWORD:
this.password = array[i];
break;
case INDEX_USERNAME:
this.username = array[i];
break;
default:
Log.w(TAG, "User: Got An Unowned value: " + array[i]);
break;
}
}
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Vector<String> getLiked_notes() {
return liked_notes;
}
public void setLiked_notes(Vector<String> liked_notes) {
this.liked_notes = liked_notes;
}
private void createArrayNotes(String s) {
Log.d(TAG, "createArrayNotes:" + s);
String[] noteIds = s.split("\\|");
for (int i = 0; i < noteIds.length; i++) {
Log.d(TAG, "createArrayNotes: Note ID " + i + ": " + noteIds[i]);
liked_notes.add(noteIds[i]);
}
Log.d(TAG, "createArrayNotes: =================: == Done With Note IDS");
}
public String Serialise(){
return id + "||" + username + "||" + password + "||" + email + "||" + serialiseNoteList();
}
private String serialiseNoteList() {
String result = "";
for (int i = 0; i < liked_notes.size(); i++) {
result += liked_notes.get(i);
if(i != liked_notes.size() - 1){
result+=";";
}
}
return result;
}
public String toString(){
return "Id: "+id+" UserName: " + username +" Password: " +password +" email: " + email+ " Liked Notes: "+liked_notes.toString();
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 KiB

View file

@ -1,14 +1,23 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="@dimen/nav_header_height" android:layout_height="@dimen/nav_header_height"
android:background="@drawable/header_nav" android:background="@drawable/header_nav"
android:gravity="bottom" android:gravity="bottom"
android:orientation="vertical" android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin" android:paddingBottom="60dp"
android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin" android:paddingTop="@dimen/activity_vertical_margin"
android:theme="@style/ThemeOverlay.AppCompat.Dark"> android:theme="@style/ThemeOverlay.AppCompat.Dark">
</LinearLayout> <ImageView
android:layout_width="70dp"
android:layout_height="70dp"
android:id="@+id/user_avatar"
android:src="@drawable/default_avatar"
android:scaleType="fitCenter"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:contentDescription="@string/avatar" />
</RelativeLayout>

View file

@ -38,5 +38,6 @@
<string name="hello_blank_fragment">Hello blank fragment</string> <string name="hello_blank_fragment">Hello blank fragment</string>
<string name="login_err_message_invalid">Password should be at least 4 chars long</string> <string name="login_err_message_invalid">Password should be at least 4 chars long</string>
<string name="title_activity_maps">Map</string> <string name="title_activity_maps">Map</string>
<string name="avatar">Avatar</string>
</resources> </resources>