# Conflicts:
#	app/src/main/java/com/android_app/matan/ara/sagi/thesocialnotework/PersonalFragment.java
This commit is contained in:
Matan Bar Yosef 2016-07-09 18:26:49 +03:00
commit 43c34b9316
10 changed files with 773 additions and 480 deletions

View file

@ -6,7 +6,9 @@
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission." /> <uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- To auto-complete the email text field in the login form with the user's emails --> <!-- To auto-complete the email text field in the login form with the user's emails -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" /> <uses-permission android:name="android.permission.GET_ACCOUNTS" />

View file

@ -377,6 +377,7 @@ public class GmapFragment extends Fragment implements OnMapReadyCallback {
} }
VolleyUtilSingleton.getInstance(getActivity()).post(Utils.BASE_URL + "/note/like", jsonObj, getNotesSuccessListener, Utils.genericErrorListener); VolleyUtilSingleton.getInstance(getActivity()).post(Utils.BASE_URL + "/note/like", jsonObj, getNotesSuccessListener, Utils.genericErrorListener);
mainActivity.getUser().getLiked_notes().add(note.getId()); mainActivity.getUser().getLiked_notes().add(note.getId());
mainActivity.getUser().updateUser(mainActivity);
likes.setText("Likes: "+(note.getLikes()+1)); likes.setText("Likes: "+(note.getLikes()+1));
} }
} }

View file

@ -38,11 +38,9 @@ public class LoginActivity extends AppCompatActivity implements View.OnClickList
private TextView mRegisterButton; private TextView mRegisterButton;
private Button mLoginButton; private Button mLoginButton;
private final String TAG = "[TSN/LoginActivity]"; private final String TAG = "[TSN/LoginActivity]";
private final String BASE_URL = "http://thesocialnotework-api.appspot.com/api";
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;
private boolean permissionsReturend = false;
@Override @Override
@ -126,8 +124,6 @@ public class LoginActivity extends AppCompatActivity implements View.OnClickList
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.Editor editor = sharedPref.edit();
String id, password, email, avatar, username, likedNotes = ""; String id, password, email, avatar, username, likedNotes = "";
JSONArray likedNotes_JSON; JSONArray likedNotes_JSON;
@ -143,8 +139,7 @@ public class LoginActivity extends AppCompatActivity implements View.OnClickList
likedNotes += User.LIKED_NOTES_DELIMETER; 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); Utils.updateUserSharedPref(id + User.ATTARS_DELIMETER + username + User.ATTARS_DELIMETER + password + User.ATTARS_DELIMETER + email + User.ATTARS_DELIMETER + avatar + User.ATTARS_DELIMETER + likedNotes);
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("UserData", id + User.ATTARS_DELIMETER + username + User.ATTARS_DELIMETER + password + User.ATTARS_DELIMETER + email + User.ATTARS_DELIMETER + avatar + User.ATTARS_DELIMETER + likedNotes); loginUserBundle.putString("UserData", id + User.ATTARS_DELIMETER + username + User.ATTARS_DELIMETER + password + User.ATTARS_DELIMETER + email + User.ATTARS_DELIMETER + avatar + User.ATTARS_DELIMETER + likedNotes);

View file

