This commit is contained in:
Aran Zaiger 2016-07-10 17:57:54 +03:00
commit ffe73a159e
7 changed files with 347 additions and 133 deletions

View file

@ -10,12 +10,9 @@ import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import org.json.JSONObject;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ -27,14 +24,11 @@ public class RegisterActivity extends AppCompatActivity implements View.OnClickL
private Button registerButton;
private Button testBtn;
private RegisterActivity self;
protected RelativeLayout layout;
private final String TAG = "Register Activity";
private final String TAG = "[TSN/RegisterActivity]";
private final String BASE_URL = "http://thesocialnotework-api.appspot.com/api";
private final String REG_PATH = "/register";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@ -58,15 +52,30 @@ public class RegisterActivity extends AppCompatActivity implements View.OnClickL
this.registerButton.setOnClickListener(this);
}
private boolean isUsernameValid(String username) { // username validation
/**
* username validation
* @param username
* @return
*/
private boolean isUsernameValid(String username) {
return !TextUtils.isEmpty(username) && username.length() > 0;
}
private boolean isPasswordValid(String password) { // password validation
/**
* password validation
* @param password
* @return
*/
private boolean isPasswordValid(String password) {
return !TextUtils.isEmpty(password) && password.length() > 3;
}
private boolean isEmailValid(String email) { // email validation
/**
* email validation
* @param email
* @return
*/
private boolean isEmailValid(String email) {
if (TextUtils.isEmpty(email))
return false;
String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
@ -75,11 +84,21 @@ public class RegisterActivity extends AppCompatActivity implements View.OnClickL
return matcher.matches();
}
private boolean isParamsValid(String username, String password, String email) { // private method that validates all params
/**
* private method that validates all params
* @param username
* @param password
* @param email
* @return
*/
private boolean isParamsValid(String username, String password, String email) {
return (isUsernameValid(username) && isPasswordValid(password) && isEmailValid(email));
}
private void attemptRegister() { // attempt registering
/**
* attempt registering
*/
private void attemptRegister() {
Utils.showLoadingDialog(this, "Registering", "Please Wait...");
if (isParamsValid(mUsernameView.getText().toString(), mPasswordView.getText().toString(), mEmailView.getText().toString())) { // params are valid
String username = mUsernameView.getText().toString();
@ -101,9 +120,16 @@ public class RegisterActivity extends AppCompatActivity implements View.OnClickL
}
}
/**
* listener to success response on register from server
*/
Response.Listener<JSONObject> onRegisterSuccess = new Response.Listener<JSONObject>() {
/**
* on response register from server
* @param response
*/
@Override
public void onResponse(JSONObject response) { // listener to success response on register from server
public void onResponse(JSONObject response) {
Utils.dismissLoadingDialog();
try {
if (response.getString("message").equals("created")) { // user created
@ -120,16 +146,25 @@ public class RegisterActivity extends AppCompatActivity implements View.OnClickL
}
};
Response.ErrorListener onRegisterError = new Response.ErrorListener() {
/**
* listener to error response on register from server
* @param error
*/
@Override
public void onErrorResponse(VolleyError error) { // listener to error response on register from server
public void onErrorResponse(VolleyError error) {
Utils.dismissLoadingDialog();
Toast.makeText(self, "Username is already taken. maybe: " + mUsernameView.getText().toString() + "_666 ? :)", Toast.LENGTH_LONG).show();
}
};
/**
* onclick methods to redirect to register and to login
* @param view
*/
@Override
public void onClick(View view) { // onclick methods to redirect to register and to login
public void onClick(View view) {
switch (view.getId()) {
case R.id.ra_register_button:
attemptRegister();
@ -140,7 +175,10 @@ public class RegisterActivity extends AppCompatActivity implements View.OnClickL
}
}
private void returnToLogin() { // redirect to login
/**
* redirect to login
*/
private void returnToLogin() {
Intent i = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(i);
finish();

View file

@ -14,18 +14,37 @@ public class RoundAvatarImageView extends ImageView {
public static float radius = 110.0f;
/**
* constructor I
* @param context
*/
public RoundAvatarImageView(Context context) {
super(context);
}
/**
* constructor II
* @param context
* @param attrs
*/
public RoundAvatarImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* constructor III
* @param context
* @param attrs
* @param defStyle
*/
public RoundAvatarImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
/**
* Clip the image to a rounded avatar
* @param canvas
*/
@Override
protected void onDraw(Canvas canvas) {
//float radius = 36.0f;

View file

@ -52,19 +52,32 @@ public class SettingsFragment extends Fragment implements View.OnClickListener,
}
/**
* a function that called when this class created
*
* @param savedInstanceState
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
/**
* a function that called when view is created
*
* @param inflater
* @param container
* @param savedInstanceState
* @return
*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_settings, container, false);
this.parent = (MainActivity) getActivity();
Utils.showLoadingDialog(parent, "Just a sec...", "");
this.user = parent.getUser();
this.parent = (MainActivity) getActivity(); // holds the activity
Utils.showLoadingDialog(parent, "Just a sec...", ""); // loading dialog
this.user = parent.getUser(); // holds the user
this.cameraBtn = (ImageButton) view.findViewById(R.id.btn_camera);
this.cameraBtn.setOnClickListener(this);
this.avatarImage = (ImageView) view.findViewById(R.id.settings_userAvater_iamgeView);
@ -105,21 +118,21 @@ public class SettingsFragment extends Fragment implements View.OnClickListener,
super.onDetach();
}
/**
* a function that called on click
*
* @param view
*/
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_camera:
//check for permission
// ActivityCompat.requestPermissions(parent, new String[]{Manifest.permission.CAMERA}, 1);
if ((ActivityCompat.checkSelfPermission(parent, android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED)
&& (ActivityCompat.checkSelfPermission(parent, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)) {
openCamera(view);
} else {
Toast.makeText(getActivity(), "No Camera or Storage Permissions granted.\n\"An App is nothing without its permissions\"", Toast.LENGTH_LONG).show();
}
break;
case R.id.btn_save:
if (txt_password.getText().length() > 3 && txt_email.getText().length() > 0)
@ -147,15 +160,25 @@ public class SettingsFragment extends Fragment implements View.OnClickListener,
startActivityForResult(intent, 1);
}
/**
* Creates a folder to hold the photos
*/
protected void createDir() {
File f = new File(Utils.PHOTOS_DIR_PATH);
f.mkdirs();
}
/**
* upon receiving response from the camera
*
* @param requestCode
* @param resultCode
* @param intent
*/
@Override
public void onActivityResult(int requestCode, int resaultCode, Intent intent) {
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, requestCode, intent);
if (resaultCode == Activity.RESULT_OK) {
if (resultCode == Activity.RESULT_OK) {
if (currentImgUri != null) {
saveImage();
Log.d(TAG, "onActivityResult: Image Capured!! - Now Upload That Shit!!");
@ -169,47 +192,51 @@ public class SettingsFragment extends Fragment implements View.OnClickListener,
}
}
/**
* Saves the image
*/
private void saveImage() {
Utils.showLoadingDialog(parent, "Saving Image...", "This Can Take a while");
Utils.showLoadingDialog(parent, "Saving Image...", "This Can Take a while"); // Loader
Bitmap b = BitmapFactory.decodeFile(currentImgUri.getPath()); // Original Image
Bitmap out;
Bitmap b= BitmapFactory.decodeFile(currentImgUri.getPath()); // Original Image
Bitmap out;
if (b.getWidth() >= b.getHeight()){
out = Bitmap.createBitmap(
b,
b.getWidth()/2 - b.getHeight()/2,
0,
b.getHeight(),
b.getHeight()
);
}else{
out = Bitmap.createBitmap(
b,
0,
b.getHeight()/2 - b.getWidth()/2,
b.getWidth(),
b.getWidth()
);
}
out = Bitmap.createScaledBitmap(out, 320, 320, false);
File file = new File(currentImgUri.getPath());
FileOutputStream fOut;
try {
fOut = new FileOutputStream(file);
out.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
b.recycle();
out.recycle();
} catch (Exception e) {}
// Crop image
if (b.getWidth() >= b.getHeight()) {
out = Bitmap.createBitmap(
b,
b.getWidth() / 2 - b.getHeight() / 2,
0,
b.getHeight(),
b.getHeight()
);
} else {
out = Bitmap.createBitmap(
b,
0,
b.getHeight() / 2 - b.getWidth() / 2,
b.getWidth(),
b.getWidth()
);
}
// Resizing image
out = Bitmap.createScaledBitmap(out, 320, 320, false);
File file = new File(currentImgUri.getPath());
FileOutputStream fOut;
try {
fOut = new FileOutputStream(file);
out.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
b.recycle();
out.recycle();
} catch (Exception e) {}
JSONObject payload = new JSONObject();
// Upload image
try {
payload.put("image", ImageToBase64(file.getAbsolutePath()));
} catch (JSONException e) {
@ -234,6 +261,11 @@ public class SettingsFragment extends Fragment implements View.OnClickListener,
}, Utils.genericErrorListener);
}
/**
* Converts the file to base 64 bit
* @param filePath
* @return
*/
private String ImageToBase64(String filePath) {
Bitmap bm = BitmapFactory.decodeFile(filePath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();

View file

@ -6,14 +6,18 @@ import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import java.util.Random;
public class SplashActivity extends AppCompatActivity {
private ImageView background;
private int timerDelay = 3500;
/**
* called when this class is created
* @param savedInstanceState
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@ -21,7 +25,9 @@ public class SplashActivity extends AppCompatActivity {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_splash);
background = (ImageView) findViewById(R.id.background);
final int sdk = android.os.Build.VERSION.SDK_INT;
final int sdk = android.os.Build.VERSION.SDK_INT; // holds the sdk
// Configuring the method to use considering the sdk
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
background.setImageDrawable( getResources().getDrawable(rand_splash()) );
} else {
@ -30,6 +36,7 @@ public class SplashActivity extends AppCompatActivity {
final String userData = Utils.getUserFromSharedPrefs(this);
// Timer for the splash image until it will disappear
Thread timerThread = new Thread(){
public void run(){
try{
@ -53,6 +60,9 @@ public class SplashActivity extends AppCompatActivity {
timerThread.start();
}
/**
* on pause function
*/
@Override
protected void onPause() {
// TODO Auto-generated method stub
@ -60,6 +70,10 @@ public class SplashActivity extends AppCompatActivity {
finish();
}
/**
* randomize splash screen
* @return
*/
protected int rand_splash() {
int min = 2, max = 4;
// Usually this can be a field rather than a method variable
@ -69,10 +83,6 @@ public class SplashActivity extends AppCompatActivity {
// so add 1 to make it inclusive
int randomNum = rand.nextInt((max - min) + 1) + min;
switch (randomNum){
// case 0:
// return R.drawable.splash_0;
// case 1:
// return R.drawable.splash_1;
case 2:
return R.drawable.splash_2;
case 3:

View file

@ -66,6 +66,8 @@ public class User {
Log.d(TAG, "User: Constructor Created:\n"+this.toString());
}
// Getters & Setters //
public int getNumber_of_notes() {
return number_of_notes;
}
@ -111,6 +113,10 @@ public class User {
}
/**
* get liked notes
* @return
*/
public Vector<String> getLiked_notes() {
return liked_notes;
}
@ -124,10 +130,18 @@ public class User {
}
}
/**
* convert the user object to string in order to save to the shared prefs
* @return
*/
public String Serialise(){
return id + ATTARS_DELIMETER + username + ATTARS_DELIMETER + password + ATTARS_DELIMETER + email + ATTARS_DELIMETER +avatar + ATTARS_DELIMETER + serialiseNoteList();
}
/**
* convert the user note list to string in order to save to the shared prefs
* @return
*/
private String serialiseNoteList() {
String result = "";
for (int i = 0; i < liked_notes.size(); i++) {
@ -143,6 +157,10 @@ public class User {
return "Id: "+id+" UserName: " + username +" Password: " +password +" email: " + email+ " Avatar: " +avatar+" Liked Notes: "+liked_notes.toString();
}
/**
* update user
* @param activity
*/
public void updateUser(final MainActivity activity){
VolleyUtilSingleton.getInstance(activity).post(Utils.BASE_URL + "/user/upsert", this.toJSON(), new Response.Listener<JSONObject>() {
@Override

View file

@ -19,8 +19,6 @@ import android.widget.ImageView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import org.json.JSONArray;
import org.json.JSONException;
@ -40,23 +38,28 @@ import java.util.HashMap;
public class Utils {
public static final String TAG = "Utils";
public static final String BASE_URL = "http://thesocialnotework-api.appspot.com/api", UPLOAD_IMAGE_PATH="/file/upload";
public static final String BASE_URL = "http://thesocialnotework-api.appspot.com/api", UPLOAD_IMAGE_PATH = "/file/upload";
public static ProgressDialog progress;
private static HashMap<String, Bitmap> bitmapHash = new HashMap<>();
public static final String PHOTOS_DIR_PATH = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/TheSocialNotework/";
public static final String PHOTOS_DIR_PATH = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/TheSocialNotework/";
private static boolean mLocationPermission = false;
private static boolean mCameraPermission = false;
private static SharedPreferences prefs;
public static int filterColor = Color.parseColor("#33adff"), circleColor =0x6666a3ff;
public static final long DAY_MILI = 86400000L,WEEK_MILI = 604800000L,MONTH_MILI = 2592000000L;
public static final float DISTANCE_SMALL = 1000,DISTANCE_MEDIUM = 10000,DISTANCE_LONG = 100000;
public static int filterColor = Color.parseColor("#33adff"), circleColor = 0x6666a3ff;
public static final long DAY_MILI = 86400000L, WEEK_MILI = 604800000L, MONTH_MILI = 2592000000L;
public static final float DISTANCE_SMALL = 1000, DISTANCE_MEDIUM = 10000, DISTANCE_LONG = 100000;
/**
* gets the bitmap from the url
*
* @param url
* @return
*/
public static Bitmap getBitmapFromURL(String url) {
if (Utils.bitmapHash.containsKey(url)){
if (Utils.bitmapHash.containsKey(url)) {
Log.d(TAG, "getBitmapFromURL: Found is hash");
return bitmapHash.get(url);
} else {
@ -78,8 +81,9 @@ public class Utils {
}
// //Generic response ErrorListener
/**
* Generic response ErrorListener
*/
public static Response.ErrorListener genericErrorListener = new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
@ -88,7 +92,9 @@ public class Utils {
Utils.dismissLoadingDialog();
}
};
/**
* Generic response deleteNoteSuccessListener
*/
public static Response.Listener<JSONObject> deleteNoteSuccessListener = new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
@ -96,7 +102,9 @@ public class Utils {
}
};
//response listener for getting all user notes
/**
* response listener for getting all user notes
*/
public static Response.Listener<JSONObject> genericSuccessListener = new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
@ -104,6 +112,13 @@ public class Utils {
}
};
/**
* Show loading dialog
*
* @param context
* @param title
* @param msg
*/
public static void showLoadingDialog(Context context, String title, String msg) {
progress = new ProgressDialog(context);
progress.setTitle(title);
@ -112,17 +127,23 @@ public class Utils {
progress.show();
}
/**
* Stop loading dialog
*/
public static void dismissLoadingDialog() {
if (progress != null && progress.isShowing()) {
progress.dismiss();
}
}
/**
* get all the notes from the object
* @param noteObject
* @param time
* @return
* @throws JSONException
*/
public static Note getNoteFromJsonObj(JSONObject noteObject, Date time) throws JSONException {
// List<Note> listOfNotes = new ArrayList<>();
Note note = new Note(
noteObject.getString("id"),
Float.parseFloat(noteObject.getJSONObject("location").getString("lat")),
@ -138,10 +159,13 @@ public class Utils {
jsonArrayToStringArray(noteObject.getJSONArray("tags"))
);
return note;
// listOfNotes.add(addNote);
}
/**
* convert json array to string array
* @param jArray
* @return
*/
public static ArrayList<String> jsonArrayToStringArray(JSONArray jArray) {
ArrayList<String> stringArray = new ArrayList<String>();
for (int i = 0, count = jArray.length(); i < count; i++) {
@ -155,36 +179,48 @@ public class Utils {
return stringArray;
}
public static void URLtoImageView(ImageView iv, String url){
if(bitmapHash.containsKey(url)){
iv.setImageBitmap(bitmapHash.get(url));
}else{
new setUserAvatar(iv, url).execute();
}
}
private static class setUserAvatar extends AsyncTask<Void, Void, Bitmap> {
private ImageView iv;
private String url;
public setUserAvatar(ImageView imageView, String url) {
this.iv = imageView;
this.url = url;
/**
* convert url to image view
* @param iv
* @param url
*/
public static void URLtoImageView(ImageView iv, String url) {
if (bitmapHash.containsKey(url)) {
iv.setImageBitmap(bitmapHash.get(url));
} else {
new setUserAvatar(iv, url).execute();
}
}
@Override
protected Bitmap doInBackground(Void... v) {
// Bitmap b;
/**
* sets the user avatar
*/
private static class setUserAvatar extends AsyncTask<Void, Void, Bitmap> {
private ImageView iv;
private String url;
return Utils.getBitmapFromURL(url);
public setUserAvatar(ImageView imageView, String url) {
this.iv = imageView;
this.url = url;
}
@Override
protected Bitmap doInBackground(Void... v) {
return Utils.getBitmapFromURL(url);
}
@Override
protected void onPostExecute(Bitmap b) {
iv.setImageBitmap(b);
}
}
@Override
protected void onPostExecute(Bitmap b) {
iv.setImageBitmap(b);
}
}
/**
* gets a rounded bitmap
* @param bitmap
* @param pixels
* @return
*/
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels) {
Log.d(TAG, "rounded bitmap");
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap
@ -208,44 +244,78 @@ public class Utils {
return output;
}
/**
* set location permission
* @param locationPermission
*/
public static void setLocationPermission(boolean locationPermission) {
mLocationPermission = locationPermission;
}
/**
* set camera permission
* @param cameraPermission
*/
public static void setCameraPermission(boolean cameraPermission) {
mCameraPermission = cameraPermission;
}
/**
* check for permissions
* @return
*/
public static boolean arePermissionsGranted() {
return (mLocationPermission && mCameraPermission);
}
public static boolean isCameraPermissionGranted(){
/**
* checks for camera permission
* @return
*/
public static boolean isCameraPermissionGranted() {
return mCameraPermission;
}
public static boolean isLocationPermissionGranted(){
/**
* checks for location permission
* @return
*/
public static boolean isLocationPermissionGranted() {
return mLocationPermission;
}
public static String getUserFromSharedPrefs(Context contexst){
if(prefs == null){
prefs = contexst.getSharedPreferences(MainActivity.LOCAL_DATA_TSN, Context.MODE_PRIVATE);
/**
* get user from shared prefs
* @param contexst
* @return
*/
public static String getUserFromSharedPrefs(Context contexst) {
if (prefs == null) {
prefs = contexst.getSharedPreferences(MainActivity.LOCAL_DATA_TSN, Context.MODE_PRIVATE);
}
return prefs.getString("UserData", null);
};
/**
* update user shared pref
* @param data
* @throws Exception
*/
public static void updateUserSharedPref(String data) throws Exception {
if (prefs == null) throw new Exception("Prefs are not available");
SharedPreferences.Editor editor = prefs.edit();
editor.putString("UserData", data);
editor.commit();
}
return prefs.getString("UserData", null);
};
public static void updateUserSharedPref(String data) throws Exception {
if(prefs == null) throw new Exception("Prefs are not available");
SharedPreferences.Editor editor = prefs.edit();
editor.putString("UserData", data);
editor.commit();
}
public static void removeUserDataFromPrefs() throws Exception{
if(prefs == null) throw new Exception("Prefs are not available");
SharedPreferences.Editor editor = prefs.edit();
editor.remove("UserData");
editor.commit();
}
/**
* remove user data
* @throws Exception
*/
public static void removeUserDataFromPrefs() throws Exception {
if (prefs == null) throw new Exception("Prefs are not available");
SharedPreferences.Editor editor = prefs.edit();
editor.remove("UserData");
editor.commit();
}
}

View file

@ -25,6 +25,10 @@ public class VolleyUtilSingleton {
private final String TAG = "VolleyUtilSingleton";
/**
* volley singleton
* @param context
*/
private VolleyUtilSingleton(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
@ -32,6 +36,11 @@ public class VolleyUtilSingleton {
mImageLoader = new ImageLoader(this.mRequestQueue,new LruBitmapCache());
}
/**
* new singleton
* @param context
* @return
*/
public static synchronized VolleyUtilSingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new VolleyUtilSingleton(context);
@ -56,6 +65,11 @@ public class VolleyUtilSingleton {
return mImageLoader;
}
/**
* create new user on http request
* @param url
* @param body
*/
public void newUser(String url, JSONObject body) {
JsonObjectRequest request =
new JsonObjectRequest(
@ -86,6 +100,13 @@ public class VolleyUtilSingleton {
addToRequestQueue(request);
}
/**
* http post request
* @param url
* @param body
* @param successFunction
* @param errorFunction
*/
public void post(String url, JSONObject body, Response.Listener<JSONObject> successFunction, Response.ErrorListener errorFunction) {
JsonObjectRequest request =
new JsonObjectRequest(
@ -98,6 +119,12 @@ public class VolleyUtilSingleton {
addToRequestQueue(request);
}
/**
* http get request
* @param url
* @param successFunction
* @param errorFunction
*/
public void get(String url, Response.Listener<JSONObject> successFunction, Response.ErrorListener errorFunction) {
JsonObjectRequest request =
new JsonObjectRequest(