@ -43,190 +43,207 @@ import java.util.Date;
import java.util.List; import java.util.List;
public class MainActivity extends AppCompatActivity 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 User user; protected User user;
private GPSUtils gpsUtils; private GPSUtils gpsUtils;
private GmapFragment gmapFragment; private boolean locationPermission;
private PersonalFragment personalFragment; private GmapFragment gmapFragment;
private SettingsFragment settingsFragment; private PersonalFragment personalFragment;
private Toolbar toolbar; private SettingsFragment settingsFragment;
public static final String BASE_URL = "http://thesocialnotework-api.appspot.com/api"; private Toolbar toolbar;
private ImageView menu_avatar; public static final String BASE_URL = "http://thesocialnotework-api.appspot.com/api";
private MainActivity self; private ImageView menu_avatar;
private NavigationView nav_view; private MainActivity self;
private final int FINE_PERM = 0, CAMERA_PERM = 1; private NavigationView nav_view;
private final int FINE_PERM = 0, CAMERA_PERM = 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);
this.self = this; this.self = this;
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Personal Notes");
setSupportActionBar(toolbar);
gmapFragment = new GmapFragment();
personalFragment = new PersonalFragment();
settingsFragment = new SettingsFragment();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
toolbar = (Toolbar) findViewById(R.id.toolbar); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
toolbar.setTitle("Personal Notes"); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
setSupportActionBar(toolbar); this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
gmapFragment = new GmapFragment(); drawer.setDrawerListener(toggle);
personalFragment = new PersonalFragment(); toggle.syncState();
settingsFragment = new SettingsFragment();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( navigationView.setNavigationItemSelectedListener(this);
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//get Bundle data (UserString) //get Bundle data (UserString)
Bundle b = getIntent().getExtras(); Bundle b = getIntent().getExtras();
this.user = new User(b.getString("UserData")); this.user = new User(b.getString("UserData"));
//Get The Nav_View Avatar View //Get The Nav_View Avatar View
nav_view = (NavigationView) findViewById(R.id.nav_view); nav_view = (NavigationView) findViewById(R.id.nav_view);
View header_v = nav_view.getHeaderView(0); View header_v = nav_view.getHeaderView(0);
menu_avatar = (ImageView) header_v.findViewById(R.id.nav_user_avatar); menu_avatar = (ImageView) header_v.findViewById(R.id.nav_user_avatar);
//Change Layout //Change Layout
Log.d(TAG, "Changing Fragment to Personal Activity"); Log.d(TAG, "Changing Fragment to Personal Activity");
// PersonalFragment personalFragment = new PersonalFragment(); // PersonalFragment personalFragment = new PersonalFragment();
personalFragment.setArguments(b); personalFragment.setArguments(b);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.fragment_container, personalFragment); ft.replace(R.id.fragment_container, personalFragment);
ft.commit(); ft.commit();
Log.d(TAG, "Changed"); Log.d(TAG, "Changed");
gpsUtils = new GPSUtils(this); gpsUtils = new GPSUtils(this);
gpsUtils.getLocation(); gpsUtils.getLocation();
//Change The Avatar //Change The Avatar
Utils.URLtoImageView(menu_avatar, user.getAvatar()); Utils.URLtoImageView(menu_avatar, user.getAvatar());
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, 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;
} }
@Override return super.onOptionsItemSelected(item);
public void onBackPressed() { }
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) { @SuppressWarnings("StatementWithEmptyBody")
drawer.closeDrawer(GravityCompat.START); @Override
} else { public boolean onNavigationItemSelected(MenuItem item) {
super.onBackPressed(); FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Bundle b = new Bundle();
int id = item.getItemId();
if (id == R.id.nav_explore) {
toolbar.setTitle("Explore");
setSupportActionBar(toolbar);
} else if (id == R.id.nav_map) {
Log.d(TAG, "Before going to map");
toolbar.setTitle("Map");
setSupportActionBar(toolbar);
ft.replace(R.id.fragment_container, gmapFragment);
ft.commit();
} else if (id == R.id.nav_personal) {
Log.d(TAG, "Before going to personal");
ft.replace(R.id.fragment_container, personalFragment);
ft.commit();
} else if (id == R.id.nav_settings) {
toolbar.setTitle("Settings");
setSupportActionBar(toolbar);
ft.replace(R.id.fragment_container, settingsFragment);
ft.commit();
} else if (id == R.id.nav_logout) {
try {
Utils.removeUserDataFromPrefs();
} catch (Exception e) {
e.printStackTrace();
}
Intent loginActivity = new Intent(MainActivity.this, LoginActivity.class);
startActivity(loginActivity);
finish();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public GPSUtils getGPSUtils() {
return this.gpsUtils;
}
public User getUser() {
return user;
}
public String getUserId() {
return user.getId();
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
Log.d(TAG, "onRequestPermissionsResult: in func");
switch (requestCode) {
case FINE_PERM: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 2) {
if (!(grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
Log.d(TAG, "onRequestPermissionsResult: Did Not get permission for location");
Toast.makeText(MainActivity.this, "No Location Permissions granted.\n\"An App is nothing without its permissions\"", Toast.LENGTH_LONG).show();
System.exit(0);
}
if (!(grantResults[1] == PackageManager.PERMISSION_GRANTED)) {
Log.d(TAG, "onRequestPermissionsResult:DIDNT get permission for camera");
Toast.makeText(MainActivity.this, "No Camera Permissions granted.\nyou will not be able to change avatar", Toast.LENGTH_LONG).show();
Utils.setCameraPermission(false);
} else {
Utils.setCameraPermission(true);
}
if (grantResults[2] != PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "onRequestPermissionsResult:DIDNT get READ\\WRITE External storage permission");
Toast.makeText(MainActivity.this, "No READ\\WRITE External storage Permissions granted.\nyou will not be able to change avatar", Toast.LENGTH_LONG).show();
Utils.setCameraPermission(false);
} else {
Utils.setCameraPermission(true);
}
return;
} }
}
} }
@Override }
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override public void updateNavAvatar() {
public boolean onOptionsItemSelected(MenuItem item) { //Change The Avatar
// Handle action bar item clicks here. The action bar will Log.d(TAG, "updateNavAvatar: PINPINPINPIN");
// automatically handle clicks on the Home/Up button, so long Utils.URLtoImageView(menu_avatar, user.getAvatar());
// as you specify a parent activity in AndroidManifest.xml. Toast.makeText(this, "Profile Updated!", Toast.LENGTH_LONG).show();
int id = item.getItemId();
//noinspection SimplifiableIfStatement }
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Bundle b = new Bundle();
int id = item.getItemId();
if (id == R.id.nav_explore) {
toolbar.setTitle("Explore");
setSupportActionBar(toolbar);
} else if (id == R.id.nav_map) {
Log.d(TAG, "Before going to map");
toolbar.setTitle("Map");
setSupportActionBar(toolbar);
ft.replace(R.id.fragment_container, gmapFragment);
ft.commit();
} else if (id == R.id.nav_personal) {
Log.d(TAG, "Before going to personal");
ft.replace(R.id.fragment_container, personalFragment);
ft.commit();
} else if (id == R.id.nav_settings) {
toolbar.setTitle("Settings");
setSupportActionBar(toolbar);
ft.replace(R.id.fragment_container, settingsFragment);
ft.commit();
} else if (id == R.id.nav_logout) {
SharedPreferences sharedPref = this.getSharedPreferences(MainActivity.LOCAL_DATA_TSN, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.remove("UserData");
editor.commit();
Intent loginActivity = new Intent(MainActivity.this, LoginActivity.class);
startActivity(loginActivity);
finish();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public GPSUtils getGPSUtils() {
return this.gpsUtils;
}
public User getUser() {
return user;
}
public String getUserId() {
return user.getId();
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
Log.d(TAG, "onRequestPermissionsResult: in func");
switch (requestCode) {
case FINE_PERM: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 1) {
if (!(grantResults[0] == PackageManager.PERMISSION_GRANTED)){
Log.d(TAG, "onRequestPermissionsResult: Did Not get permission for location");
Toast.makeText(MainActivity.this, "No Location Permissions granted.\n\"An App is nothing without its permissions\"", Toast.LENGTH_LONG).show();
System.exit(0);
}
if (!(grantResults[1] == PackageManager.PERMISSION_GRANTED)) {
Log.d(TAG, "onRequestPermissionsResult:DIDNT get permission for camera");
Toast.makeText(MainActivity.this, "No Camera Permissions granted.\nyou will not be able to change avatar", Toast.LENGTH_LONG).show();
Utils.setCameraPermission(false);
} else {
Utils.setCameraPermission(true);
}
return;
}
}
}
}
} }

View file

@ -52,15 +52,15 @@ import java.util.List;
*/ */
public class PersonalFragment extends Fragment { public class PersonalFragment extends Fragment {
protected ListView noteList; protected ListView noteList;
private final String BASE_URL = "http://thesocialnotework-api.appspot.com/api"; private final String BASE_URL = "http://thesocialnotework-api.appspot.com/api";
private GPSUtils gpsUtils; private GPSUtils gpsUtils;
private List<Note> listOfNotes; private List<Note> listOfNotes;
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; private MainActivity activity;
private final int FINE_PERM = 0, CAMERA_PERM = 1; private final int FINE_PERM = 0, CAMERA_PERM = 1;
private ImageButton dateFilter; private ImageButton dateFilter;
@ -84,22 +84,25 @@ public class PersonalFragment extends Fragment {
} }
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, public View onCreateView(LayoutInflater inflater, ViewGroup container,
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(); activity = (MainActivity) getActivity();
Bundle bundle = getArguments(); Bundle bundle = getArguments();
this.userId = activity.getUserId(); this.userId = activity.getUserId();
Log.d(TAG, "onCreateView: userID: " + userId); Log.d(TAG, "onCreateView: userID: " + userId);
ActivityCompat.requestPermissions(activity, new String[]{
android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE
},
FINE_PERM
);
ActivityCompat.requestPermissions(activity, new String[]{
android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.CAMERA
},
FINE_PERM
);
// ActivityCompat.requestPermissions(activity, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, FINE_PERM); // ActivityCompat.requestPermissions(activity, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, FINE_PERM);
// if (!Utils.arePermissionsGranted()) { // if (!Utils.arePermissionsGranted()) {
@ -176,126 +179,126 @@ public class PersonalFragment extends Fragment {
} }
@Override @Override
public void onAttach(Context context) { public void onAttach(Context context) {
super.onAttach(context); super.onAttach(context);
Utils.dismissLoadingDialog(); Utils.dismissLoadingDialog();
Log.d(TAG, "onAttach"); Log.d(TAG, "onAttach");
} }
@Override @Override
public void onDetach() { public void onDetach() {
super.onDetach(); super.onDetach();
Utils.dismissLoadingDialog(); Utils.dismissLoadingDialog();
} }
public void getAllNotes() { public void getAllNotes() {
Log.d(TAG, "url: " + BASE_URL + "/note/all?uid=" + userId); Log.d(TAG, "url: " + BASE_URL + "/note/all?uid=" + userId);
VolleyUtilSingleton.getInstance(getActivity()).get(BASE_URL + "/note/all?uid=" + userId, getNotesSuccessListener, Utils.genericErrorListener); VolleyUtilSingleton.getInstance(getActivity()).get(BASE_URL + "/note/all?uid=" + userId, getNotesSuccessListener, Utils.genericErrorListener);
} }
private View.OnClickListener addNewNoteDialog = new View.OnClickListener() { private View.OnClickListener addNewNoteDialog = new View.OnClickListener() {
public void onClick(View v) { public void onClick(View v) {
//create and configure dialog //create and configure dialog
final Dialog dialog = new Dialog(getActivity()); final Dialog dialog = new Dialog(getActivity());
dialog.setContentView(R.layout.note_view_full); dialog.setContentView(R.layout.note_view_full);
dialog.setTitle("New Note"); dialog.setTitle("New Note");
WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialog.getWindow().getAttributes()); lp.copyFrom(dialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.MATCH_PARENT; lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.MATCH_PARENT; lp.height = WindowManager.LayoutParams.MATCH_PARENT;
dialog.setCancelable(false); dialog.setCancelable(false);
dialog.show(); dialog.show();
dialog.getWindow().setAttributes(lp); dialog.getWindow().setAttributes(lp);
//get note_view_full layout elements //get note_view_full layout elements
final Switch permissionSwitch = (Switch) dialog.findViewById(R.id.nvf_note_permission); final Switch permissionSwitch = (Switch) dialog.findViewById(R.id.nvf_note_permission);
final EditText newTitle = (EditText) dialog.findViewById(R.id.nvf_note_title); final EditText newTitle = (EditText) dialog.findViewById(R.id.nvf_note_title);
final EditText newBody = (EditText) dialog.findViewById(R.id.nvf_note_content); final EditText newBody = (EditText) dialog.findViewById(R.id.nvf_note_content);
Button saveBtn = (Button) dialog.findViewById(R.id.nvf_note_submit_btn); Button saveBtn = (Button) dialog.findViewById(R.id.nvf_note_submit_btn);
Button cancelBtn = (Button) dialog.findViewById(R.id.nvf_note_cancel_btn); Button cancelBtn = (Button) dialog.findViewById(R.id.nvf_note_cancel_btn);
cancelBtn.setOnClickListener(new View.OnClickListener() { cancelBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) { public void onClick(View v) {
dialog.dismiss(); dialog.dismiss();
} }
}); });
saveBtn.setOnClickListener(new View.OnClickListener() { saveBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) { public void onClick(View v) {
//title too short //title too short
if (newTitle.getText().length() == 0) { if (newTitle.getText().length() == 0) {
Toast toast = Toast.makeText(getActivity(), "Title too short.", Toast.LENGTH_LONG); Toast toast = Toast.makeText(getActivity(), "Title too short.", Toast.LENGTH_LONG);
toast.show(); toast.show();
return; return;
} }
//title too long //title too long
if (newTitle.getText().length() > 20) { if (newTitle.getText().length() > 20) {
Toast toast = Toast.makeText(getActivity(), "Title too long.\n Use up to 20 notes.", Toast.LENGTH_LONG); Toast toast = Toast.makeText(getActivity(), "Title too long.\n Use up to 20 notes.", Toast.LENGTH_LONG);
toast.show(); toast.show();
return; return;
} }
//volley post //volley post
final JSONObject noteJson = new JSONObject(); final JSONObject noteJson = new JSONObject();
try { try {
//TODO need to get owner id from login screen //TODO need to get owner id from login screen
noteJson.put("owner_id", userId); noteJson.put("owner_id", userId);
noteJson.put("title", newTitle.getText()); noteJson.put("title", newTitle.getText());
noteJson.put("lat", gpsUtils.getLatitude()); noteJson.put("lat", gpsUtils.getLatitude());
noteJson.put("lng", gpsUtils.getLongitude()); noteJson.put("lng", gpsUtils.getLongitude());
noteJson.put("address", gpsUtils.getAddress()); noteJson.put("address", gpsUtils.getAddress());
noteJson.put("body", newBody.getText()); noteJson.put("body", newBody.getText());
noteJson.put("is_public", permissionSwitch.isChecked()); noteJson.put("is_public", permissionSwitch.isChecked());
// noteJson.put("tags",); // noteJson.put("tags",);
Log.d(TAG, "Json: " + noteJson.toString()); Log.d(TAG, "Json: " + noteJson.toString());
} catch (Exception e) { } catch (Exception e) {
Log.d(TAG, "saveBtn: " + e.toString()); Log.d(TAG, "saveBtn: " + e.toString());
} }
//send request and close dialog
VolleyUtilSingleton.getInstance(getActivity()).post(BASE_URL + "/note/upsert", noteJson, newNoteSuccessListener, Utils.genericErrorListener);
dialog.dismiss();
}
});
//change text of switch according to state.
permissionSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
permissionSwitch.setText(R.string.nvf_public_label);
else
permissionSwitch.setText(R.string.nvf_private_label);
}
});
//send request and close dialog
VolleyUtilSingleton.getInstance(getActivity()).post(BASE_URL + "/note/upsert", noteJson, newNoteSuccessListener, Utils.genericErrorListener);
dialog.dismiss();
} }
}; });
//response listener for adding new note
Response.Listener<JSONObject> newNoteSuccessListener = new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG, "newNoteSuccess: response - " + response.toString());
try {
Date time = new Date();
JSONObject noteObject = response.getJSONObject("note");
time.setTime(noteObject.getLong("created_at"));
addNoteFromJsonObj(noteObject, time);
noteList.setAdapter(noteListAdapter);
} catch (Exception e) {
Log.e(TAG, "newNoteSuccess:" + e.getMessage());
}
//change text of switch according to state.
permissionSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
permissionSwitch.setText(R.string.nvf_public_label);
else
permissionSwitch.setText(R.string.nvf_private_label);
} }
}; });
}
};
//response listener for adding new note
Response.Listener<JSONObject> newNoteSuccessListener = new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG, "newNoteSuccess: response - " + response.toString());
try {
Date time = new Date();
JSONObject noteObject = response.getJSONObject("note");
time.setTime(noteObject.getLong("created_at"));
addNoteFromJsonObj(noteObject, time);
noteList.setAdapter(noteListAdapter);
} catch (Exception e) {
Log.e(TAG, "newNoteSuccess:" + e.getMessage());
}
}
};
// //response Error listener for adding new note // //response Error listener for adding new note
@ -307,29 +310,30 @@ public class PersonalFragment extends Fragment {
// }; // };
//response listener for getting all user notes //response listener for getting all user notes
Response.Listener<JSONObject> getNotesSuccessListener = new Response.Listener<JSONObject>() { Response.Listener<JSONObject> getNotesSuccessListener = new Response.Listener<JSONObject>() {
@Override @Override
public void onResponse(JSONObject response) { public void onResponse(JSONObject response) {
Log.d(TAG, "getNotesSuccessListener: " + response.toString()); Log.d(TAG, "getNotesSuccessListener: " + response.toString());
Utils.dismissLoadingDialog(); Utils.dismissLoadingDialog();
try { try {
//need to get all notes and add to listOfNotes //need to get all notes and add to listOfNotes
JSONArray noteObjectsArray = response.getJSONArray("notes"); JSONArray noteObjectsArray = response.getJSONArray("notes");
Date time = new Date(); activity.getUser().setNumber_of_notes(noteObjectsArray.length());
for (int i = 0; i < noteObjectsArray.length(); i++) { Date time = new Date();
JSONObject noteObject = noteObjectsArray.getJSONObject(i); for (int i = 0; i < noteObjectsArray.length(); i++) {
time.setTime(noteObject.getLong("created_at")); JSONObject noteObject = noteObjectsArray.getJSONObject(i);
time.setTime(noteObject.getLong("created_at"));
addNoteFromJsonObj(noteObject, time);
}
noteList.setAdapter(noteListAdapter);
} catch (Exception e) {
Log.e(TAG, "newNoteSuccess:" + e.getMessage());
}
addNoteFromJsonObj(noteObject, time);
} }
}; noteList.setAdapter(noteListAdapter);
} catch (Exception e) {
Log.e(TAG, "newNoteSuccess:" + e.getMessage());
}
}
};
// //response ErrorListener for getting all user notes // //response ErrorListener for getting all user notes
@ -352,55 +356,55 @@ public class PersonalFragment extends Fragment {
// }; // };
private ArrayList<String> jsonArrayToStringArray(JSONArray jArray) { private ArrayList<String> jsonArrayToStringArray(JSONArray jArray) {
ArrayList<String> stringArray = new ArrayList<String>(); ArrayList<String> stringArray = new ArrayList<String>();
for (int i = 0, count = jArray.length(); i < count; i++) { for (int i = 0, count = jArray.length(); i < count; i++) {
try { try {
JSONObject jsonObject = jArray.getJSONObject(i); JSONObject jsonObject = jArray.getJSONObject(i);
stringArray.add(jsonObject.toString()); stringArray.add(jsonObject.toString());
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); e.printStackTrace();
} }
}
return stringArray;
} }
return stringArray;
}
private void addNoteFromJsonObj(JSONObject noteObject, Date time) throws JSONException { private void addNoteFromJsonObj(JSONObject noteObject, Date time) throws JSONException {
Note addNote = new Note( Note addNote = new Note(
noteObject.getString("id"), noteObject.getString("id"),
Float.parseFloat(noteObject.getJSONObject("location").getString("lat")), Float.parseFloat(noteObject.getJSONObject("location").getString("lat")),
Float.parseFloat(noteObject.getJSONObject("location").getString("lng")), Float.parseFloat(noteObject.getJSONObject("location").getString("lng")),
noteObject.getJSONObject("location").getString("address"), noteObject.getJSONObject("location").getString("address"),
noteObject.getString("title"), noteObject.getString("title"),
noteObject.getString("body"), noteObject.getString("body"),
time.toString(), time.toString(),
noteObject.getBoolean("is_public"), noteObject.getBoolean("is_public"),
noteObject.getInt("likes"), noteObject.getInt("likes"),
noteObject.getString("avatar"), noteObject.getString("avatar"),
noteObject.getString("owner_id"), noteObject.getString("owner_id"),
jsonArrayToStringArray(noteObject.getJSONArray("tags")) jsonArrayToStringArray(noteObject.getJSONArray("tags"))
); );
listOfNotes.add(addNote); listOfNotes.add(addNote);
} }
// click on listView item // click on listView item
class ItemClickedListener implements AdapterView.OnItemClickListener { class ItemClickedListener implements AdapterView.OnItemClickListener {
@Override @Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) { public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
//create and configure dialog //create and configure dialog
final Note note = listOfNotes.get(position); final Note note = listOfNotes.get(position);
final Dialog noteViewDialog = new Dialog(getActivity()); final Dialog noteViewDialog = new Dialog(getActivity());
noteViewDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); noteViewDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
noteViewDialog.setContentView(R.layout.note_display_full); noteViewDialog.setContentView(R.layout.note_display_full);
// noteViewDialog.setTitle("You wrote..."); // noteViewDialog.setTitle("You wrote...");
WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(noteViewDialog.getWindow().getAttributes()); lp.copyFrom(noteViewDialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.MATCH_PARENT; lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.MATCH_PARENT; lp.height = WindowManager.LayoutParams.MATCH_PARENT;
noteViewDialog.show(); noteViewDialog.show();
// dialog.getWindow().setAttributes(lp); // dialog.getWindow().setAttributes(lp);

View file

@ -1,57 +1,56 @@
package com.android_app.matan.ara.sagi.thesocialnotework; package com.android_app.matan.ara.sagi.thesocialnotework;
import android.*;
import android.Manifest; import android.Manifest;
import android.app.Activity; import android.app.Activity;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.graphics.Bitmap; import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri; import android.net.Uri;
import android.os.Bundle; import android.os.Bundle;
import android.provider.MediaStore; import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat; import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment; import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.Log; import android.util.Log;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.Button; import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView; import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
public class SettingsFragment extends Fragment { import com.android.volley.Response;
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2"; import org.json.JSONException;
private static final String TAG = "Settings" ; import org.json.JSONObject;
private static final int REQUEST_IMAGE_CAPTURE = 1;
private Button cameraBtn; import java.io.ByteArrayOutputStream;
import java.io.File;
public class SettingsFragment extends Fragment implements View.OnClickListener, TextWatcher {
private static final String TAG = "[TSN/Settings]" ;
private MainActivity parent;
private ImageButton cameraBtn;
private ImageView avatarImage; private ImageView avatarImage;
// private OnFragmentInteractionListener mListener; private EditText txt_username, txt_password, txt_email;
private Uri currentImgUri;
private TextView lbl_num_of_notes, lbl_num_of_liked;
private User user;
private Button btn_save;
public SettingsFragment() { public SettingsFragment() {
// Required empty public constructor // Required empty public constructor
} }
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment SettingsFragment.
*/
// TODO: Rename and change types and number of parameters
public static SettingsFragment newInstance(String param1, String param2) {
SettingsFragment fragment = new SettingsFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
@ -63,19 +62,40 @@ public class SettingsFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) { Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_settings, container, false); View view = inflater.inflate(R.layout.fragment_settings, container, false);
this.parent = (MainActivity)getActivity();
Utils.showLoadingDialog(parent, "Just a sec...", "");
this.user = parent.getUser();
Log.d(TAG, "onCreateView: "+user.toString());
this.cameraBtn = (ImageButton) view.findViewById(R.id.btn_camera);
this.cameraBtn.setOnClickListener(this);
this.avatarImage = (ImageView) view.findViewById(R.id.settings_userAvater_iamgeView);
this.txt_email = (EditText)view.findViewById(R.id.txt_email);
this.txt_email.addTextChangedListener(this);
this.txt_password = (EditText)view.findViewById(R.id.txt_password);
this.txt_password.addTextChangedListener(this);
this.txt_username = (EditText)view.findViewById(R.id.txt_username);
this.lbl_num_of_notes = (TextView)view.findViewById(R.id.lbl_num_of_notes);
this.lbl_num_of_liked = (TextView)view.findViewById(R.id.lbl_num_of_liked);
this.btn_save = (Button)view.findViewById(R.id.btn_save);
this.btn_save.setOnClickListener(this);
cameraBtn = (Button) view.findViewById(R.id.camera_button); this.txt_username.setEnabled(false);
cameraBtn.setOnClickListener(cameraBtnListener);
avatarImage = (ImageView) view.findViewById(R.id.settings_userAvater_iamgeView); //Populate The data
Utils.URLtoImageView(avatarImage, user.getAvatar());
this.txt_username.setText(""+user.getUsername());
this.txt_password.setText(""+user.getPassword());
Log.d(TAG, "onCreateView: The FUCKING EMAIL IS --------------->>>" + user.getEmail());
this.txt_email.setText(""+user.getEmail());
this.lbl_num_of_notes.setText(""+user.getNumber_of_notes()); //TODO
this.lbl_num_of_liked.setText(""+user.getLiked_notes().size());
Utils.dismissLoadingDialog();
return view; return view;
} }
// // TODO: Rename method, update argument and hook method into UI event
// public void onButtonPressed(Uri uri) {
// if (mListener != null) {
// mListener.onFragmentInteraction(uri);
// }
// }
@Override @Override
public void onAttach(Context context) { public void onAttach(Context context) {
@ -84,67 +104,120 @@ public class SettingsFragment extends Fragment {
@Override @Override
public void onDetach() { public void onDetach() {
super.onDetach(); super.onDetach();
}
// /**
// * This interface must be implemented by activities that contain this
// * fragment to allow an interaction in this fragment to be communicated
// * to the activity and potentially other fragments contained in that
// * activity.
// * <p>
// * See the Android Training lesson <a href=
// * "http://developer.android.com/training/basics/fragments/communicating.html"
// * >Communicating with Other Fragments</a> for more information.
// */
// public interface OnFragmentInteractionListener {
// // TODO: Update argument type and name
// void onFragmentInteraction(Uri uri);
// }
private View.OnClickListener cameraBtnListener = new View.OnClickListener()
{
public void onClick(View v)
{
if (ActivityCompat.checkSelfPermission((MainActivity) getActivity(),
Manifest.permission.CAMERA)
== PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "in camera Button");
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
else{
Toast.makeText(getActivity(), "No Location Permissions granted.\n\"An App is nothing without its permissions\"", Toast.LENGTH_LONG).show();
}
}
};
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(TAG, "on activity result");
Log.d(TAG, "requestCode: "+requestCode);
Log.d(TAG, "resultCode: "+resultCode);
Log.d(TAG, "Activity.RESULT_OK: "+Activity.RESULT_OK);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) {
Log.d(TAG, "inside if");
Bundle extras = data.getExtras();
Bitmap imageBitmap= (Bitmap) extras.get("data");
Log.d(TAG, "bitmap: "+imageBitmap.toString());
// Bitmap imageBitmap = (Bitmap) extras.get("data");
avatarImage.setImageBitmap(imageBitmap);
}
} }
@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:
user.updateUser(parent);
break;
}
}
/**
* creates a new camera intent
* @param v
*/
protected void openCamera(View v) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
createDir();
Long currentImageTimeStamp = System.currentTimeMillis();
String timeStamp = Long.toString(currentImageTimeStamp);
File photo = new File(Utils.PHOTOS_DIR_PATH, timeStamp + ".jpg");
currentImgUri = Uri.fromFile(photo);
intent.putExtra(MediaStore.EXTRA_OUTPUT, currentImgUri);
Log.d(TAG, "openCamera: Image URI is: " + currentImgUri);
startActivityForResult(intent, 1);
}
protected void createDir() {
File f = new File(Utils.PHOTOS_DIR_PATH);
f.mkdirs();
}
@Override
public void onActivityResult(int requestCode, int resaultCode, Intent intent) {
super.onActivityResult(requestCode, requestCode, intent);
if (resaultCode == Activity.RESULT_OK) {
if (currentImgUri != null) {
saveImage();
Log.d(TAG, "onActivityResult: Image Capured!! - Now Upload That Shit!!");
} else { //capturing failed
Toast.makeText(getActivity(), "Failed to Get Photo, Try Again", Toast.LENGTH_LONG).show();
Log.e(TAG, "onActivityResult: Image URI returned as NULL - Orientation Fail");
}
} else {
Log.i(TAG, "onActivityResult: User Canceled Image taking");
}
}
private void saveImage() {
Utils.showLoadingDialog(parent, "Saving Image...", "This Can Take a while");
File myFile = new File(currentImgUri.getPath());
JSONObject payload = new JSONObject();
try {
payload.put("image", ImageToBase64(myFile.getAbsolutePath()));
} catch (JSONException e) {
e.printStackTrace();
Utils.dismissLoadingDialog();
Toast.makeText(parent, "Failed to upload image.. Try Again", Toast.LENGTH_LONG).show();
}
VolleyUtilSingleton.getInstance(parent).post(Utils.BASE_URL + Utils.UPLOAD_IMAGE_PATH, payload, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG, "onResponse: "+response.toString());
try {
user.setAvatar(response.getString("image_url"));
//Populate The data
Utils.URLtoImageView(avatarImage, user.getAvatar());
user.updateUser(parent);
} catch (JSONException e) {
e.printStackTrace();
}
Utils.dismissLoadingDialog();
}
}, Utils.genericErrorListener);
}
private String ImageToBase64(String filePath){
Bitmap bm = BitmapFactory.decodeFile(filePath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 50, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
Log.d(TAG, "ImageToBase64: "+b.length/1000);
return Base64.encodeToString(b, Base64.DEFAULT);
}
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
user.setEmail(txt_email.getText().toString());
user.setPassword(txt_password.getText().toString());
}
@Override
public void afterTextChanged(Editable editable) {
}
} }

View file

@ -1,16 +1,11 @@
package com.android_app.matan.ara.sagi.thesocialnotework; package com.android_app.matan.ara.sagi.thesocialnotework;
import android.content.Context;
import android.content.Intent; 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.support.v7.graphics.drawable.DrawableWrapper;
import android.util.Log;
import android.view.Window; import android.view.Window;
import android.view.WindowManager; import android.view.WindowManager;
import android.widget.ImageView; import android.widget.ImageView;
import android.widget.LinearLayout;
import java.util.Random; import java.util.Random;
@ -18,7 +13,6 @@ public class SplashActivity extends AppCompatActivity {
private ImageView background; private ImageView background;
private int timerDelay = 3500; private int timerDelay = 3500;
private final String TAG = "Splash Screen Activity";
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
@ -33,8 +27,8 @@ public class SplashActivity extends AppCompatActivity {
} else { } else {
background.setImageDrawable( getResources().getDrawable(rand_splash())); background.setImageDrawable( getResources().getDrawable(rand_splash()));
} }
SharedPreferences sharedPref = this.getSharedPreferences(MainActivity.LOCAL_DATA_TSN, Context.MODE_PRIVATE);
final String userData = sharedPref.getString("UserData", null); final String userData = Utils.getUserFromSharedPrefs(this);
Thread timerThread = new Thread(){ Thread timerThread = new Thread(){
public void run(){ public void run(){

View file

@ -1,6 +1,15 @@
package com.android_app.matan.ara.sagi.thesocialnotework; package com.android_app.matan.ara.sagi.thesocialnotework;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log; import android.util.Log;
import android.widget.Toast;
import com.android.volley.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Vector; import java.util.Vector;
@ -21,9 +30,13 @@ public class User {
public static final String TAG = "[TSN/User]", ATTARS_DELIMETER="||" , LIKED_NOTES_DELIMETER="|"; public static final String TAG = "[TSN/User]", ATTARS_DELIMETER="||" , LIKED_NOTES_DELIMETER="|";
protected String id, password, email, avatar, username; protected String id, password, email, avatar, username;
protected Vector<String> liked_notes; protected Vector<String> liked_notes;
protected int number_of_notes;
protected User self;
public User(String serializedUserData){ public User(String serializedUserData){
self = this;
liked_notes = new Vector<>(); liked_notes = new Vector<>();
number_of_notes = 0;
String[] array = serializedUserData.split("\\|\\|"); String[] array = serializedUserData.split("\\|\\|");
for (int i = 0 ; i < array.length ; i ++){ for (int i = 0 ; i < array.length ; i ++){
switch (i){ switch (i){
@ -52,6 +65,14 @@ public class User {
} }
} }
public int getNumber_of_notes() {
return number_of_notes;
}
public void setNumber_of_notes(int number_of_notes) {
this.number_of_notes = number_of_notes;
}
public String getId() { public String getId() {
return id; return id;
} }
@ -119,7 +140,7 @@ public class User {
for (int i = 0; i < liked_notes.size(); i++) { for (int i = 0; i < liked_notes.size(); i++) {
result += liked_notes.get(i); result += liked_notes.get(i);
if(i != liked_notes.size() - 1){ if(i != liked_notes.size() - 1){
result+=";"; result+=User.LIKED_NOTES_DELIMETER;
} }
} }
return result; return result;
@ -129,6 +150,46 @@ public class User {
return "Id: "+id+" UserName: " + username +" Password: " +password +" email: " + email+ " Avatar: " +avatar+" Liked Notes: "+liked_notes.toString(); return "Id: "+id+" UserName: " + username +" Password: " +password +" email: " + email+ " Avatar: " +avatar+" Liked Notes: "+liked_notes.toString();
} }
public void updateUser(final MainActivity activity){
Log.d(TAG, "updateUser: ================================");
VolleyUtilSingleton.getInstance(activity).post(Utils.BASE_URL + "/user/upsert", this.toJSON(), new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
if(response.get("status").equals("OK")){
Log.d(TAG, "onResponse: In OKOKOKOK");
activity.updateNavAvatar();
Utils.updateUserSharedPref(self.Serialise());
activity.updateNavAvatar();
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}, Utils.genericErrorListener);
}
public JSONObject toJSON() {
JSONObject json = new JSONObject();
JSONArray liked = new JSONArray();
for (int i = 0; i < liked_notes.size(); i++) {
liked.put(liked_notes.get(i));
}
try {
json.put("id", this.id);
json.put("password", this.password);
json.put("username", this.username);
json.put("email", this.email);
json.put("avatar", this.avatar);
json.put("liked_notes_id", liked);
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
} }

View file

@ -2,6 +2,7 @@ package com.android_app.matan.ara.sagi.thesocialnotework;
import android.app.ProgressDialog; import android.app.ProgressDialog;
import android.content.Context; import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap; import android.graphics.Bitmap;
import android.graphics.BitmapFactory; import android.graphics.BitmapFactory;
import android.graphics.Canvas; import android.graphics.Canvas;
@ -11,6 +12,7 @@ import android.graphics.PorterDuffXfermode;
import android.graphics.Rect; import android.graphics.Rect;
import android.graphics.RectF; import android.graphics.RectF;
import android.os.AsyncTask; import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log; import android.util.Log;
import android.widget.ImageView; import android.widget.ImageView;
@ -37,11 +39,14 @@ import java.util.HashMap;
public class Utils { public class Utils {
public static final String TAG = "Utils"; public static final String TAG = "Utils";
public static final String BASE_URL = "http://thesocialnotework-api.appspot.com/api"; public static final String BASE_URL = "http://thesocialnotework-api.appspot.com/api", UPLOAD_IMAGE_PATH="/file/upload";
public static ProgressDialog progress; public static ProgressDialog progress;
private static HashMap<String, Bitmap> bitmapHash = new HashMap<>(); private static HashMap<String, Bitmap> bitmapHash = new HashMap<>();
public static final String PHOTOS_DIR_PATH = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/TheSocialNotework/";
private static boolean mLocationPermission = false; private static boolean mLocationPermission = false;
private static boolean mCameraPermission = false; private static boolean mCameraPermission = false;
private static SharedPreferences prefs;
public static Bitmap getBitmapFromURL(String url) { public static Bitmap getBitmapFromURL(String url) {
@ -74,6 +79,7 @@ public class Utils {
public void onErrorResponse(VolleyError error) { public void onErrorResponse(VolleyError error) {
Log.d(TAG, "genericErrorListener"); Log.d(TAG, "genericErrorListener");
error.printStackTrace(); error.printStackTrace();
Utils.dismissLoadingDialog();
} }
}; };
@ -142,7 +148,8 @@ public class Utils {
private static class setUserAvatar extends AsyncTask<Void, Void, Bitmap> { private static class setUserAvatar extends AsyncTask<Void, Void, Bitmap> {
private ImageView iv; private ImageView iv;
private String url; private String url;
public setUserAvatar(ImageView imageView, String url){
public setUserAvatar(ImageView imageView, String url) {
this.iv = imageView; this.iv = imageView;
this.url = url; this.url = url;
} }
@ -151,14 +158,13 @@ public class Utils {
protected Bitmap doInBackground(Void... v) { protected Bitmap doInBackground(Void... v) {
// Bitmap b; // Bitmap b;
return Utils.getBitmapFromURL(url); return Utils.getBitmapFromURL(url);
} }
@Override @Override
protected void onPostExecute(Bitmap b){ protected void onPostExecute(Bitmap b) {
iv.setImageBitmap(b); iv.setImageBitmap(b);
//getRoundedCornerBitmap(b, 20);
} }
} }
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels) { public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels) {
@ -204,6 +210,28 @@ public class Utils {
return mLocationPermission; return mLocationPermission;
} }
public static String getUserFromSharedPrefs(Context contexst){
if(prefs == null){
prefs = contexst.getSharedPreferences(MainActivity.LOCAL_DATA_TSN, Context.MODE_PRIVATE);
}
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();
}
} }

View file

@ -1,20 +1,138 @@
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_height="match_parent"
tools:context="com.android_app.matan.ara.sagi.thesocialnotework.SettingsFragment"> tools:context="com.android_app.matan.ara.sagi.thesocialnotework.SettingsFragment">
<Button <LinearLayout
android:layout_width="wrap_content" android:orientation="vertical"
android:layout_height="wrap_content" android:layout_width="match_parent"
android:text="Change" android:layout_height="match_parent"
android:id="@+id/camera_button" android:weightSum="1"
android:layout_gravity="center"/> android:padding="10dp"
android:layout_marginTop="15dp">
<ImageView <LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.26">
<LinearLayout
android:orientation="vertical"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.65">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="@+id/txt_username"
android:hint="Username" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="@+id/txt_password"
android:hint="Password" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:id="@+id/txt_email"
android:hint="Email"
android:inputType="none|text" />
</LinearLayout>
<RelativeLayout
android:layout_width="90dp"
android:layout_height="90dp">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/settings_userAvater_iamgeView"
android:layout_gravity="top|center_horizontal"
android:src="@drawable/default_avatar" />
<ImageButton
android:layout_width="45dp"
android:layout_height="45dp"
android:id="@+id/btn_camera"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:background="@android:color/transparent"
android:src="@drawable/ic_menu_camera"
android:tint="#7b7b7b" />
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_weight="0.14"
android:weightSum="1">
<TextView
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:id="@+id/settings_userAvater_iamgeView" android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_gravity="center_horizontal|bottom" /> android:text="Nuber Of Notes: "
</FrameLayout> android:id="@+id/textView3"
android:textStyle="bold"
android:layout_weight="0.25" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="15"
android:id="@+id/lbl_num_of_notes"
android:layout_weight="0.25" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Notes I Liked:"
android:id="@+id/textView4"
android:textStyle="bold"
android:layout_weight="0.25" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="30"
android:id="@+id/lbl_num_of_liked"
android:layout_weight="0.25" />
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="126dp"
android:layout_gravity="right"
android:layout_weight="0.07">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save Changes"
android:id="@+id/btn_save"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_marginEnd="29dp" />
</RelativeLayout>
</LinearLayout>
</RelativeLayout>