From 0448deb35ddc005a76362933a1870cc6d5b57f9d Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Mon, 24 Oct 2016 12:29:23 +0200 Subject: [PATCH 001/103] Added comments to make it easier to understand The process of adding comments to code that I read helps me make sense of it even if I never read them again. Comments that are just a question mark are place holders to return to when I have a better idea of what that piece of code is for. --- .../src/main/java/com/Pau/ImapNotes2/ImapNotes2.java | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/ImapNotes2.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/ImapNotes2.java index ba693bf2..1ade6a26 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/ImapNotes2.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/ImapNotes2.java @@ -9,6 +9,7 @@ import android.app.Application; import android.content.Context; + public class ImapNotes2 extends Application { private ConfigurationFile thisSessionConfigurationFile; @@ -16,35 +17,44 @@ public class ImapNotes2 extends Application { private ArrayList noteList; private static Context context; + // Called when starting the application. public void onCreate(){ super.onCreate(); + // Save the context in a static so that it is easy toi access everywhere. ImapNotes2.context = getApplicationContext(); } + // Simplify access to the application context. public static Context getAppContext() { return ImapNotes2.context; } + // ? public void SetConfigurationFile(ConfigurationFile currentSettings){ this.thisSessionConfigurationFile = currentSettings; } + // ? public ConfigurationFile GetConfigurationFile(){ return this.thisSessionConfigurationFile; } + // ? public void SetImaper(Imaper currentImaper){ this.thisSessionImapFolder = currentImaper; } + // ? public Imaper GetImaper(){ return this.thisSessionImapFolder; } + // ? public void SetNotesList(ArrayList currentNotesList){ this.noteList = currentNotesList; } + // ? public ArrayList GetNotesList(){ return this.noteList; } From bb4e96e7ca56d01a1b30080c563957c4c7b3b30e Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Mon, 24 Oct 2016 12:47:31 +0200 Subject: [PATCH 002/103] Added comments. --- .../ImapNotes2/Data/ConfigurationFile.java | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFile.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFile.java index b4ec7b09..f6e7d6f1 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFile.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFile.java @@ -16,30 +16,46 @@ public class ConfigurationFile { + // Why do we need a copy of the application context reference? + // It is not necessary in the actual constructor only in the Clear + // method which presumably could get it from the getContext static method. private Context applicationContext; + // For logging. private static final String TAG = "IN_ConfigurationFile"; + // The account name is the concatenation of the username and server. private String accountname; + // User name on the IMAP server. private String username; private String password; + // Address of the IMAP server private String server; + // Port number. private String portnum; + // TLS, etc. private String security; + // ? private String usesticky; + // The name of the IMAP folder to be used. private String imapfolder; public ConfigurationFile(Context myContext){ + // Save the context reference. It seems that this is probably unnecessary. this.applicationContext = myContext; try { Document fileToLoad = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse( new File(this.applicationContext.getFilesDir()+"/ImapNotes2.conf")); + // The expressions ending in getNodeValue shoule be placed in a function + // to reduce clutter and improve maintainability. this.username = this.LoadItemFromXML(fileToLoad, "username").item(0).getChildNodes().item(0).getNodeValue(); this.password = this.LoadItemFromXML(fileToLoad, "password").item(0).getChildNodes().item(0).getNodeValue(); this.server = this.LoadItemFromXML(fileToLoad, "server").item(0).getChildNodes().item(0).getNodeValue(); this.imapfolder = this.LoadItemFromXML(fileToLoad, "imapfolder").item(0).getChildNodes().item(0).getNodeValue(); this.accountname = this.username + "@" + this.server; + // All of these can be simplified by initializing the fields to the default values and + // only setting when the value exists in the file. if (this.LoadItemFromXML(fileToLoad, "portnum").getLength() == 0) // portnum option doesn't exist this.portnum = ""; @@ -58,6 +74,8 @@ public ConfigurationFile(Context myContext){ //Log.d(TAG, "conf file present, we read data"); } catch (Exception e) { + // This catch should be turned into a simple if then and the catch + // reserved for conditions that cannot be checked for. //Log.d(TAG, "Conf file absent, go to the exception that initializes variables"); this.accountname = ""; this.username = ""; @@ -137,6 +155,9 @@ public void Clear(){ this.imapfolder = null; } + // This function could take the context as an argument. + // In addition the name of the file should be a named constant + // because it is used elewhere. public void SaveConfigurationToXML() throws IllegalArgumentException, IllegalStateException, IOException{ FileOutputStream configurationFile = this.applicationContext.openFileOutput("ImapNotes2.conf", Context.MODE_PRIVATE); XmlSerializer serializer = Xml.newSerializer(); From f3f6a0ab6734d2eca00864437f57981dfad2e72d Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Wed, 26 Oct 2016 20:43:49 +0200 Subject: [PATCH 003/103] Reformatted all files to get consistent indentation, etc. --- ImapNote2/src/main/AndroidManifest.xml | 150 +++--- .../AccontConfigurationActivity.java | 349 -------------- .../AccountConfigurationActivity.java | 355 ++++++++++++++ .../ImapNotes2/Data/ConfigurationFile.java | 180 ++++--- .../ImapNotes2/Data/ImapNotes2Account.java | 72 +-- .../java/com/Pau/ImapNotes2/Data/NotesDb.java | 157 +++--- .../java/com/Pau/ImapNotes2/ImapNotes2.java | 96 ++-- .../java/com/Pau/ImapNotes2/Listactivity.java | 454 +++++++++--------- .../ImapNotes2/Miscs/ImapNotes2Result.java | 26 +- .../Miscs/ImapNotesAuthenticatorService.java | 159 +++--- .../java/com/Pau/ImapNotes2/Miscs/Imaper.java | 279 +++++------ .../com/Pau/ImapNotes2/Miscs/OneNote.java | 106 ++-- .../java/com/Pau/ImapNotes2/Miscs/Sticky.java | 78 +-- .../com/Pau/ImapNotes2/Miscs/SyncThread.java | 34 +- .../Pau/ImapNotes2/Miscs/UpdateThread.java | 137 +++--- .../com/Pau/ImapNotes2/NewNoteActivity.java | 72 +-- .../Pau/ImapNotes2/NoteDetailActivity.java | 266 +++++----- .../com/Pau/ImapNotes2/NotesListAdapter.java | 84 ++-- .../src/main/res/layout/account_selection.xml | 354 +++++++------- ImapNote2/src/main/res/layout/main.xml | 12 +- ImapNote2/src/main/res/layout/new_note.xml | 12 +- ImapNote2/src/main/res/layout/note_detail.xml | 41 +- .../src/main/res/layout/note_element.xml | 45 +- ImapNote2/src/main/res/menu/detail.xml | 54 ++- ImapNote2/src/main/res/menu/list.xml | 37 +- ImapNote2/src/main/res/menu/newnote.xml | 8 +- ImapNote2/src/main/res/values-v14/styles.xml | 29 +- ImapNote2/src/main/res/values/strings.xml | 5 + ImapNote2/src/main/res/values/styles.xml | 25 +- ImapNote2/src/main/res/xml/authenticator.xml | 9 +- ImapNote2/src/main/res/xml/searchable.xml | 4 +- ImapNote2/src/main/res/xml/syncadapter.xml | 7 +- build.gradle | 2 +- gradle/wrapper/gradle-wrapper.properties | 4 +- 34 files changed, 1872 insertions(+), 1830 deletions(-) delete mode 100644 ImapNote2/src/main/java/com/Pau/ImapNotes2/AccontConfigurationActivity.java create mode 100644 ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java diff --git a/ImapNote2/src/main/AndroidManifest.xml b/ImapNote2/src/main/AndroidManifest.xml index 9680deb1..798abb8d 100644 --- a/ImapNote2/src/main/AndroidManifest.xml +++ b/ImapNote2/src/main/AndroidManifest.xml @@ -1,75 +1,93 @@ - - - - - - - - - - - - + - - - - - - - - - - + - - - + + + + + + + + - - - + - - - + + + + + + + + - - - - - - + + - + + + - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccontConfigurationActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccontConfigurationActivity.java deleted file mode 100644 index fcd54633..00000000 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccontConfigurationActivity.java +++ /dev/null @@ -1,349 +0,0 @@ -package com.Pau.ImapNotes2; - -import java.util.ArrayList; -import java.util.List; - -import com.Pau.ImapNotes2.Data.ConfigurationFile; -import com.Pau.ImapNotes2.Data.ImapNotes2Account; -import com.Pau.ImapNotes2.Miscs.ImapNotes2Result; -import com.Pau.ImapNotes2.Miscs.Imaper; - -import android.accounts.Account; -import android.accounts.AccountAuthenticatorActivity; -import android.accounts.AccountManager; -import android.app.ProgressDialog; -import android.content.ContentResolver; -import android.os.AsyncTask; -import android.os.Bundle; -import android.os.CountDownTimer; -import android.support.v4.app.NavUtils; -import android.util.Log; -import android.view.Menu; -import android.view.MenuItem; -import android.view.View; -import android.view.View.OnClickListener; -import android.view.WindowManager; -import android.widget.AdapterView; -import android.widget.AdapterView.OnItemSelectedListener; -import android.widget.ArrayAdapter; -import android.widget.Button; -import android.widget.CheckBox; -import android.widget.LinearLayout; -import android.widget.Spinner; -import android.widget.TextView; -import android.widget.Toast; - -public class AccontConfigurationActivity extends AccountAuthenticatorActivity implements OnItemSelectedListener{ - public static final int TO_REFRESH = 999; - public static final String AUTHORITY = "com.Pau.ImapNotes2.provider"; - private static final String TAG = "AccontConfigurationActivity"; - - private Imaper imapFolder; - - private TextView accountnameTextView; - private TextView usernameTextView; - private TextView passwordTextView; - private TextView serverTextView; - private TextView portnumTextView; - private TextView syncintervalTextView; - private TextView folderTextView; - private CheckBox stickyCheckBox; - private Spinner securitySpinner; - private ImapNotes2Account imapNotes2Account; - private String security; - private int security_i; - private String action; - private String accountname; - private ConfigurationFile settings; - private static Account myAccount = null; - private static AccountManager accountManager; - - private OnClickListener clickListenerLogin = new View.OnClickListener() { - @Override - public void onClick(View v) { - // Click on Login Button - if (((String) accountnameTextView.getText().toString()).contains("'")) { - // Single quotation marks are not allowed in accountname - Toast.makeText(getApplicationContext(), "Quotation marks are not allowed in accountname", - Toast.LENGTH_LONG).show(); - } else { - DoLogin(v); - } - } - }; - - private OnClickListener clickListenerEdit = new View.OnClickListener() { - @Override - public void onClick(View v) { - // Click on Edit Button - if (((String) accountnameTextView.getText().toString()).contains("'")) { - // Single quotation marks are not allowed in accountname - Toast.makeText(getApplicationContext(), "Quotation marks are not allowed in accountname", - Toast.LENGTH_LONG).show(); - } else { - DoLogin(v); - } - } - }; - - private OnClickListener clickListenerRemove = new View.OnClickListener() { - @Override - public void onClick(View v) { - // Clic on Remove Button - accountManager.removeAccount(myAccount, null, null); - Toast.makeText(getApplicationContext(), "Account has been removed", - Toast.LENGTH_LONG).show(); - finish();//finishing activity - } - }; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.account_selection); - getActionBar().setDisplayHomeAsUpEnabled(true); - this.accountnameTextView = (TextView)(findViewById(R.id.accountnameEdit)); - this.usernameTextView = (TextView)findViewById(R.id.usernameEdit); - this.passwordTextView = (TextView)findViewById(R.id.passwordEdit); - this.serverTextView = (TextView)findViewById(R.id.serverEdit); - this.portnumTextView = (TextView)findViewById(R.id.portnumEdit); - this.syncintervalTextView = (TextView)findViewById(R.id.syncintervalEdit); - this.folderTextView = (TextView)findViewById(R.id.folderEdit); - this.stickyCheckBox = (CheckBox)findViewById(R.id.stickyCheckBox); - - securitySpinner = (Spinner) findViewById(R.id.securitySpinner); - List list = new ArrayList(); - list.add("None"); - list.add("SSL/TLS"); - list.add("SSL/TLS (accept all certificates)"); - list.add("STARTTLS"); - list.add("STARTTLS (accept all certificates)"); - ArrayAdapter dataAdapter = new ArrayAdapter - (this, android.R.layout.simple_spinner_item,list); - dataAdapter.setDropDownViewResource - (android.R.layout.simple_spinner_dropdown_item); - securitySpinner.setAdapter(dataAdapter); - // Spinner item selection Listener - securitySpinner.setOnItemSelectedListener(this); - - imapNotes2Account = new ImapNotes2Account(); - this.imapFolder = ((ImapNotes2)getApplicationContext()).GetImaper(); - this.settings = new ConfigurationFile(this.getApplicationContext()); - - Bundle extras = getIntent().getExtras(); - if (extras != null) { - if (extras.containsKey("action")) { - action = extras.getString("action"); - } - if (extras.containsKey("accountname")) { - accountname = extras.getString("accountname"); - } - } - - if (this.settings != null) { - this.accountnameTextView.setText(this.settings.GetAccountname()); - this.usernameTextView.setText(this.settings.GetUsername()); - this.passwordTextView.setText(this.settings.GetPassword()); - this.serverTextView.setText(this.settings.GetServer()); - this.portnumTextView.setText(this.settings.GetPortnum()); - this.security = this.settings.GetSecurity(); - if (this.security == null) this.security = "0"; - this.security_i = Integer.parseInt(this.security); - this.securitySpinner.setSelection(this.security_i); - this.stickyCheckBox.setChecked(Boolean.parseBoolean(this.settings.GetUsesticky())); - this.syncintervalTextView.setText("15"); - this.folderTextView.setText(this.settings.GetFoldername()); - } - - LinearLayout layout = (LinearLayout) findViewById(R.id.bttonsLayout); - accountManager = AccountManager.get(getApplicationContext()); - Account[] accounts = accountManager.getAccountsByType("com.Pau.ImapNotes2"); - for (Account account : accounts) { - if (account.name.equals(accountname)) { - myAccount = account; - break; - } - } - - if ((this.action == null) || (this.myAccount == null)) { this.action = "CREATE_ACCOUNT"; } - - if (this.action.equals("EDIT_ACCOUNT")) { - // Here we have to edit an existing account - this.accountnameTextView.setText(this.accountname); - this.usernameTextView.setText(this.accountManager.getUserData (myAccount, "username")); - this.passwordTextView.setText(this.accountManager.getPassword(myAccount)); - this.serverTextView.setText(this.accountManager.getUserData(myAccount, "server")); - this.portnumTextView.setText(this.accountManager.getUserData(myAccount, "portnum")); - this.security = this.accountManager.getUserData (myAccount, "security"); - this.stickyCheckBox.setChecked(Boolean.parseBoolean(this.accountManager.getUserData(myAccount,"usesticky"))); - this.syncintervalTextView.setText(this.accountManager.getUserData(myAccount, "syncinterval")); - this.folderTextView.setText(this.accountManager.getUserData (myAccount, "imapfolder")); - if (this.security == null) this.security = "0"; - this.security_i = Integer.parseInt(this.security); - this.securitySpinner.setSelection(this.security_i); - Button buttonEdit = new Button(this); - buttonEdit.setText("Save"); - buttonEdit.setOnClickListener(clickListenerEdit); - layout.addView(buttonEdit); - Button buttonRemove = new Button(this); - buttonRemove.setText("Remove"); - buttonRemove.setOnClickListener(clickListenerRemove); - layout.addView(buttonRemove); - } else { - // Here we have to create a new account - Button buttonView = new Button(this); - buttonView.setText("Check & Create Account"); - buttonView.setOnClickListener(clickListenerLogin); - layout.addView(buttonView); - } - - // Don't display keyboard when on note detail, only if user touches the screen - getWindow().setSoftInputMode( - WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN - ); - } - - // DoLogin method is defined in account_selection.xml (account_selection layout) - public void DoLogin(View v) { - ProgressDialog loadingDialog = ProgressDialog.show(this, "ImapNotes2" , "Logging into your account... ", true); - this.imapNotes2Account.SetAccountname(this.accountnameTextView.getText().toString().trim()); - this.imapNotes2Account.SetUsername(this.usernameTextView.getText().toString().trim()); - this.imapNotes2Account.SetPassword(this.passwordTextView.getText().toString().trim()); - this.imapNotes2Account.SetServer(this.serverTextView.getText().toString().trim()); - this.imapNotes2Account.SetPortnum(this.portnumTextView.getText().toString()); - this.imapNotes2Account.SetSecurity(this.security); - this.imapNotes2Account.SetUsesticky(String.valueOf(this.stickyCheckBox.isChecked())); - this.imapNotes2Account.SetSyncinterval(this.syncintervalTextView.getText().toString()); - this.imapNotes2Account.SetFoldername(this.folderTextView.getText().toString()); - long SYNC_FREQUENCY = Long.parseLong(syncintervalTextView.getText().toString(), 10) * 60; - new LoginThread().execute(this.imapFolder, this.imapNotes2Account, loadingDialog, this, this.action, SYNC_FREQUENCY); - - } - - class LoginThread extends AsyncTask { - - private AccontConfigurationActivity accontConfigurationActivity; - private ImapNotes2Result res = new ImapNotes2Result(); - String action; - - protected Boolean doInBackground(Object... stuffs) { - this.action = (String)stuffs[4]; - try { - this.res=((Imaper)stuffs[0]).ConnectToProvider( - ((ImapNotes2Account)stuffs[1]).GetUsername(), - ((ImapNotes2Account)stuffs[1]).GetPassword(), - ((ImapNotes2Account)stuffs[1]).GetServer(), - ((ImapNotes2Account)stuffs[1]).GetPortnum(), - ((ImapNotes2Account)stuffs[1]).GetSecurity(), - ((ImapNotes2Account)stuffs[1]).GetUsesticky(), - ((ImapNotes2Account)stuffs[1]).GetFoldername()); - accontConfigurationActivity = (AccontConfigurationActivity)stuffs[3]; - if (this.res.returnCode==0) { - Account account = new Account(((ImapNotes2Account)stuffs[1]).GetAccountname(), "com.Pau.ImapNotes2"); - long SYNC_FREQUENCY = (long)stuffs[5]; - AccountManager am = AccountManager.get(((AccontConfigurationActivity)stuffs[3])); - accontConfigurationActivity.setResult(AccontConfigurationActivity.TO_REFRESH); - Bundle result = null; - if (this.action.equals("EDIT_ACCOUNT")) { - result = new Bundle(); - result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name); - result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type); - setAccountAuthenticatorResult(result); - am.setUserData(account, "username", ((ImapNotes2Account)stuffs[1]).GetUsername()); - am.setUserData(account, "server", ((ImapNotes2Account)stuffs[1]).GetServer()); - am.setUserData(account, "portnum", ((ImapNotes2Account)stuffs[1]).GetPortnum()); - am.setUserData(account, "syncinterval", ((ImapNotes2Account)stuffs[1]).GetSyncinterval()); - am.setUserData(account, "security", ((ImapNotes2Account)stuffs[1]).GetSecurity()); - am.setUserData(account, "usesticky", ((ImapNotes2Account)stuffs[1]).GetUsesticky()); - am.setUserData(account, "imapfolder", ((ImapNotes2Account)stuffs[1]).GetFoldername()); - // Run the Sync Adapter Periodically - ContentResolver.setIsSyncable(account, AUTHORITY, 1); - ContentResolver.setSyncAutomatically(account, AUTHORITY, true); - ContentResolver.addPeriodicSync(account, AUTHORITY, new Bundle(), SYNC_FREQUENCY); - this.res.errorMessage = "Account has been modified"; - return true; - } else { - if (am.addAccountExplicitly(account, ((ImapNotes2Account)stuffs[1]).GetPassword(), null)) { - result = new Bundle(); - result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name); - result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type); - setAccountAuthenticatorResult(result); - am.setUserData(account, "username", ((ImapNotes2Account)stuffs[1]).GetUsername()); - am.setUserData(account, "server", ((ImapNotes2Account)stuffs[1]).GetServer()); - am.setUserData(account, "portnum", ((ImapNotes2Account)stuffs[1]).GetPortnum()); - am.setUserData(account, "syncinterval", ((ImapNotes2Account)stuffs[1]).GetSyncinterval()); - am.setUserData(account, "security", ((ImapNotes2Account)stuffs[1]).GetSecurity()); - am.setUserData(account, "usesticky", ((ImapNotes2Account)stuffs[1]).GetUsesticky()); - am.setUserData(account, "imapfolder", ((ImapNotes2Account)stuffs[1]).GetFoldername()); - // Run the Sync Adapter Periodically - ContentResolver.setIsSyncable(account, AUTHORITY, 1); - ContentResolver.setSyncAutomatically(account, AUTHORITY, true); - ContentResolver.addPeriodicSync(account, AUTHORITY, new Bundle(), SYNC_FREQUENCY); - this.res.errorMessage = "Account has been added"; - return true; - } else { - this.res.errorMessage = "Account already exists or is null"; - return false; - } - } - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - ((ProgressDialog)stuffs[2]).dismiss(); - } - return false; - } - - protected void onPostExecute(Boolean result){ - if(result){ - accontConfigurationActivity.settings.Clear(); - this.accontConfigurationActivity.accountnameTextView.setText(""); - this.accontConfigurationActivity.usernameTextView.setText(""); - this.accontConfigurationActivity.passwordTextView.setText(""); - this.accontConfigurationActivity.serverTextView.setText(""); - this.accontConfigurationActivity.portnumTextView.setText(""); - this.accontConfigurationActivity.syncintervalTextView.setText("15"); - this.accontConfigurationActivity.securitySpinner.setSelection(0); - this.accontConfigurationActivity.folderTextView.setText(""); - this.accontConfigurationActivity.stickyCheckBox.setChecked(false); - } - final Toast tag = Toast.makeText(getApplicationContext(), this.res.errorMessage,Toast.LENGTH_LONG); - tag.show(); - new CountDownTimer(5000, 1000) { - public void onTick(long millisUntilFinished) {tag.show();} - public void onFinish() {tag.show();} - }.start(); - if (this.action.equals("EDIT_ACCOUNT")) finish(); - } - } - - public boolean onCreateOptionsMenu(Menu menu) { - return true; - } - - public boolean onOptionsItemSelected (MenuItem item){ - switch (item.getItemId()){ - case android.R.id.home: - NavUtils.navigateUpFromSameTask(this); - return true; - default: - return super.onOptionsItemSelected(item); - } - } - - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - this.security = Integer.toString(position); - if ((position == 0) || (position == 3) || (position == 4)) - this.portnumTextView.setText("143"); - if ((position == 1) || (position == 2)) - this.portnumTextView.setText("993"); - } - - @Override - public void onNothingSelected(AdapterView parent) { - // TODO Auto-generated method stub - } - -} diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java new file mode 100644 index 00000000..221b6a80 --- /dev/null +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java @@ -0,0 +1,355 @@ +package com.Pau.ImapNotes2; + +import java.util.ArrayList; +import java.util.List; + +import com.Pau.ImapNotes2.Data.ConfigurationFile; +import com.Pau.ImapNotes2.Data.ImapNotes2Account; +import com.Pau.ImapNotes2.Miscs.ImapNotes2Result; +import com.Pau.ImapNotes2.Miscs.Imaper; + +import android.accounts.Account; +import android.accounts.AccountAuthenticatorActivity; +import android.accounts.AccountManager; +import android.app.ProgressDialog; +import android.content.ContentResolver; +import android.os.AsyncTask; +import android.os.Bundle; +import android.os.CountDownTimer; +import android.support.v4.app.NavUtils; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.WindowManager; +import android.widget.AdapterView; +import android.widget.AdapterView.OnItemSelectedListener; +import android.widget.ArrayAdapter; +import android.widget.Button; +import android.widget.CheckBox; +import android.widget.LinearLayout; +import android.widget.Spinner; +import android.widget.TextView; +import android.widget.Toast; + +public class AccountConfigurationActivity extends AccountAuthenticatorActivity implements OnItemSelectedListener { + public static final int TO_REFRESH = 999; + public static final String AUTHORITY = "com.Pau.ImapNotes2.provider"; + private static final String TAG = "AccontConfigurationActivity"; + + private Imaper imapFolder; + + private TextView accountnameTextView; + private TextView usernameTextView; + private TextView passwordTextView; + private TextView serverTextView; + private TextView portnumTextView; + private TextView syncintervalTextView; + private TextView folderTextView; + private CheckBox stickyCheckBox; + private Spinner securitySpinner; + private ImapNotes2Account imapNotes2Account; + private String security; + private int security_i; + private String action; + private String accountname; + private ConfigurationFile settings; + private static Account myAccount = null; + private static AccountManager accountManager; + + private OnClickListener clickListenerLogin = new View.OnClickListener() { + @Override + public void onClick(View v) { + // Click on Login Button + if (((String) accountnameTextView.getText().toString()).contains("'")) { + // Single quotation marks are not allowed in accountname + Toast.makeText(getApplicationContext(), "Quotation marks are not allowed in accountname", + Toast.LENGTH_LONG).show(); + } else { + DoLogin(v); + } + } + }; + + private OnClickListener clickListenerEdit = new View.OnClickListener() { + @Override + public void onClick(View v) { + // Click on Edit Button + if (((String) accountnameTextView.getText().toString()).contains("'")) { + // Single quotation marks are not allowed in accountname + Toast.makeText(getApplicationContext(), "Quotation marks are not allowed in accountname", + Toast.LENGTH_LONG).show(); + } else { + DoLogin(v); + } + } + }; + + private OnClickListener clickListenerRemove = new View.OnClickListener() { + @Override + public void onClick(View v) { + // Clic on Remove Button + accountManager.removeAccount(myAccount, null, null); + Toast.makeText(getApplicationContext(), "Account has been removed", + Toast.LENGTH_LONG).show(); + finish();//finishing activity + } + }; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.account_selection); + getActionBar().setDisplayHomeAsUpEnabled(true); + this.accountnameTextView = (TextView) (findViewById(R.id.accountnameEdit)); + this.usernameTextView = (TextView) findViewById(R.id.usernameEdit); + this.passwordTextView = (TextView) findViewById(R.id.passwordEdit); + this.serverTextView = (TextView) findViewById(R.id.serverEdit); + this.portnumTextView = (TextView) findViewById(R.id.portnumEdit); + this.syncintervalTextView = (TextView) findViewById(R.id.syncintervalEdit); + this.folderTextView = (TextView) findViewById(R.id.folderEdit); + this.stickyCheckBox = (CheckBox) findViewById(R.id.stickyCheckBox); + + securitySpinner = (Spinner) findViewById(R.id.securitySpinner); + List list = new ArrayList(); + list.add("None"); + list.add("SSL/TLS"); + list.add("SSL/TLS (accept all certificates)"); + list.add("STARTTLS"); + list.add("STARTTLS (accept all certificates)"); + ArrayAdapter dataAdapter = new ArrayAdapter + (this, android.R.layout.simple_spinner_item, list); + dataAdapter.setDropDownViewResource + (android.R.layout.simple_spinner_dropdown_item); + securitySpinner.setAdapter(dataAdapter); + // Spinner item selection Listener + securitySpinner.setOnItemSelectedListener(this); + + imapNotes2Account = new ImapNotes2Account(); + this.imapFolder = ((ImapNotes2) getApplicationContext()).GetImaper(); + this.settings = new ConfigurationFile(); + + Bundle extras = getIntent().getExtras(); + if (extras != null) { + if (extras.containsKey("action")) { + action = extras.getString("action"); + } + if (extras.containsKey("accountname")) { + accountname = extras.getString("accountname"); + } + } + + if (this.settings != null) { + this.accountnameTextView.setText(this.settings.GetAccountname()); + this.usernameTextView.setText(this.settings.GetUsername()); + this.passwordTextView.setText(this.settings.GetPassword()); + this.serverTextView.setText(this.settings.GetServer()); + this.portnumTextView.setText(this.settings.GetPortnum()); + this.security = this.settings.GetSecurity(); + if (this.security == null) this.security = "0"; + this.security_i = Integer.parseInt(this.security); + this.securitySpinner.setSelection(this.security_i); + this.stickyCheckBox.setChecked(Boolean.parseBoolean(this.settings.GetUsesticky())); + this.syncintervalTextView.setText("15"); + this.folderTextView.setText(this.settings.GetFoldername()); + } + + LinearLayout layout = (LinearLayout) findViewById(R.id.bttonsLayout); + accountManager = AccountManager.get(getApplicationContext()); + Account[] accounts = accountManager.getAccountsByType("com.Pau.ImapNotes2"); + for (Account account : accounts) { + if (account.name.equals(accountname)) { + myAccount = account; + break; + } + } + + if ((this.action == null) || (this.myAccount == null)) { + this.action = "CREATE_ACCOUNT"; + } + + if (this.action.equals("EDIT_ACCOUNT")) { + // Here we have to edit an existing account + this.accountnameTextView.setText(this.accountname); + this.usernameTextView.setText(this.accountManager.getUserData(myAccount, "username")); + this.passwordTextView.setText(this.accountManager.getPassword(myAccount)); + this.serverTextView.setText(this.accountManager.getUserData(myAccount, "server")); + this.portnumTextView.setText(this.accountManager.getUserData(myAccount, "portnum")); + this.security = this.accountManager.getUserData(myAccount, "security"); + this.stickyCheckBox.setChecked(Boolean.parseBoolean(this.accountManager.getUserData(myAccount, "usesticky"))); + this.syncintervalTextView.setText(this.accountManager.getUserData(myAccount, "syncinterval")); + this.folderTextView.setText(this.accountManager.getUserData(myAccount, "imapfolder")); + if (this.security == null) this.security = "0"; + this.security_i = Integer.parseInt(this.security); + this.securitySpinner.setSelection(this.security_i); + Button buttonEdit = new Button(this); + buttonEdit.setText("Save"); + buttonEdit.setOnClickListener(clickListenerEdit); + layout.addView(buttonEdit); + Button buttonRemove = new Button(this); + buttonRemove.setText("Remove"); + buttonRemove.setOnClickListener(clickListenerRemove); + layout.addView(buttonRemove); + } else { + // Here we have to create a new account + Button buttonView = new Button(this); + buttonView.setText("Check & Create Account"); + buttonView.setOnClickListener(clickListenerLogin); + layout.addView(buttonView); + } + + // Don't display keyboard when on note detail, only if user touches the screen + getWindow().setSoftInputMode( + WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN + ); + } + + // DoLogin method is defined in account_selection.xml (account_selection layout) + public void DoLogin(View v) { + ProgressDialog loadingDialog = ProgressDialog.show(this, "ImapNotes2", "Logging into your account... ", true); + this.imapNotes2Account.SetAccountname(this.accountnameTextView.getText().toString().trim()); + this.imapNotes2Account.SetUsername(this.usernameTextView.getText().toString().trim()); + this.imapNotes2Account.SetPassword(this.passwordTextView.getText().toString().trim()); + this.imapNotes2Account.SetServer(this.serverTextView.getText().toString().trim()); + this.imapNotes2Account.SetPortnum(this.portnumTextView.getText().toString()); + this.imapNotes2Account.SetSecurity(this.security); + this.imapNotes2Account.SetUsesticky(String.valueOf(this.stickyCheckBox.isChecked())); + this.imapNotes2Account.SetSyncinterval(this.syncintervalTextView.getText().toString()); + this.imapNotes2Account.SetFoldername(this.folderTextView.getText().toString()); + long SYNC_FREQUENCY = Long.parseLong(syncintervalTextView.getText().toString(), 10) * 60; + new LoginThread().execute(this.imapFolder, this.imapNotes2Account, loadingDialog, this, this.action, SYNC_FREQUENCY); + + } + + class LoginThread extends AsyncTask { + + private AccountConfigurationActivity accontConfigurationActivity; + private ImapNotes2Result res = new ImapNotes2Result(); + String action; + + protected Boolean doInBackground(Object... stuffs) { + this.action = (String) stuffs[4]; + try { + this.res = ((Imaper) stuffs[0]).ConnectToProvider( + ((ImapNotes2Account) stuffs[1]).GetUsername(), + ((ImapNotes2Account) stuffs[1]).GetPassword(), + ((ImapNotes2Account) stuffs[1]).GetServer(), + ((ImapNotes2Account) stuffs[1]).GetPortnum(), + ((ImapNotes2Account) stuffs[1]).GetSecurity(), + ((ImapNotes2Account) stuffs[1]).GetUsesticky(), + ((ImapNotes2Account) stuffs[1]).GetFoldername()); + accontConfigurationActivity = (AccountConfigurationActivity) stuffs[3]; + if (this.res.returnCode == 0) { + Account account = new Account(((ImapNotes2Account) stuffs[1]).GetAccountname(), "com.Pau.ImapNotes2"); + long SYNC_FREQUENCY = (long) stuffs[5]; + AccountManager am = AccountManager.get(((AccountConfigurationActivity) stuffs[3])); + accontConfigurationActivity.setResult(AccountConfigurationActivity.TO_REFRESH); + Bundle result = null; + if (this.action.equals("EDIT_ACCOUNT")) { + result = new Bundle(); + result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name); + result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type); + setAccountAuthenticatorResult(result); + am.setUserData(account, "username", ((ImapNotes2Account) stuffs[1]).GetUsername()); + am.setUserData(account, "server", ((ImapNotes2Account) stuffs[1]).GetServer()); + am.setUserData(account, "portnum", ((ImapNotes2Account) stuffs[1]).GetPortnum()); + am.setUserData(account, "syncinterval", ((ImapNotes2Account) stuffs[1]).GetSyncinterval()); + am.setUserData(account, "security", ((ImapNotes2Account) stuffs[1]).GetSecurity()); + am.setUserData(account, "usesticky", ((ImapNotes2Account) stuffs[1]).GetUsesticky()); + am.setUserData(account, "imapfolder", ((ImapNotes2Account) stuffs[1]).GetFoldername()); + // Run the Sync Adapter Periodically + ContentResolver.setIsSyncable(account, AUTHORITY, 1); + ContentResolver.setSyncAutomatically(account, AUTHORITY, true); + ContentResolver.addPeriodicSync(account, AUTHORITY, new Bundle(), SYNC_FREQUENCY); + this.res.errorMessage = "Account has been modified"; + return true; + } else { + if (am.addAccountExplicitly(account, ((ImapNotes2Account) stuffs[1]).GetPassword(), null)) { + result = new Bundle(); + result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name); + result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type); + setAccountAuthenticatorResult(result); + am.setUserData(account, "username", ((ImapNotes2Account) stuffs[1]).GetUsername()); + am.setUserData(account, "server", ((ImapNotes2Account) stuffs[1]).GetServer()); + am.setUserData(account, "portnum", ((ImapNotes2Account) stuffs[1]).GetPortnum()); + am.setUserData(account, "syncinterval", ((ImapNotes2Account) stuffs[1]).GetSyncinterval()); + am.setUserData(account, "security", ((ImapNotes2Account) stuffs[1]).GetSecurity()); + am.setUserData(account, "usesticky", ((ImapNotes2Account) stuffs[1]).GetUsesticky()); + am.setUserData(account, "imapfolder", ((ImapNotes2Account) stuffs[1]).GetFoldername()); + // Run the Sync Adapter Periodically + ContentResolver.setIsSyncable(account, AUTHORITY, 1); + ContentResolver.setSyncAutomatically(account, AUTHORITY, true); + ContentResolver.addPeriodicSync(account, AUTHORITY, new Bundle(), SYNC_FREQUENCY); + this.res.errorMessage = "Account has been added"; + return true; + } else { + this.res.errorMessage = "Account already exists or is null"; + return false; + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + ((ProgressDialog) stuffs[2]).dismiss(); + } + return false; + } + + protected void onPostExecute(Boolean result) { + if (result) { + accontConfigurationActivity.settings.Clear(); + this.accontConfigurationActivity.accountnameTextView.setText(""); + this.accontConfigurationActivity.usernameTextView.setText(""); + this.accontConfigurationActivity.passwordTextView.setText(""); + this.accontConfigurationActivity.serverTextView.setText(""); + this.accontConfigurationActivity.portnumTextView.setText(""); + this.accontConfigurationActivity.syncintervalTextView.setText("15"); + this.accontConfigurationActivity.securitySpinner.setSelection(0); + this.accontConfigurationActivity.folderTextView.setText(""); + this.accontConfigurationActivity.stickyCheckBox.setChecked(false); + } + final Toast tag = Toast.makeText(getApplicationContext(), this.res.errorMessage, Toast.LENGTH_LONG); + tag.show(); + new CountDownTimer(5000, 1000) { + public void onTick(long millisUntilFinished) { + tag.show(); + } + + public void onFinish() { + tag.show(); + } + }.start(); + if (this.action.equals("EDIT_ACCOUNT")) finish(); + } + } + + public boolean onCreateOptionsMenu(Menu menu) { + return true; + } + + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + NavUtils.navigateUpFromSameTask(this); + return true; + default: + return super.onOptionsItemSelected(item); + } + } + + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + this.security = Integer.toString(position); + if ((position == 0) || (position == 3) || (position == 4)) + this.portnumTextView.setText("143"); + if ((position == 1) || (position == 2)) + this.portnumTextView.setText("993"); + } + + @Override + public void onNothingSelected(AdapterView parent) { + // TODO Auto-generated method stub + } + +} diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFile.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFile.java index f6e7d6f1..c7b22d7c 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFile.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFile.java @@ -11,18 +11,16 @@ import org.xmlpull.v1.XmlSerializer; import android.content.Context; -import android.util.Log; +//import android.util.Log; import android.util.Xml; +import com.Pau.ImapNotes2.ImapNotes2; + public class ConfigurationFile { - // Why do we need a copy of the application context reference? - // It is not necessary in the actual constructor only in the Clear - // method which presumably could get it from the getContext static method. - private Context applicationContext; // For logging. private static final String TAG = "IN_ConfigurationFile"; - + // The account name is the concatenation of the username and server. private String accountname; // User name on the IMAP server. @@ -38,43 +36,38 @@ public class ConfigurationFile { private String usesticky; // The name of the IMAP folder to be used. private String imapfolder; - - - public ConfigurationFile(Context myContext){ - // Save the context reference. It seems that this is probably unnecessary. - this.applicationContext = myContext; - + + + public ConfigurationFile() { try { Document fileToLoad = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse( - new File(this.applicationContext.getFilesDir()+"/ImapNotes2.conf")); - // The expressions ending in getNodeValue shoule be placed in a function - // to reduce clutter and improve maintainability. - this.username = this.LoadItemFromXML(fileToLoad, "username").item(0).getChildNodes().item(0).getNodeValue(); - this.password = this.LoadItemFromXML(fileToLoad, "password").item(0).getChildNodes().item(0).getNodeValue(); - this.server = this.LoadItemFromXML(fileToLoad, "server").item(0).getChildNodes().item(0).getNodeValue(); - this.imapfolder = this.LoadItemFromXML(fileToLoad, "imapfolder").item(0).getChildNodes().item(0).getNodeValue(); + new File(ImapNotes2.ConfigurationFilePath())); + this.username = this.NodeValueFromXML(fileToLoad, "username"); + this.password = this.NodeValueFromXML(fileToLoad, "password"); + this.server = this.NodeValueFromXML(fileToLoad, "server"); + this.imapfolder = this.NodeValueFromXML(fileToLoad, "imapfolder"); this.accountname = this.username + "@" + this.server; - // All of these can be simplified by initializing the fields to the default values and + // All of these can be simplified by initializing the fields to the default values and // only setting when the value exists in the file. if (this.LoadItemFromXML(fileToLoad, "portnum").getLength() == 0) // portnum option doesn't exist this.portnum = ""; else - this.portnum = this.LoadItemFromXML(fileToLoad, "portnum").item(0).getChildNodes().item(0).getNodeValue(); + this.portnum = this.NodeValueFromXML(fileToLoad, "portnum"); if (this.LoadItemFromXML(fileToLoad, "security").getLength() == 0) // security option doesn't exist, say "0" this.security = "0"; else - this.security = this.LoadItemFromXML(fileToLoad, "security").item(0).getChildNodes().item(0).getNodeValue(); + this.security = this.NodeValueFromXML(fileToLoad, "security"); if (this.LoadItemFromXML(fileToLoad, "usesticky").getLength() == 0) // usesticky option doesn't exist, say no this.usesticky = "false"; else - this.usesticky = this.LoadItemFromXML(fileToLoad, "usesticky").item(0).getChildNodes().item(0).getNodeValue(); + this.usesticky = this.NodeValueFromXML(fileToLoad, "usesticky"); //Log.d(TAG, "conf file present, we read data"); } catch (Exception e) { - // This catch should be turned into a simple if then and the catch + // This catch should be turned into a simple if then and the catch // reserved for conditions that cannot be checked for. //Log.d(TAG, "Conf file absent, go to the exception that initializes variables"); this.accountname = ""; @@ -87,112 +80,117 @@ public ConfigurationFile(Context myContext){ this.imapfolder = ""; } } - - public String GetAccountname(){ + + public String GetAccountname() { return this.accountname; } - - public String GetUsername(){ + + public String GetUsername() { return this.username; } - - public void SetUsername(String Username){ + + public void SetUsername(String Username) { this.username = Username; } - - public String GetPassword(){ + + public String GetPassword() { return this.password; } - - public void SetPassword(String Password){ + + public void SetPassword(String Password) { this.password = Password; } - - public String GetServer(){ + + public String GetServer() { return this.server; } - - public void SetServer(String Server){ + + public void SetServer(String Server) { this.server = Server; } - - public String GetPortnum(){ + + public String GetPortnum() { return this.portnum; } - - public void SetPortnum(String Portnum){ + + public void SetPortnum(String Portnum) { this.portnum = Portnum; } - - public String GetSecurity(){ + + public String GetSecurity() { return this.security; } - - public void SetSecurity(String Security){ + + public void SetSecurity(String Security) { this.security = Security; } - - public String GetUsesticky(){ + + public String GetUsesticky() { return this.usesticky; } - - public void SetUsesticky(String Usesticky){ + + public void SetUsesticky(String Usesticky) { this.usesticky = Usesticky; } - public String GetFoldername(){ + public String GetFoldername() { return this.imapfolder; } - - public void Clear(){ - new File(this.applicationContext.getFilesDir()+"/ImapNotes2.conf").delete(); - this.username=null; - this.password=null; - this.server=null; - this.portnum=null; - this.security=null; - this.usesticky=null; + + + public void Clear() { + new File(ImapNotes2.ConfigurationFilePath()).delete(); + this.username = null; + this.password = null; + this.server = null; + this.portnum = null; + this.security = null; + this.usesticky = null; this.imapfolder = null; } - - // This function could take the context as an argument. + + // This function could take the context as an argument. // In addition the name of the file should be a named constant // because it is used elewhere. - public void SaveConfigurationToXML() throws IllegalArgumentException, IllegalStateException, IOException{ - FileOutputStream configurationFile = this.applicationContext.openFileOutput("ImapNotes2.conf", Context.MODE_PRIVATE); + public void SaveConfigurationToXML() + throws IllegalArgumentException, IllegalStateException, IOException { + FileOutputStream configurationFile + = ImapNotes2.getAppContext().openFileOutput(ImapNotes2.ConfigurationFilePath(), + Context.MODE_PRIVATE); XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(configurationFile, "UTF-8"); - serializer.startDocument(null, Boolean.valueOf(true)); - serializer.startTag(null, "Configuration"); - serializer.startTag(null, "username"); - serializer.text(this.username); - serializer.endTag(null, "username"); - serializer.startTag(null, "password"); - serializer.text(this.password); - serializer.endTag(null, "password"); - serializer.startTag(null, "server"); - serializer.text(this.server); - serializer.endTag(null, "server"); - serializer.startTag(null, "portnum"); - serializer.text(this.portnum); - serializer.endTag(null, "portnum"); - serializer.startTag(null, "security"); - serializer.text(this.security); - serializer.endTag(null, "security"); - serializer.startTag(null,"imapfolder"); - serializer.text(this.imapfolder); - serializer.endTag(null, "imapfolder"); - serializer.startTag(null, "usesticky"); - serializer.text(this.usesticky); - serializer.endTag(null, "usesticky"); - serializer.endTag(null, "Configuration"); + serializer.startDocument(null, true); + serializer.startTag(null, "Configuration"); + SerializeText(serializer, "username", this.username); + SerializeText(serializer, "password", this.password); + SerializeText(serializer, "server", this.server); + SerializeText(serializer, "portnum", this.portnum); + SerializeText(serializer, "security", this.security); + SerializeText(serializer, "imapfolder", this.imapfolder); + SerializeText(serializer, "usesticky", this.usesticky); + serializer.endTag(null, "Configuration"); serializer.endDocument(); serializer.flush(); configurationFile.close(); } - - private NodeList LoadItemFromXML(Document fileLoaded, String tag){ + + // Avoid repeated literal tag names. + private void SerializeText(XmlSerializer serializer, String tag, String text) + throws IOException { + serializer.startTag(null, tag); + serializer.text(text); + serializer.endTag(null, tag); + } + + private NodeList LoadItemFromXML(Document fileLoaded, String tag) { return fileLoaded.getElementsByTagName(tag); - + } + + // Reduce clutter and improve maintainability. + private String NodeValueFromXML(Document fileLoaded, String tag) { + return LoadItemFromXML(fileLoaded, tag).item(0).getChildNodes().item(0).getNodeValue(); + } + + } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ImapNotes2Account.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ImapNotes2Account.java index 31b637a4..dbd55d05 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ImapNotes2Account.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ImapNotes2Account.java @@ -15,118 +15,118 @@ public class ImapNotes2Account { private String imapfolder = ""; private Boolean accountHasChanged = false; private Account account = null; - - + + public ImapNotes2Account() { } - + public String toString() { return this.accountname + ":" + this.username + ":" + this.password + ":" - + this.server + ":" + this.portnum + ":" + this.security + ":" - + this.usesticky + ":" + this.imapfolder + ":" + this.accountHasChanged.toString(); - } + + this.server + ":" + this.portnum + ":" + this.security + ":" + + this.usesticky + ":" + this.imapfolder + ":" + this.accountHasChanged.toString(); + } public String GetAccountname() { return this.accountname; } - + public void SetAccount(Account account) { this.account = account; } - + public Account GetAccount() { return this.account; } - + public void SetAccountname(String Accountname) { if (this.accountname.equals(Accountname)) this.accountHasChanged = true; this.accountname = Accountname; } - + public String GetUsername() { return this.username; } - + public void SetUsername(String Username) { this.username = Username; } - + public String GetPassword() { return this.password; } - + public void SetPassword(String Password) { this.password = Password; } - + public String GetServer() { return this.server; } - + public void SetServer(String Server) { this.server = Server; } - + public String GetPortnum() { return this.portnum; } - + public void SetPortnum(String Portnum) { this.portnum = Portnum; } - + public String GetSecurity() { return this.security; } - + public void SetSecurity(String Security) { this.security = Security; } - + public String GetUsesticky() { return this.usesticky; } - + public void SetUsesticky(String Usesticky) { this.usesticky = Usesticky; } - + public String GetSyncinterval() { return this.syncinterval; } - + public void SetSyncinterval(String Syncinterval) { this.syncinterval = Syncinterval; } - + public void SetaccountHasChanged() { this.accountHasChanged = true; } - + public void SetaccountHasNotChanged() { this.accountHasChanged = false; } - + public Boolean GetaccountHasChanged() { return this.accountHasChanged; } - public String GetFoldername(){ + public String GetFoldername() { return this.imapfolder; } public void SetFoldername(String folder) { this.imapfolder = folder; } - + public void Clear() { - this.username=null; - this.password=null; - this.server=null; - this.portnum=null; - this.security=null; - this.usesticky=null; - this.imapfolder=null; - this.accountHasChanged=false; + this.username = null; + this.password = null; + this.server = null; + this.portnum = null; + this.security = null; + this.usesticky = null; + this.imapfolder = null; + this.accountHasChanged = false; } } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java index 5da9495e..15dfb45c 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java @@ -18,149 +18,150 @@ public class NotesDb { - private static final int NOTES_VERSION = 3; - private static final String TAG = "IN_NotesDb"; - private Context ctx; - - private static final String CREATE_NOTES_DB = "CREATE TABLE IF NOT EXISTS " - + "notesTable (" + private static final int NOTES_VERSION = 3; + private static final String TAG = "IN_NotesDb"; + private Context ctx; + + private static final String CREATE_NOTES_DB = "CREATE TABLE IF NOT EXISTS " + + "notesTable (" + "pk integer primary key autoincrement, " + "title text not null, " + "date text not null, " + "number text not null, " + "accountname text not null);"; - private SQLiteDatabase notesDb; - private NotesDbHelper defaultHelper; - - public NotesDb(Context applicationContext){ - this.defaultHelper = new NotesDbHelper(applicationContext, "NotesDb", NOTES_VERSION); - this.ctx = applicationContext; - - } - - public void OpenDb(){ + private SQLiteDatabase notesDb; + private NotesDbHelper defaultHelper; + + public NotesDb(Context applicationContext) { + this.defaultHelper = new NotesDbHelper(applicationContext, "NotesDb", NOTES_VERSION); + this.ctx = applicationContext; + + } + + public void OpenDb() { this.notesDb = this.defaultHelper.getWritableDatabase(); - - } - public void CloseDb(){ + } + + public void CloseDb() { this.notesDb.close(); - - } - - public void InsertANoteInDb(OneNote noteElement, String accountname){ + + } + + public void InsertANoteInDb(OneNote noteElement, String accountname) { ContentValues tableRow = new ContentValues(); tableRow.put("title", (noteElement.GetTitle() != null) ? noteElement.GetTitle() : ""); tableRow.put("date", noteElement.GetDate()); tableRow.put("number", noteElement.GetUid()); tableRow.put("accountname", accountname); this.notesDb.insert("notesTable", null, tableRow); - //Log.d(TAG, "note inserted"); + //Log.d(TAG, "note inserted"); } - public void DeleteANote(String number, String accountname){ + public void DeleteANote(String number, String accountname) { this.notesDb.execSQL("delete from notesTable where number = '" + number + - "' and accountname = '" + accountname + "'"); + "' and accountname = '" + accountname + "'"); } - public void UpdateANote(String olduid, String newuid, String accountname){ + public void UpdateANote(String olduid, String newuid, String accountname) { String req = "update notesTable set number='" + newuid + "' where number='-" + olduid + "' and accountname='" + accountname + "'"; this.notesDb.execSQL(req); } - public String GetDate(String uid, String accountname){ - String selectQuery = "select date from notesTable where number = '" + uid + "' and accountname='"+accountname+"'"; + public String GetDate(String uid, String accountname) { + String selectQuery = "select date from notesTable where number = '" + uid + "' and accountname='" + accountname + "'"; Cursor c = this.notesDb.rawQuery(selectQuery, null); if (c.moveToFirst()) { - return c.getString(0); + return c.getString(0); } return ""; } public String GetTempNumber(String accountname) { - String selectQuery = "select case when cast(max(abs(number)+1) as int) > 0 then cast(max(abs(number)+1) as int)*-1 else '-1' end from notesTable where number < '0' and accountname='"+accountname+"'"; + String selectQuery = "select case when cast(max(abs(number)+1) as int) > 0 then cast(max(abs(number)+1) as int)*-1 else '-1' end from notesTable where number < '0' and accountname='" + accountname + "'"; Cursor c = this.notesDb.rawQuery(selectQuery, null); if (c.moveToFirst()) { - return c.getString(0); + return c.getString(0); } return "-1"; } - public void GetStoredNotes(ArrayList noteList, String accountname){ - noteList.clear(); - Date date=null; - Cursor resultPointer = this.notesDb.query("notesTable", null,"accountname = ?", new String[]{accountname},null,null,"date DESC"); - - if(resultPointer.moveToFirst()){ - int titleIndex = resultPointer.getColumnIndex("title"); - int bodyIndex = resultPointer.getColumnIndex("body"); - int dateIndex = resultPointer.getColumnIndex("date"); - int numberIndex = resultPointer.getColumnIndex("number"); - int positionIndex = resultPointer.getColumnIndex("position"); - int colorIndex = resultPointer.getColumnIndex("color"); + public void GetStoredNotes(ArrayList noteList, String accountname) { + noteList.clear(); + Date date = null; + Cursor resultPointer = this.notesDb.query("notesTable", null, "accountname = ?", new String[]{accountname}, null, null, "date DESC"); + + if (resultPointer.moveToFirst()) { + int titleIndex = resultPointer.getColumnIndex("title"); + int bodyIndex = resultPointer.getColumnIndex("body"); + int dateIndex = resultPointer.getColumnIndex("date"); + int numberIndex = resultPointer.getColumnIndex("number"); + int positionIndex = resultPointer.getColumnIndex("position"); + int colorIndex = resultPointer.getColumnIndex("color"); do { String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); try { - date = sdf.parse(resultPointer.getString(dateIndex)); - } catch(ParseException e){ - //Exception handling - } catch(Exception e){ - //handle exception + date = sdf.parse(resultPointer.getString(dateIndex)); + } catch (ParseException e) { + //Exception handling + } catch (Exception e) { + //handle exception } DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(this.ctx); //String sdate = dateFormat.format(date); String sdate = DateFormat.getDateTimeInstance().format(date); - + noteList.add(new OneNote(resultPointer.getString(titleIndex), - sdate, - resultPointer.getString(numberIndex))); + sdate, + resultPointer.getString(numberIndex))); } while (resultPointer.moveToNext()); } - + } - - public void ClearDb(String accountname){ - this.notesDb.execSQL("delete from notesTable where accountname = '" + accountname+"'"); - + + public void ClearDb(String accountname) { + this.notesDb.execSQL("delete from notesTable where accountname = '" + accountname + "'"); + } - + /** * Database helper that creates and maintains the SQLite database. */ private static class NotesDbHelper extends SQLiteOpenHelper { - public NotesDbHelper(Context currentApplicationContext, String dbName, int dbVersion) { - super(currentApplicationContext, dbName, null, dbVersion); - } + public NotesDbHelper(Context currentApplicationContext, String dbName, int dbVersion) { + super(currentApplicationContext, dbName, null, dbVersion); + } - @Override - public void onCreate(SQLiteDatabase _db) { - _db.execSQL(NotesDb.CREATE_NOTES_DB); - } + @Override + public void onCreate(SQLiteDatabase _db) { + _db.execSQL(NotesDb.CREATE_NOTES_DB); + } @Override public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) { - //Log.d(TAG,"onUpgrade from:"+oldVersion+" to:"+newVersion); - for (int i=oldVersion; i noteList; - private static Context context; - - // Called when starting the application. - public void onCreate(){ - super.onCreate(); - // Save the context in a static so that it is easy toi access everywhere. - ImapNotes2.context = getApplicationContext(); - } - - // Simplify access to the application context. - public static Context getAppContext() { - return ImapNotes2.context; - } + + private ConfigurationFile thisSessionConfigurationFile; + private Imaper thisSessionImapFolder; + private ArrayList noteList; + + private static Context context; + private static final String configurationFileName = "ImapNotes2.conf"; + + // Called when starting the application. + public void onCreate() { + super.onCreate(); + // Save the context in a static so that it is easy to access everywhere. + ImapNotes2.context = getApplicationContext(); + } + + // Simplify access to the application context. But why not just use getApplicationContext + // everywhere? + public static Context getAppContext() { + return ImapNotes2.context; + } + + public static String ConfigurationFilePath() { + return ConfigurationDirPath() + "/" + configurationFileName; + } + + public static String ConfigurationDirPath() { + return ImapNotes2.ConfigurationDir().getPath(); + } + + public static File ConfigurationDir() { + return ImapNotes2.getAppContext().getFilesDir(); + } // ? - public void SetConfigurationFile(ConfigurationFile currentSettings){ - this.thisSessionConfigurationFile = currentSettings; - } - + public void SetConfigurationFile(ConfigurationFile currentSettings) { + this.thisSessionConfigurationFile = currentSettings; + } + // ? - public ConfigurationFile GetConfigurationFile(){ - return this.thisSessionConfigurationFile; - } - + public ConfigurationFile GetConfigurationFile() { + return this.thisSessionConfigurationFile; + } + // ? - public void SetImaper(Imaper currentImaper){ - this.thisSessionImapFolder = currentImaper; - } - + public void SetImaper(Imaper currentImaper) { + this.thisSessionImapFolder = currentImaper; + } + // ? - public Imaper GetImaper(){ - return this.thisSessionImapFolder; - } - + public Imaper GetImaper() { + return this.thisSessionImapFolder; + } + // ? - public void SetNotesList(ArrayList currentNotesList){ - this.noteList = currentNotesList; - } - + public void SetNotesList(ArrayList currentNotesList) { + this.noteList = currentNotesList; + } + // ? - public ArrayList GetNotesList(){ - return this.noteList; - } + public ArrayList GetNotesList() { + return this.noteList; + } } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java index 31796e97..ffc28b77 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java @@ -12,7 +12,7 @@ import org.apache.commons.io.FileUtils; -import com.Pau.ImapNotes2.R; +//import com.Pau.ImapNotes2.R; import com.Pau.ImapNotes2.Data.NotesDb; import com.Pau.ImapNotes2.Miscs.Imaper; import com.Pau.ImapNotes2.Miscs.OneNote; @@ -53,107 +53,108 @@ import android.widget.Filterable; import android.widget.ListView; import android.widget.SearchView; -import android.widget.SimpleAdapter; +//import android.widget.SimpleAdapter; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; -public class Listactivity extends Activity implements OnItemSelectedListener,Filterable { +public class Listactivity extends Activity implements OnItemSelectedListener, Filterable { private static final int SEE_DETAIL = 2; private static final int DELETE_BUTTON = 3; private static final int NEW_BUTTON = 4; private static final int SAVE_BUTTON = 5; private static final int EDIT_BUTTON = 6; - + private ArrayList noteList; private NotesListAdapter listToView; private ArrayAdapter spinnerList; - + private Imaper imapFolder; private static NotesDb storedNotes = null; private Spinner accountSpinner; public static ImapNotes2Account imapNotes2Account; private static AccountManager accountManager; - private static Account[] accounts; + // Ensure that we never have to check for null by initializing reference. + private static Account[] accounts = new Account[0]; private static List currentList; private TextView status = null; private static String OldStatus; - private Button editAccountButton=null; + private Button editAccountButton = null; private ListView listview; public static final String AUTHORITY = "com.Pau.ImapNotes2.provider"; private static final String TAG = "IN_Listactivity"; - + private OnClickListener clickListenerEditAccount = new View.OnClickListener() { @Override public void onClick(View v) { - // Clic on editAccount Button Intent res = new Intent(); String mPackage = "com.Pau.ImapNotes2"; String mClass = ".AccontConfigurationActivity"; - res.setComponent(new ComponentName(mPackage,mPackage+mClass)); + res.setComponent(new ComponentName(mPackage, mPackage + mClass)); res.putExtra("action", "EDIT_ACCOUNT"); res.putExtra("accountname", Listactivity.imapNotes2Account.GetAccountname()); startActivity(res); } }; - - /** Called when the activity is first created. */ + + /** + * Called when the activity is first created. + */ @Override public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.main); - - // Accounts spinner - this.accountSpinner = (Spinner) findViewById(R.id.accountSpinner); - Listactivity.currentList = new ArrayList(); - // Spinner item selection Listener - this.accountSpinner.setOnItemSelectedListener(this); - - imapNotes2Account = new ImapNotes2Account(); - Listactivity.accountManager = AccountManager.get(getApplicationContext()); - Listactivity.accountManager.addOnAccountsUpdatedListener((OnAccountsUpdateListener) - new AccountsUpdateListener(), null, true); - - status = (TextView)findViewById(R.id.status); - - this.spinnerList = new ArrayAdapter - (this, android.R.layout.simple_spinner_item,Listactivity.currentList); - spinnerList.setDropDownViewResource - (android.R.layout.simple_spinner_dropdown_item); - this.accountSpinner.setAdapter(spinnerList); - - this.noteList = new ArrayList(); - ((ImapNotes2)this.getApplicationContext()).SetNotesList(this.noteList); - this.listToView = new NotesListAdapter( - getApplicationContext(), - this.noteList, - R.layout.note_element, - new String[]{"title","date"}, - new int[]{R.id.noteTitle, R.id.noteInformation}); - listview = (ListView) findViewById(R.id.notesList); - listview.setAdapter(this.listToView); - - listview.setTextFilterEnabled(true); - - this.imapFolder = new Imaper(); - ((ImapNotes2)this.getApplicationContext()).SetImaper(this.imapFolder); - - if (Listactivity.storedNotes == null) - storedNotes = new NotesDb(getApplicationContext()); - - // When item is clicked, we go to NoteDetailActivity - listview.setOnItemClickListener(new OnItemClickListener() { - public void onItemClick(AdapterView arg0, View widget, int selectedNote, long arg3) { - Intent toDetail = new Intent(widget.getContext(), NoteDetailActivity.class); - toDetail.putExtra("selectedNote", (OneNote)arg0.getItemAtPosition(selectedNote)); - toDetail.putExtra("useSticky", Listactivity.imapNotes2Account.GetUsesticky()); - startActivityForResult(toDetail,SEE_DETAIL); - } - }); + super.onCreate(savedInstanceState); + setContentView(R.layout.main); + + this.accountSpinner = (Spinner) findViewById(R.id.accountSpinner); + Listactivity.currentList = new ArrayList<>(); + + this.accountSpinner.setOnItemSelectedListener(this); + + imapNotes2Account = new ImapNotes2Account(); + Listactivity.accountManager = AccountManager.get(getApplicationContext()); + Listactivity.accountManager.addOnAccountsUpdatedListener( + new AccountsUpdateListener(), null, true); + + status = (TextView) findViewById(R.id.status); + + this.spinnerList = new ArrayAdapter<> + (this, android.R.layout.simple_spinner_item, Listactivity.currentList); + spinnerList.setDropDownViewResource + (android.R.layout.simple_spinner_dropdown_item); + this.accountSpinner.setAdapter(spinnerList); + + this.noteList = new ArrayList<>(); + ((ImapNotes2) this.getApplicationContext()).SetNotesList(this.noteList); + this.listToView = new NotesListAdapter( + getApplicationContext(), + this.noteList, + R.layout.note_element, + new String[]{"title", "date"}, + new int[]{R.id.noteTitle, R.id.noteInformation}); + listview = (ListView) findViewById(R.id.notesList); + listview.setAdapter(this.listToView); + + listview.setTextFilterEnabled(true); + + this.imapFolder = new Imaper(); + ((ImapNotes2) this.getApplicationContext()).SetImaper(this.imapFolder); + + if (Listactivity.storedNotes == null) + storedNotes = new NotesDb(getApplicationContext()); + + // When item is clicked, we go to NoteDetailActivity + listview.setOnItemClickListener(new OnItemClickListener() { + public void onItemClick(AdapterView arg0, View widget, int selectedNote, long arg3) { + Intent toDetail = new Intent(widget.getContext(), NoteDetailActivity.class); + toDetail.putExtra("selectedNote", (OneNote) arg0.getItemAtPosition(selectedNote)); + toDetail.putExtra("useSticky", Listactivity.imapNotes2Account.GetUsesticky()); + startActivityForResult(toDetail, SEE_DETAIL); + } + }); - editAccountButton = (Button) findViewById(R.id.editAccountButton); - editAccountButton.setOnClickListener(clickListenerEditAccount); + editAccountButton = (Button) findViewById(R.id.editAccountButton); + editAccountButton.setOnClickListener(clickListenerEditAccount); } @@ -168,10 +169,10 @@ public void onDestroy() { public void onStart() { super.onStart(); - int len = this.accounts == null ? 0 : this.accounts.length; + int len = accounts == null ? 0 : accounts.length; if (len > 0) updateAccountSpinner(); } - + @Override protected void onResume() { super.onResume(); @@ -195,9 +196,9 @@ public void onReceive(Context context, Intent intent) { if (isSynced) { // Display last sync date DateFormat dateFormat = - android.text.format.DateFormat.getDateFormat(getApplicationContext()); + android.text.format.DateFormat.getDateFormat(getApplicationContext()); Date date = new Date(); - String sdate = DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.SHORT).format(date); + String sdate = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(date); String sinterval = " (interval:" + String.valueOf(syncInterval) + " min)"; status.setText("Last sync: " + sdate + sinterval); } else { @@ -206,7 +207,7 @@ public void onReceive(Context context, Intent intent) { if (isChanged) { if (Listactivity.storedNotes == null) - storedNotes = new NotesDb(getApplicationContext()); + storedNotes = new NotesDb(getApplicationContext()); storedNotes.OpenDb(); storedNotes.GetStoredNotes(noteList, accountname); listToView.notifyDataSetChanged(); @@ -216,131 +217,131 @@ public void onReceive(Context context, Intent intent) { } }; - public void RefreshList(){ - ProgressDialog loadingDialog = ProgressDialog.show(this, "ImapNotes2" , "Refreshing notes list... ", true); + public void RefreshList() { + ProgressDialog loadingDialog = ProgressDialog.show(this, "ImapNotes2", "Refreshing notes list... ", true); - new SyncThread().execute(this.imapFolder, Listactivity.imapNotes2Account, this.noteList, this.listToView, loadingDialog, this.storedNotes, this.getApplicationContext()); + new SyncThread().execute(this.imapFolder, Listactivity.imapNotes2Account, this.noteList, this.listToView, loadingDialog, storedNotes, this.getApplicationContext()); status.setText("Welcome"); } - - public void UpdateList(String suid, String noteBody, String color, String action){ - ProgressDialog loadingDialog = ProgressDialog.show(this, "imapnote2" , "Updating notes list... ", true); - new UpdateThread().execute(this.imapFolder, Listactivity.imapNotes2Account, this.noteList, this.listToView, loadingDialog, suid, noteBody, color, this.getApplicationContext(), action, this.storedNotes); + public void UpdateList(String suid, String noteBody, String color, String action) { + ProgressDialog loadingDialog = ProgressDialog.show(this, "imapnote2", "Updating notes list... ", true); + + new UpdateThread().execute(this.imapFolder, Listactivity.imapNotes2Account, this.noteList, this.listToView, loadingDialog, suid, noteBody, color, this.getApplicationContext(), action, storedNotes); } - - public boolean onCreateOptionsMenu(Menu menu){ - getMenuInflater().inflate(R.menu.list, menu); - - // Associate searchable configuration with the SearchView - SearchManager searchManager = - (SearchManager) getSystemService(Context.SEARCH_SERVICE); - SearchView searchView = - (SearchView) menu.findItem(R.id.search).getActionView(); - searchView.setSearchableInfo( - searchManager.getSearchableInfo(getComponentName())); - SearchView.OnQueryTextListener textChangeListener = new SearchView.OnQueryTextListener() { - @Override - public boolean onQueryTextChange(String newText) { - // this is your adapter that will be filtered - listToView.getFilter().filter(newText); - return true; - } - - @Override - public boolean onQueryTextSubmit(String query) { - // this is your adapter that will be filtered - listToView.getFilter().filter(query); - return true; - } - }; - searchView.setOnQueryTextListener(textChangeListener); - - return true; - } - - public boolean onOptionsItemSelected (MenuItem item){ - switch (item.getItemId()){ - case R.id.login: - Intent res = new Intent(); - String mPackage = "com.Pau.ImapNotes2"; - String mClass = ".AccontConfigurationActivity"; - res.setComponent(new ComponentName(mPackage,mPackage+mClass)); - res.putExtra("action", "CREATE_ACCOUNT"); - startActivity(res); - return true; - case R.id.refresh: - this.TriggerSync(this.status); - return true; - case R.id.newnote: - Intent toNew = new Intent(this, NewNoteActivity.class); - toNew.putExtra("usesSticky", Listactivity.imapNotes2Account.GetUsesticky()); - startActivityForResult(toNew,Listactivity.NEW_BUTTON); - return true; - case R.id.about: - try { - ComponentName comp = new ComponentName(this.getApplicationContext(), Listactivity.class); - PackageInfo pinfo = this.getApplicationContext().getPackageManager().getPackageInfo(comp.getPackageName(), 0); - String versionName = "Version: " + pinfo.versionName; - String versionCode = "Code: " + String.valueOf(pinfo.versionCode); - - new AlertDialog.Builder(this) - .setTitle("About ImapNotes2") - .setMessage(versionName + "\n" + versionCode) - .setPositiveButton("OK", new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int which) { - // Do nothing - } - }) - .show(); - } catch (android.content.pm.PackageManager.NameNotFoundException e) { - Log.d("XXXXX","except"); + + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(R.menu.list, menu); + + // Associate searchable configuration with the SearchView + SearchManager searchManager = + (SearchManager) getSystemService(Context.SEARCH_SERVICE); + SearchView searchView = + (SearchView) menu.findItem(R.id.search).getActionView(); + searchView.setSearchableInfo( + searchManager.getSearchableInfo(getComponentName())); + SearchView.OnQueryTextListener textChangeListener = new SearchView.OnQueryTextListener() { + @Override + public boolean onQueryTextChange(String newText) { + // this is your adapter that will be filtered + listToView.getFilter().filter(newText); + return true; } - return true; - default: - return super.onOptionsItemSelected(item); + + @Override + public boolean onQueryTextSubmit(String query) { + // this is your adapter that will be filtered + listToView.getFilter().filter(query); + return true; + } + }; + searchView.setOnQueryTextListener(textChangeListener); + + return true; } + + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case R.id.login: + Intent res = new Intent(); + String mPackage = "com.Pau.ImapNotes2"; + String mClass = ".AccontConfigurationActivity"; + res.setComponent(new ComponentName(mPackage, mPackage + mClass)); + res.putExtra("action", "CREATE_ACCOUNT"); + startActivity(res); + return true; + case R.id.refresh: + TriggerSync(this.status); + return true; + case R.id.newnote: + Intent toNew = new Intent(this, NewNoteActivity.class); + toNew.putExtra("usesSticky", Listactivity.imapNotes2Account.GetUsesticky()); + startActivityForResult(toNew, Listactivity.NEW_BUTTON); + return true; + case R.id.about: + try { + ComponentName comp = new ComponentName(this.getApplicationContext(), Listactivity.class); + PackageInfo pinfo = this.getApplicationContext().getPackageManager().getPackageInfo(comp.getPackageName(), 0); + String versionName = "Version: " + pinfo.versionName; + String versionCode = "Code: " + String.valueOf(pinfo.versionCode); + + new AlertDialog.Builder(this) + .setTitle("About ImapNotes2") + .setMessage(versionName + "\n" + versionCode) + .setPositiveButton("OK", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + // Do nothing + } + }) + .show(); + } catch (android.content.pm.PackageManager.NameNotFoundException e) { + Log.d(TAG, "except"); + } + return true; + default: + return super.onOptionsItemSelected(item); + } } - - protected void onActivityResult(int requestCode, int resultCode, Intent data){ - switch(requestCode) { + + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + switch (requestCode) { case Listactivity.SEE_DETAIL: - // Returning from NoteDetailActivity - if (resultCode == Listactivity.DELETE_BUTTON) { - // Delete Message asked for - // String suid will contain the Message Imap UID to delete - String suid = data.getStringExtra("DELETE_ITEM_NUM_IMAP"); - this.UpdateList(suid, null, null, "delete"); - } - if (resultCode == Listactivity.EDIT_BUTTON) { - String txt = data.getStringExtra("EDIT_ITEM_TXT"); - String suid = data.getStringExtra("EDIT_ITEM_NUM_IMAP"); - String color = data.getStringExtra("EDIT_ITEM_COLOR"); - //Log.d(TAG,"Received request to delete message:"+suid); - //Log.d(TAG,"Received request to replace message with:"+txt); - this.UpdateList(suid, txt, color, "update"); - } + // Returning from NoteDetailActivity + if (resultCode == Listactivity.DELETE_BUTTON) { + // Delete Message asked for + // String suid will contain the Message Imap UID to delete + String suid = data.getStringExtra("DELETE_ITEM_NUM_IMAP"); + this.UpdateList(suid, null, null, "delete"); + } + if (resultCode == Listactivity.EDIT_BUTTON) { + String txt = data.getStringExtra("EDIT_ITEM_TXT"); + String suid = data.getStringExtra("EDIT_ITEM_NUM_IMAP"); + String color = data.getStringExtra("EDIT_ITEM_COLOR"); + //Log.d(TAG,"Received request to delete message:"+suid); + //Log.d(TAG,"Received request to replace message with:"+txt); + this.UpdateList(suid, txt, color, "update"); + } case Listactivity.NEW_BUTTON: - // Returning from NewNoteActivity - if (resultCode == Listactivity.SAVE_BUTTON) { - String res = data.getStringExtra("SAVE_ITEM"); - //Log.d(TAG,"Received request to save message:"+res); - String color = data.getStringExtra("SAVE_ITEM_COLOR"); - this.UpdateList(null, res, color, "insert"); - } + // Returning from NewNoteActivity + if (resultCode == Listactivity.SAVE_BUTTON) { + String res = data.getStringExtra("SAVE_ITEM"); + //Log.d(TAG,"Received request to save message:"+res); + String color = data.getStringExtra("SAVE_ITEM_COLOR"); + this.UpdateList(null, res, color, "insert"); + } } } // Spinner item selected listener @Override public void onItemSelected(AdapterView parent, View view, int pos, long id) { - ((TextView) this.accountSpinner.getSelectedView()).setBackgroundColor(0xFFB6B6B6); + (this.accountSpinner.getSelectedView()).setBackgroundColor(0xFFB6B6B6); Account account = Listactivity.accounts[pos]; // Check periodic sync. If set to 86400 (once a day), set it to 900 (15 minutes) // this is due to bad upgrade to v4 which handles offline mode and syncing // Remove this code after V4.0 if version no more used - List currentSyncs = ContentResolver.getPeriodicSyncs (account, AUTHORITY); + List currentSyncs = ContentResolver.getPeriodicSyncs(account, AUTHORITY); for (PeriodicSync onesync : currentSyncs) { if (onesync.period == 86400) { ContentResolver.setIsSyncable(account, AUTHORITY, 1); @@ -352,63 +353,63 @@ public void onItemSelected(AdapterView parent, View view, int pos, long id) { } // End of code Listactivity.imapNotes2Account.SetAccountname(account.name); - Listactivity.imapNotes2Account.SetUsername(Listactivity.accountManager.getUserData (account, "username")); + Listactivity.imapNotes2Account.SetUsername(Listactivity.accountManager.getUserData(account, "username")); String pwd = Listactivity.accountManager.getPassword(account); Listactivity.imapNotes2Account.SetPassword(pwd); - Listactivity.imapNotes2Account.SetServer(Listactivity.accountManager.getUserData (account, "server")); - Listactivity.imapNotes2Account.SetPortnum(Listactivity.accountManager.getUserData (account, "portnum")); - Listactivity.imapNotes2Account.SetSecurity(Listactivity.accountManager.getUserData (account, "security")); - Listactivity.imapNotes2Account.SetUsesticky(accountManager.getUserData (account, "usesticky")); - Listactivity.imapNotes2Account.SetSyncinterval(Listactivity.accountManager.getUserData (account, "syncinterval")); + Listactivity.imapNotes2Account.SetServer(Listactivity.accountManager.getUserData(account, "server")); + Listactivity.imapNotes2Account.SetPortnum(Listactivity.accountManager.getUserData(account, "portnum")); + Listactivity.imapNotes2Account.SetSecurity(Listactivity.accountManager.getUserData(account, "security")); + Listactivity.imapNotes2Account.SetUsesticky(accountManager.getUserData(account, "usesticky")); + Listactivity.imapNotes2Account.SetSyncinterval(Listactivity.accountManager.getUserData(account, "syncinterval")); Listactivity.imapNotes2Account.SetaccountHasChanged(); Listactivity.imapNotes2Account.SetAccount(account); this.RefreshList(); } - + @Override public void onNothingSelected(AdapterView parent) { // TODO Auto-generated method stub - + } - private void updateAccountSpinner () { + private void updateAccountSpinner() { this.spinnerList.notifyDataSetChanged(); //this.accountSpinner.setSelection(spinnerList.getPosition(currentAccountname)); if (this.accountSpinner.getSelectedItemId() == android.widget.AdapterView.INVALID_ROW_ID) { - this.accountSpinner.setSelection(0); + this.accountSpinner.setSelection(0); } - + if (Listactivity.currentList.size() == 1) { Account account = Listactivity.accounts[0]; - Listactivity.imapNotes2Account.SetUsername(Listactivity.accountManager.getUserData (account, "username")); + Listactivity.imapNotes2Account.SetUsername(Listactivity.accountManager.getUserData(account, "username")); String pwd = Listactivity.accountManager.getPassword(account); Listactivity.imapNotes2Account.SetPassword(pwd); - Listactivity.imapNotes2Account.SetServer(Listactivity.accountManager.getUserData (account, "server")); - Listactivity.imapNotes2Account.SetPortnum(Listactivity.accountManager.getUserData (account, "portnum")); - Listactivity.imapNotes2Account.SetSecurity(Listactivity.accountManager.getUserData (account, "security")); - Listactivity.imapNotes2Account.SetUsesticky(accountManager.getUserData (account, "usesticky")); - Listactivity.imapNotes2Account.SetSyncinterval(Listactivity.accountManager.getUserData (account, "syncinterval")); + Listactivity.imapNotes2Account.SetServer(Listactivity.accountManager.getUserData(account, "server")); + Listactivity.imapNotes2Account.SetPortnum(Listactivity.accountManager.getUserData(account, "portnum")); + Listactivity.imapNotes2Account.SetSecurity(Listactivity.accountManager.getUserData(account, "security")); + Listactivity.imapNotes2Account.SetUsesticky(accountManager.getUserData(account, "usesticky")); + Listactivity.imapNotes2Account.SetSyncinterval(Listactivity.accountManager.getUserData(account, "syncinterval")); Listactivity.imapNotes2Account.SetaccountHasChanged(); } } private class AccountsUpdateListener implements OnAccountsUpdateListener { private ArrayList newAccounts; - + @Override public void onAccountsUpdated(Account[] accounts) { List newList; Integer newListSize = 0; //invoked when the AccountManager starts up and whenever the account set changes - this.newAccounts = new ArrayList(); + this.newAccounts = new ArrayList<>(); for (final Account account : accounts) { if (account.type.equals("com.Pau.ImapNotes2")) { this.newAccounts.add(account); } } if (this.newAccounts.size() > 0) { - Account[] imapNotes2Accounts = new Account[this.newAccounts.size()] ; + Account[] imapNotes2Accounts = new Account[this.newAccounts.size()]; int i = 0; for (final Account account : this.newAccounts) { imapNotes2Accounts[i] = account; @@ -416,20 +417,21 @@ public void onAccountsUpdated(Account[] accounts) { } Listactivity.accounts = imapNotes2Accounts; newList = new ArrayList(); - for (Account account: Listactivity.accounts ) { + for (Account account : Listactivity.accounts) { newList.add(account.name); } if (newList.size() == 0) return; - + Boolean equalLists = true; ListIterator iter = Listactivity.currentList.listIterator(); - while(iter.hasNext()){ + while (iter.hasNext()) { String s = iter.next(); if (!(newList.contains(s))) { iter.remove(); - String stringDir = (ImapNotes2.getAppContext()).getFilesDir() + "/" + s; + // Why try here? try { - FileUtils.deleteDirectory(new File (stringDir)); + String stringDir = ImapNotes2.ConfigurationDirPath() + "/" + s; + FileUtils.deleteDirectory(new File(stringDir)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); @@ -437,18 +439,18 @@ public void onAccountsUpdated(Account[] accounts) { equalLists = false; } } - for (String accountName: newList ) { + for (String accountName : newList) { if (!(Listactivity.currentList.contains(accountName))) { Listactivity.currentList.add(accountName); - SyncUtils.CreateDirs (accountName, ImapNotes2.getAppContext()); - + SyncUtils.CreateDirs(accountName, ImapNotes2.getAppContext()); + equalLists = false; } } if (equalLists) return; updateAccountSpinner(); } else { - File filesDir = (ImapNotes2.getAppContext()).getFilesDir(); + File filesDir = ImapNotes2.ConfigurationDir(); try { FileUtils.cleanDirectory(filesDir); } catch (IOException e) { @@ -458,7 +460,7 @@ public void onAccountsUpdated(Account[] accounts) { Intent res = new Intent(); String mPackage = "com.Pau.ImapNotes2"; String mClass = ".AccontConfigurationActivity"; - res.setComponent(new ComponentName(mPackage,mPackage+mClass)); + res.setComponent(new ComponentName(mPackage, mPackage + mClass)); startActivity(res); } } @@ -466,38 +468,38 @@ public void onAccountsUpdated(Account[] accounts) { // In case of neccessary debug with user approval // This function will be called from onDestroy - public void SendLogcatMail(){ - String emailData=""; + public void SendLogcatMail() { + String emailData = ""; try { - Process process = Runtime.getRuntime().exec("logcat -d"); - BufferedReader bufferedReader = new BufferedReader( - new InputStreamReader(process.getInputStream())); - - StringBuilder sb=new StringBuilder(); - String line; - while ((line = bufferedReader.readLine()) != null) { - sb.append(line + "\n"); - } - emailData=sb.toString(); + Process process = Runtime.getRuntime().exec("logcat -d"); + BufferedReader bufferedReader = new BufferedReader( + new InputStreamReader(process.getInputStream())); + + StringBuilder sb = new StringBuilder(); + String line; + while ((line = bufferedReader.readLine()) != null) { + sb.append(line + "\n"); + } + emailData = sb.toString(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } - + //send file using email Intent emailIntent = new Intent(Intent.ACTION_SEND); String to[] = {"nb@dagami.org"}; - emailIntent .putExtra(Intent.EXTRA_EMAIL, to); + emailIntent.putExtra(Intent.EXTRA_EMAIL, to); // the attachment - emailIntent .putExtra(Intent.EXTRA_TEXT, emailData); + emailIntent.putExtra(Intent.EXTRA_TEXT, emailData); // the mail subject - emailIntent .putExtra(Intent.EXTRA_SUBJECT, "Logcat content for ImapNotes2 debugging"); + emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Logcat content for ImapNotes2 debugging"); emailIntent.setType("message/rfc822"); - startActivity(Intent.createChooser(emailIntent , "Send email...")); + startActivity(Intent.createChooser(emailIntent, "Send email...")); } public static void TriggerSync(TextView statusField) { - OldStatus=statusField.getText().toString(); + OldStatus = statusField.getText().toString(); statusField.setText("Syncing..."); Account mAccount = Listactivity.imapNotes2Account.GetAccount(); Bundle settingsBundle = new Bundle(); @@ -509,9 +511,9 @@ public static void TriggerSync(TextView statusField) { ContentResolver.requestSync(mAccount, AUTHORITY, settingsBundle); } - @Override - public Filter getFilter() { - return null; - } + @Override + public Filter getFilter() { + return null; + } } - + diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/ImapNotes2Result.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/ImapNotes2Result.java index 8a3b7856..1c363599 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/ImapNotes2Result.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/ImapNotes2Result.java @@ -4,17 +4,17 @@ public class ImapNotes2Result { - public int returnCode; - public String errorMessage; - public Long UIDValidity; - public boolean hasUIDPLUS; - public Folder notesFolder; - - public ImapNotes2Result () { - returnCode = -1; - errorMessage = ""; - UIDValidity = (long) -1; - hasUIDPLUS = true; - notesFolder = null; - } + public int returnCode; + public String errorMessage; + public Long UIDValidity; + public boolean hasUIDPLUS; + public Folder notesFolder; + + public ImapNotes2Result() { + returnCode = -1; + errorMessage = ""; + UIDValidity = (long) -1; + hasUIDPLUS = true; + notesFolder = null; + } } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/ImapNotesAuthenticatorService.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/ImapNotesAuthenticatorService.java index 6e71bd62..92a3c0ff 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/ImapNotesAuthenticatorService.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/ImapNotesAuthenticatorService.java @@ -1,6 +1,6 @@ package com.Pau.ImapNotes2.Miscs; -import com.Pau.ImapNotes2.AccontConfigurationActivity; +import com.Pau.ImapNotes2.AccountConfigurationActivity; import com.Pau.ImapNotes2.Sync.SyncUtils; import android.accounts.AbstractAccountAuthenticator; @@ -14,10 +14,10 @@ import android.os.Bundle; import android.os.IBinder; -public class ImapNotesAuthenticatorService extends Service{ +public class ImapNotesAuthenticatorService extends Service { - private static final String TAG = "ImapNotesAuthenticationService"; - private Authenticator imapNotesAuthenticator; + private static final String TAG = "ImapNotesAuthenticationService"; + private Authenticator imapNotesAuthenticator; @Override public void onCreate() { @@ -25,89 +25,90 @@ public void onCreate() { } public IBinder onBind(Intent intent) { - IBinder ret = null; - if (intent.getAction().equals(android.accounts.AccountManager.ACTION_AUTHENTICATOR_INTENT)) - ret = getAuthenticator().getIBinder(); - - return ret; + IBinder ret = null; + if (intent.getAction().equals(android.accounts.AccountManager.ACTION_AUTHENTICATOR_INTENT)) + ret = getAuthenticator().getIBinder(); + + return ret; } - + private Authenticator getAuthenticator() { - if (this.imapNotesAuthenticator == null) - this.imapNotesAuthenticator = new Authenticator(this); - - return this.imapNotesAuthenticator; + if (this.imapNotesAuthenticator == null) + this.imapNotesAuthenticator = new Authenticator(this); + + return this.imapNotesAuthenticator; } - + private static class Authenticator extends AbstractAccountAuthenticator { - private Context mContext; - - public Authenticator(Context context) { - super(context); - this.mContext = context; - } - - @Override - public Bundle getAccountRemovalAllowed( - AccountAuthenticatorResponse response, Account account) - throws NetworkErrorException { - Bundle ret = super.getAccountRemovalAllowed(response, account); - if (ret.getBoolean(AccountManager.KEY_BOOLEAN_RESULT)) - SyncUtils.RemoveAccount(this.mContext, account); + private Context mContext; + + public Authenticator(Context context) { + super(context); + this.mContext = context; + } + + @Override + public Bundle getAccountRemovalAllowed( + AccountAuthenticatorResponse response, Account account) + throws NetworkErrorException { + Bundle ret = super.getAccountRemovalAllowed(response, account); + if (ret.getBoolean(AccountManager.KEY_BOOLEAN_RESULT)) + SyncUtils.RemoveAccount(this.mContext, account); /* - mContext.getContentResolver().delete(ListProvider.getClearUri(), + mContext.getContentResolver().delete(ListProvider.getClearUri(), null, null); */ - return ret; - } - @Override - public Bundle addAccount(AccountAuthenticatorResponse response, String accountType, String authTokenType, String[] requiredFeatures, Bundle options) throws NetworkErrorException { - - Intent toLoginActivity = new Intent(this.mContext, AccontConfigurationActivity.class); - toLoginActivity.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response); - Bundle bundle = new Bundle(); - bundle.putParcelable(AccountManager.KEY_INTENT, toLoginActivity); - - return bundle; - } - - @Override - public Bundle confirmCredentials(AccountAuthenticatorResponse response, Account account, Bundle options) throws NetworkErrorException { - - return null; - } - - @Override - public Bundle editProperties(AccountAuthenticatorResponse response, String accountType) { - - return null; - } - - @Override - public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException { - - return null; - } - - @Override - public String getAuthTokenLabel(String authTokenType) { - - return null; - } - - @Override - public Bundle hasFeatures(AccountAuthenticatorResponse response, Account account, String[] features) throws NetworkErrorException { - - return null; - } - - @Override - public Bundle updateCredentials(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException { - - return null; - } - + return ret; + } + + @Override + public Bundle addAccount(AccountAuthenticatorResponse response, String accountType, String authTokenType, String[] requiredFeatures, Bundle options) throws NetworkErrorException { + + Intent toLoginActivity = new Intent(this.mContext, AccountConfigurationActivity.class); + toLoginActivity.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response); + Bundle bundle = new Bundle(); + bundle.putParcelable(AccountManager.KEY_INTENT, toLoginActivity); + + return bundle; + } + + @Override + public Bundle confirmCredentials(AccountAuthenticatorResponse response, Account account, Bundle options) throws NetworkErrorException { + + return null; + } + + @Override + public Bundle editProperties(AccountAuthenticatorResponse response, String accountType) { + + return null; + } + + @Override + public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException { + + return null; + } + + @Override + public String getAuthTokenLabel(String authTokenType) { + + return null; + } + + @Override + public Bundle hasFeatures(AccountAuthenticatorResponse response, Account account, String[] features) throws NetworkErrorException { + + return null; + } + + @Override + public Bundle updateCredentials(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException { + + return null; + } + } } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Imaper.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Imaper.java index d6f89bfe..bbd09da6 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Imaper.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Imaper.java @@ -7,18 +7,22 @@ import java.security.GeneralSecurityException; import java.util.ArrayList; import java.util.Properties; + import android.content.Context; import android.content.SharedPreferences; import android.util.Log; + import javax.mail.Folder; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Store; import javax.mail.Flags; + import com.sun.mail.imap.IMAPFolder; import com.sun.mail.imap.IMAPStore; import com.sun.mail.util.MailSSLSocketFactory; + import java.util.regex.*; import com.Pau.ImapNotes2.Miscs.Sticky; @@ -27,100 +31,101 @@ import com.Pau.ImapNotes2.Miscs.ImapNotes2Result; public class Imaper { - - private Store store; - private Session session; - private static final String TAG = "IN_Imaper"; - private String proto; - private String acceptcrt; - private static String sfolder = "Notes"; - private String folderoverride; - private Folder notesFolder = null; - private ImapNotes2Result res; - private Long UIDValidity; -private Boolean useProxy = false; -public static final String PREFS_NAME = "PrefsFile"; - - public ImapNotes2Result ConnectToProvider(String username, String password, String server, String portnum, String security, String usesticky, String override) throws MessagingException{ - if (this.IsConnected()) - this.store.close(); - - res = new ImapNotes2Result(); - if (override==null) { - this.folderoverride = ""; - } else { - this.folderoverride = override; - } - this.proto = ""; - this.acceptcrt = ""; - int security_i = Integer.parseInt(security); - switch (security_i) { - case 0: - // None - this.proto = "imap"; - this.acceptcrt = ""; - break; - case 1: - // SSL/TLS - this.proto = "imaps"; - this.acceptcrt = "false"; - break; - case 2: - // SSL/TLS/TRUST ALL - this.proto = "imaps"; - this.acceptcrt = "true"; - break; - case 3: - // STARTTLS - this.proto = "imap"; - this.acceptcrt = "false"; - break; - case 4: - // STARTTLS/TRUST ALL - this.proto = "imap"; - this.acceptcrt = "true"; - break; + + private Store store; + private Session session; + private static final String TAG = "IN_Imaper"; + private String proto; + private String acceptcrt; + private static String sfolder = "Notes"; + private String folderoverride; + private Folder notesFolder = null; + private ImapNotes2Result res; + private Long UIDValidity; + private Boolean useProxy = false; + public static final String PREFS_NAME = "PrefsFile"; + + public ImapNotes2Result ConnectToProvider(String username, String password, String server, String portnum, String security, String usesticky, String override) throws MessagingException { + if (this.IsConnected()) + this.store.close(); + + res = new ImapNotes2Result(); + if (override == null) { + this.folderoverride = ""; + } else { + this.folderoverride = override; + } + this.proto = ""; + this.acceptcrt = ""; + int security_i = Integer.parseInt(security); + switch (security_i) { + case 0: + // None + this.proto = "imap"; + this.acceptcrt = ""; + break; + case 1: + // SSL/TLS + this.proto = "imaps"; + this.acceptcrt = "false"; + break; + case 2: + // SSL/TLS/TRUST ALL + this.proto = "imaps"; + this.acceptcrt = "true"; + break; + case 3: + // STARTTLS + this.proto = "imap"; + this.acceptcrt = "false"; + break; + case 4: + // STARTTLS/TRUST ALL + this.proto = "imap"; + this.acceptcrt = "true"; + break; ////////////////////// Change this - default: this.proto = "Invalid proto"; - break; - } - MailSSLSocketFactory sf = null; - try { - sf = new MailSSLSocketFactory(); - } catch (GeneralSecurityException e) { - e.printStackTrace(); - this.res.errorMessage = "Can't connect to server"; - this.res.returnCode = -1; - return this.res; - } + default: + this.proto = "Invalid proto"; + break; + } + MailSSLSocketFactory sf = null; + try { + sf = new MailSSLSocketFactory(); + } catch (GeneralSecurityException e) { + e.printStackTrace(); + this.res.errorMessage = "Can't connect to server"; + this.res.returnCode = -1; + return this.res; + } - Properties props = new Properties(); - - props.setProperty(String.format("mail.%s.host", this.proto), server); - props.setProperty(String.format("mail.%s.port", this.proto), portnum); - props.setProperty("mail.store.protocol", this.proto); - - if ((this.acceptcrt.equals("true"))) { - sf.setTrustedHosts(new String[] {server}); - if (this.proto.equals("imap")) { - props.put("mail.imap.ssl.socketFactory", sf); - props.put("mail.imap.starttls.enable", "true"); - } - } else if (this.acceptcrt.equals("false")) { - props.put(String.format("mail.%s.ssl.checkserveridentity", this.proto), "true"); - if (this.proto.equals("imap")) { - props.put("mail.imap.starttls.enable", "true"); - } - } + Properties props = new Properties(); - if (this.proto.equals("imaps")) { - props.put("mail.imaps.socketFactory", sf); - } + props.setProperty(String.format("mail.%s.host", this.proto), server); + props.setProperty(String.format("mail.%s.port", this.proto), portnum); + props.setProperty("mail.store.protocol", this.proto); + + if ((this.acceptcrt.equals("true"))) { + sf.setTrustedHosts(new String[]{server}); + if (this.proto.equals("imap")) { + props.put("mail.imap.ssl.socketFactory", sf); + props.put("mail.imap.starttls.enable", "true"); + } + } else if (this.acceptcrt.equals("false")) { + props.put(String.format("mail.%s.ssl.checkserveridentity", this.proto), "true"); + if (this.proto.equals("imap")) { + props.put("mail.imap.starttls.enable", "true"); + } + } + + if (this.proto.equals("imaps")) { + props.put("mail.imaps.socketFactory", sf); + } - props.setProperty("mail.imap.connectiontimeout","1000"); - if (this.useProxy) { - props.put("mail.imap.socks.host","10.0.2.2"); - props.put("mail.imap.socks.port","1080"); + props.setProperty("mail.imap.connectiontimeout", "1000"); + if (this.useProxy) { + props.put("mail.imap.socks.host", "10.0.2.2"); + props.put("mail.imap.socks.port", "1080"); /* props.put("proxySet","true"); props.put("socksProxyHost","10.0.2.2"); @@ -128,58 +133,58 @@ public ImapNotes2Result ConnectToProvider(String username, String password, Stri props.put("sun.net.spi.nameservice.provider.1", "dns,sun"); props.put("sun.net.spi.nameservice.nameservers", "192.168.0.99"); */ - } - this.session = Session.getInstance(props, null); + } + this.session = Session.getInstance(props, null); //this.session.setDebug(true); - this.store = this.session.getStore(this.proto); - try { - this.store.connect(server, username, password); -Boolean hasUIDPLUS = ((IMAPStore) this.store).hasCapability("UIDPLUS"); + this.store = this.session.getStore(this.proto); + try { + this.store.connect(server, username, password); + Boolean hasUIDPLUS = ((IMAPStore) this.store).hasCapability("UIDPLUS"); //Log.d(TAG, "has UIDPLUS="+hasUIDPLUS); - Folder[] folders = store.getPersonalNamespaces(); - Folder folder = folders[0]; + Folder[] folders = store.getPersonalNamespaces(); + Folder folder = folders[0]; //Log.d(TAG,"Personal Namespaces="+folder.getFullName()); - if (this.folderoverride.length() > 0) { - Imaper.sfolder = this.folderoverride; - } else if (folder.getFullName().length() == 0) { - Imaper.sfolder = "Notes"; - } else { - char separator = folder.getSeparator(); - Imaper.sfolder = folder.getFullName() + separator + "Notes"; - } - this.res.errorMessage = ""; - this.res.returnCode = 0; - return this.res; - } catch (Exception e) { - e.printStackTrace(); - Log.d(TAG, e.getMessage()); - this.res.errorMessage = e.getMessage(); - this.res.returnCode = -2; - return this.res; + if (this.folderoverride.length() > 0) { + Imaper.sfolder = this.folderoverride; + } else if (folder.getFullName().length() == 0) { + Imaper.sfolder = "Notes"; + } else { + char separator = folder.getSeparator(); + Imaper.sfolder = folder.getFullName() + separator + "Notes"; + } + this.res.errorMessage = ""; + this.res.returnCode = 0; + return this.res; + } catch (Exception e) { + e.printStackTrace(); + Log.d(TAG, e.getMessage()); + this.res.errorMessage = e.getMessage(); + this.res.returnCode = -2; + return this.res; + } + + } + + public boolean IsConnected() { + return this.store != null && this.store.isConnected(); + } + + // Put values in shared preferences: + public void SetPrefs() { + SharedPreferences preferences = ImapNotes2.getAppContext().getSharedPreferences(Listactivity.imapNotes2Account.GetAccountname(), Context.MODE_PRIVATE); + SharedPreferences.Editor editor = preferences.edit(); + editor.putString("Name", "valid_data"); + editor.putLong("UIDValidity", this.UIDValidity); + editor.apply(); } - } - - public boolean IsConnected(){ - return this.store!=null && this.store.isConnected(); - } - - // Put values in shared preferences: - public void SetPrefs() { - SharedPreferences preferences = ImapNotes2.getAppContext().getSharedPreferences(Listactivity.imapNotes2Account.GetAccountname(), Context.MODE_PRIVATE); - SharedPreferences.Editor editor = preferences.edit(); - editor.putString("Name","valid_data"); - editor.putLong("UIDValidity", this.UIDValidity); - editor.apply(); - } - - // Retrieve values from shared preferences: - public void GetPrefs() { - SharedPreferences preferences = (ImapNotes2.getAppContext()).getSharedPreferences(Listactivity.imapNotes2Account.GetAccountname(), Context.MODE_PRIVATE); - String name = preferences.getString("Name", ""); - if(!name.equalsIgnoreCase("")) { - this.UIDValidity = preferences.getLong("UIDValidity", -1); + // Retrieve values from shared preferences: + public void GetPrefs() { + SharedPreferences preferences = (ImapNotes2.getAppContext()).getSharedPreferences(Listactivity.imapNotes2Account.GetAccountname(), Context.MODE_PRIVATE); + String name = preferences.getString("Name", ""); + if (!name.equalsIgnoreCase("")) { + this.UIDValidity = preferences.getLong("UIDValidity", -1); + } } - } } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/OneNote.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/OneNote.java index 144fd431..d3951ee8 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/OneNote.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/OneNote.java @@ -2,57 +2,57 @@ import java.util.HashMap; -public class OneNote extends HashMap{ - - /** - * - */ - private static final long serialVersionUID = 1L; - - public OneNote(){ - super(); - this.put("title", "No Title"); - this.put("date", "No Date"); - this.put("uid", "0"); - - } - - public OneNote(String title, String date, String uid){ - super(); - this.put("title", title); - this.put("date", date); - this.put("uid", uid); - - } - - public String GetTitle(){ - return this.get("title"); - } - - public String GetDate(){ - return this.get("date"); - } - - public String GetUid(){ - return this.get("uid"); - } - - public void SetTitle(String title){ - this.put("title", title); - } - - public void SetDate(String date){ - this.put("date", date); - } - - public void SetUid(String uid){ - this.put("uid", uid); - } - - @Override - public String toString() { - return ("Title:"+this.GetTitle()+ - " Date: "+ this.GetDate() + - " Uid: "+ this.GetUid()); - } +public class OneNote extends HashMap { + + /** + * + */ + private static final long serialVersionUID = 1L; + + public OneNote() { + super(); + this.put("title", "No Title"); + this.put("date", "No Date"); + this.put("uid", "0"); + + } + + public OneNote(String title, String date, String uid) { + super(); + this.put("title", title); + this.put("date", date); + this.put("uid", uid); + + } + + public String GetTitle() { + return this.get("title"); + } + + public String GetDate() { + return this.get("date"); + } + + public String GetUid() { + return this.get("uid"); + } + + public void SetTitle(String title) { + this.put("title", title); + } + + public void SetDate(String date) { + this.put("date", date); + } + + public void SetUid(String uid) { + this.put("uid", uid); + } + + @Override + public String toString() { + return ("Title:" + this.GetTitle() + + " Date: " + this.GetDate() + + " Uid: " + this.GetUid()); + } } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Sticky.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Sticky.java index 346ad5f4..4adcdf59 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Sticky.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Sticky.java @@ -2,43 +2,43 @@ public class Sticky { - private static String text; - private static String position; - private static String color; - - public Sticky() { - Sticky.text = ""; - Sticky.position = "0 0 0 0"; - Sticky.color = "YELLOW"; - } - - public Sticky(String text, String position, String color) { - Sticky.text = text; - Sticky.position = position; - Sticky.color = color; - } - - public String GetPosition(){ - return Sticky.position; - } - - public String GetText(){ - return Sticky.text; - } - - public String GetColor(){ - return Sticky.color; - } - - public void SetText(String text){ - Sticky.text = text; - } - - public void SetPosition(String position){ - Sticky.position = position; - } - - public void SetColor(String color){ - Sticky.color = color; - } + private static String text; + private static String position; + private static String color; + + public Sticky() { + Sticky.text = ""; + Sticky.position = "0 0 0 0"; + Sticky.color = "YELLOW"; + } + + public Sticky(String text, String position, String color) { + Sticky.text = text; + Sticky.position = position; + Sticky.color = color; + } + + public String GetPosition() { + return Sticky.position; + } + + public String GetText() { + return Sticky.text; + } + + public String GetColor() { + return Sticky.color; + } + + public void SetText(String text) { + Sticky.text = text; + } + + public void SetPosition(String position) { + Sticky.position = position; + } + + public void SetColor(String color) { + Sticky.color = color; + } } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/SyncThread.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/SyncThread.java index c1096fbc..3f926be1 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/SyncThread.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/SyncThread.java @@ -22,7 +22,7 @@ public class SyncThread extends AsyncTask { ImapNotes2Result res = new ImapNotes2Result(); Context ctx; private static final String TAG = "SyncThread"; - + @Override protected Boolean doInBackground(Object... stuffs) { String username = null; @@ -31,28 +31,28 @@ protected Boolean doInBackground(Object... stuffs) { String portnum = null; String security = null; String usesticky = null; - this.adapter = ((NotesListAdapter)stuffs[3]); - this.notesList = ((ArrayList)stuffs[2]); - this.storedNotes = ((NotesDb)stuffs[5]); - this.ctx = (Context)stuffs[6]; - username = ((ImapNotes2Account)stuffs[1]).GetUsername(); - password = ((ImapNotes2Account)stuffs[1]).GetPassword(); - server = ((ImapNotes2Account)stuffs[1]).GetServer(); - portnum = ((ImapNotes2Account)stuffs[1]).GetPortnum(); - security = ((ImapNotes2Account)stuffs[1]).GetSecurity(); - usesticky = ((ImapNotes2Account)stuffs[1]).GetUsesticky(); - - + this.adapter = ((NotesListAdapter) stuffs[3]); + this.notesList = ((ArrayList) stuffs[2]); + this.storedNotes = ((NotesDb) stuffs[5]); + this.ctx = (Context) stuffs[6]; + username = ((ImapNotes2Account) stuffs[1]).GetUsername(); + password = ((ImapNotes2Account) stuffs[1]).GetPassword(); + server = ((ImapNotes2Account) stuffs[1]).GetServer(); + portnum = ((ImapNotes2Account) stuffs[1]).GetPortnum(); + security = ((ImapNotes2Account) stuffs[1]).GetSecurity(); + usesticky = ((ImapNotes2Account) stuffs[1]).GetUsesticky(); + + if (this.storedNotes == null) this.storedNotes = new NotesDb(this.ctx); this.storedNotes.OpenDb(); this.storedNotes.GetStoredNotes(this.notesList, Listactivity.imapNotes2Account.GetAccountname()); this.storedNotes.CloseDb(); - ((ProgressDialog)stuffs[4]).dismiss(); + ((ProgressDialog) stuffs[4]).dismiss(); return true; } - - protected void onPostExecute(Boolean result){ - if(result){ + + protected void onPostExecute(Boolean result) { + if (result) { this.adapter.notifyDataSetChanged(); } } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java index 91c632f7..9c2cece7 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java @@ -30,7 +30,7 @@ import android.util.Log; import android.widget.SimpleAdapter; -public class UpdateThread extends AsyncTask{ +public class UpdateThread extends AsyncTask { NotesListAdapter adapter; ArrayList notesList; String suid; @@ -45,18 +45,18 @@ public class UpdateThread extends AsyncTask{ String body = null; String action; private static final String TAG = "UpdateThread"; - + @Override protected Boolean doInBackground(Object... stuffs) { - this.adapter = ((NotesListAdapter)stuffs[3]); - this.notesList = ((ArrayList)stuffs[2]); - this.suid = ((String)stuffs[5]); - this.noteBody = ((String)stuffs[6]); - this.color = ((String)stuffs[7]); - this.imapFolder = ((Imaper)stuffs[0]); - this.ctx = (Context)stuffs[8]; - this.action = (String)stuffs[9]; - this.storedNotes = (NotesDb)stuffs[10]; + this.adapter = ((NotesListAdapter) stuffs[3]); + this.notesList = ((ArrayList) stuffs[2]); + this.suid = ((String) stuffs[5]); + this.noteBody = ((String) stuffs[6]); + this.color = ((String) stuffs[7]); + this.imapFolder = ((Imaper) stuffs[0]); + this.ctx = (Context) stuffs[8]; + this.action = (String) stuffs[9]; + this.storedNotes = (NotesDb) stuffs[10]; try { // Do we have a note to remove? @@ -81,7 +81,7 @@ protected Boolean doInBackground(Object... stuffs) { String[] tok = noteTxt.split("\n", 2); String title = tok[0]; String position = "0 0 0 0"; - if (((ImapNotes2Account)stuffs[1]).GetUsesticky().equals("true")) + if (((ImapNotes2Account) stuffs[1]).GetUsesticky().equals("true")) body = noteTxt.replaceAll("\n", "\\\\n"); else body = "" + this.noteBody + ""; @@ -99,28 +99,28 @@ protected Boolean doInBackground(Object... stuffs) { this.currentNote.SetUid(this.suid); // Here we ask to add the new note to the "new" folder // Must be done AFTER uid has been set in currenteNote - WriteMailToNew(currentNote, - ((ImapNotes2Account)stuffs[1]).GetUsesticky(), body); + WriteMailToNew(currentNote, + ((ImapNotes2Account) stuffs[1]).GetUsesticky(), body); this.storedNotes.InsertANoteInDb(this.currentNote, Listactivity.imapNotes2Account.GetAccountname()); this.storedNotes.CloseDb(); // Add note to noteList but chage date format before DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(this.ctx); String sdate = DateFormat.getDateTimeInstance().format(date); this.currentNote.SetDate(sdate); - this.notesList.add(0,this.currentNote); + this.notesList.add(0, this.currentNote); this.bool_to_return = true; } } catch (Exception e) { - e.printStackTrace(); - this.bool_to_return=false; + e.printStackTrace(); + this.bool_to_return = false; } finally { - ((ProgressDialog)stuffs[4]).dismiss(); + ((ProgressDialog) stuffs[4]).dismiss(); } return this.bool_to_return; } - - protected void onPostExecute(Boolean result){ + + protected void onPostExecute(Boolean result) { if (result) { if (this.bool_to_return) /* note added or removed */ this.adapter.notifyDataSetChanged(); @@ -128,71 +128,70 @@ protected void onPostExecute(Boolean result){ } public int getIndexByNumber(String pNumber) { - for(OneNote _item : this.notesList) - { - if(_item.GetUid().equals(pNumber)) + for (OneNote _item : this.notesList) { + if (_item.GetUid().equals(pNumber)) return this.notesList.indexOf(_item); } return -1; } - private void MoveMailToDeleted (String suid) { + private void MoveMailToDeleted(String suid) { String directory = (ImapNotes2.getAppContext()).getFilesDir() + "/" + Listactivity.imapNotes2Account.GetAccountname(); String positiveUid = suid.substring(1); - File from = new File (directory, suid); - File to = new File (directory + "/deleted/" + suid); + File from = new File(directory, suid); + File to = new File(directory + "/deleted/" + suid); if (!from.exists()) { - from = new File (directory + "/new", positiveUid); + from = new File(directory + "/new", positiveUid); from.delete(); } else { from.renameTo(to); } } - public void WriteMailToNew(OneNote note, String usesticky, String noteBody) throws MessagingException, IOException { - String body = null; + public void WriteMailToNew(OneNote note, String usesticky, String noteBody) throws MessagingException, IOException { + String body = null; + + // Here we add the new note to the "new" folder + //Log.d(TAG,"Add new note"); + Properties props = new Properties(); + Session session = Session.getDefaultInstance(props, null); + MimeMessage message = new MimeMessage(session); + if (usesticky.equals("true")) { + body = "BEGIN:STICKYNOTE\nCOLOR:" + this.color + "\nTEXT:" + noteBody + + "\nPOSITION:0 0 0 0\nEND:STICKYNOTE"; + message.setText(body); + message.setHeader("Content-Transfer-Encoding", "8bit"); + message.setHeader("Content-Type", "text/x-stickynote; charset=\"utf-8\""); + } else { + message.setHeader("X-Uniform-Type-Identifier", "com.apple.mail-note"); + UUID uuid = UUID.randomUUID(); + message.setHeader("X-Universally-Unique-Identifier", uuid.toString()); + body = noteBody; + body = body.replaceFirst("

", "

"); + body = body.replaceFirst("

", "

"); + body = body.replaceAll("

", "


"); + body = body.replaceAll("

", "


"); + body = body.replaceAll("

", "
"); + body = body.replaceAll("
\n", "
"); + message.setText(body, "utf-8", "html"); + message.setFlag(Flags.Flag.SEEN, true); + } + message.setSubject(note.GetTitle()); + MailDateFormat mailDateFormat = new MailDateFormat(); + // Remove (CET) or (GMT+1) part as asked in github issue #13 + String headerDate = (mailDateFormat.format(new Date())).replaceAll("\\(.*$", ""); + message.addHeader("Date", headerDate); + //déterminer l'uid temporaire + String uid = Integer.toString(Math.abs(Integer.parseInt(note.GetUid()))); + File directory = new File((ImapNotes2.getAppContext()).getFilesDir() + "/" + + Listactivity.imapNotes2Account.GetAccountname() + "/new"); + //message.setFrom(new InternetAddress("ImapNotes2", Listactivity.imapNotes2Account.GetAccountname())); + message.setFrom(Listactivity.imapNotes2Account.GetAccountname()); + File outfile = new File(directory, uid); + OutputStream str = new FileOutputStream(outfile); + message.writeTo(str); - // Here we add the new note to the "new" folder - //Log.d(TAG,"Add new note"); - Properties props = new Properties(); - Session session = Session.getDefaultInstance(props, null); - MimeMessage message = new MimeMessage(session); - if (usesticky.equals("true")) { - body = "BEGIN:STICKYNOTE\nCOLOR:" + this.color + "\nTEXT:" + noteBody + - "\nPOSITION:0 0 0 0\nEND:STICKYNOTE"; - message.setText(body); - message.setHeader("Content-Transfer-Encoding", "8bit"); - message.setHeader("Content-Type","text/x-stickynote; charset=\"utf-8\""); - } else { - message.setHeader("X-Uniform-Type-Identifier","com.apple.mail-note"); - UUID uuid = UUID.randomUUID(); - message.setHeader("X-Universally-Unique-Identifier", uuid.toString()); - body = noteBody; - body = body.replaceFirst("

", "

"); - body = body.replaceFirst("

", "

"); - body = body.replaceAll("

", "


"); - body = body.replaceAll("

", "


"); - body = body.replaceAll("

", "
"); - body = body.replaceAll("
\n", "
"); - message.setText(body, "utf-8", "html"); - message.setFlag(Flags.Flag.SEEN,true); } - message.setSubject(note.GetTitle()); - MailDateFormat mailDateFormat = new MailDateFormat(); - // Remove (CET) or (GMT+1) part as asked in github issue #13 - String headerDate = (mailDateFormat.format(new Date())).replaceAll("\\(.*$", ""); - message.addHeader("Date", headerDate); - //déterminer l'uid temporaire - String uid = Integer.toString(Math.abs(Integer.parseInt(note.GetUid()))); - File directory = new File ((ImapNotes2.getAppContext()).getFilesDir() + "/" + - Listactivity.imapNotes2Account.GetAccountname() + "/new"); - //message.setFrom(new InternetAddress("ImapNotes2", Listactivity.imapNotes2Account.GetAccountname())); - message.setFrom(Listactivity.imapNotes2Account.GetAccountname()); - File outfile = new File (directory, uid); - OutputStream str = new FileOutputStream(outfile); - message.writeTo(str); - - } } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NewNoteActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NewNoteActivity.java index 1016e67e..87b7e2c7 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NewNoteActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NewNoteActivity.java @@ -10,48 +10,48 @@ import android.view.MenuItem; import android.widget.EditText; -public class NewNoteActivity extends Activity{ - +public class NewNoteActivity extends Activity { + private static final int SAVE_BUTTON = 5; - private static final String TAG = "IN_NewNoteActivity"; - private String sticky; - private String color = "NONE"; - - public void onCreate(Bundle savedInstanceState) { + private static final String TAG = "IN_NewNoteActivity"; + private String sticky; + private String color = "NONE"; + + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.new_note); - getActionBar().setDisplayHomeAsUpEnabled(true); - this.ResetColors(); - this.sticky = (String)getIntent().getExtras().get("usesSticky"); - } - - private void ResetColors(){ - ((EditText)findViewById(R.id.editNote)).setBackgroundColor(Color.TRANSPARENT); - ((EditText)findViewById(R.id.editNote)).setTextColor(Color.BLACK); - } - - public boolean onCreateOptionsMenu(Menu menu){ - getMenuInflater().inflate(R.menu.newnote, menu); + getActionBar().setDisplayHomeAsUpEnabled(true); + this.ResetColors(); + this.sticky = (String) getIntent().getExtras().get("usesSticky"); + } + + private void ResetColors() { + ((EditText) findViewById(R.id.editNote)).setBackgroundColor(Color.TRANSPARENT); + ((EditText) findViewById(R.id.editNote)).setTextColor(Color.BLACK); + } + + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(R.menu.newnote, menu); return true; } - public boolean onOptionsItemSelected (MenuItem item){ - switch (item.getItemId()){ - case R.id.save: - Intent intent=new Intent(); - intent.putExtra("SAVE_ITEM",Html.toHtml(((EditText)findViewById(R.id.editNote)).getText())); - if (this.sticky.equals("true")) { - this.color="YELLOW"; - } - intent.putExtra("SAVE_ITEM_COLOR",this.color); - setResult(SAVE_BUTTON, intent); - finish();//finishing activity - return true; - case android.R.id.home: - NavUtils.navigateUpFromSameTask(this); - return true; - default: - return super.onOptionsItemSelected(item); + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case R.id.save: + Intent intent = new Intent(); + intent.putExtra("SAVE_ITEM", Html.toHtml(((EditText) findViewById(R.id.editNote)).getText())); + if (this.sticky.equals("true")) { + this.color = "YELLOW"; + } + intent.putExtra("SAVE_ITEM_COLOR", this.color); + setResult(SAVE_BUTTON, intent); + finish();//finishing activity + return true; + case android.R.id.home: + NavUtils.navigateUpFromSameTask(this); + return true; + default: + return super.onOptionsItemSelected(item); } } } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java index 8dee10f2..1149019b 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java @@ -1,6 +1,7 @@ package com.Pau.ImapNotes2; import java.util.HashMap; + import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; @@ -35,7 +36,7 @@ import android.widget.EditText; public class NoteDetailActivity extends Activity { - + private static final int DELETE_BUTTON = 3; private static final int EDIT_BUTTON = 6; private HashMap hm; @@ -50,151 +51,151 @@ public class NoteDetailActivity extends Activity { private String suid; // uid as string private final static int ROOT_AND_NEW = 3; private static final String TAG = "IN_NoteDetailActivity"; - + public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.note_detail); - getActionBar().setDisplayHomeAsUpEnabled(true); - // Don't display keyboard when on note detail, only if user touches the screen - getWindow().setSoftInputMode( - WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN - ); - - this.hm = (HashMap)getIntent().getExtras().get("selectedNote"); - this.usesticky = (String)getIntent().getExtras().get("useSticky"); + super.onCreate(savedInstanceState); + setContentView(R.layout.note_detail); + getActionBar().setDisplayHomeAsUpEnabled(true); + // Don't display keyboard when on note detail, only if user touches the screen + getWindow().setSoftInputMode( + WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN + ); - suid = this.hm.get("uid").toString(); - String rootDir = (ImapNotes2.getAppContext()).getFilesDir() + "/" + - Listactivity.imapNotes2Account.GetAccountname(); - message = SyncUtils.ReadMailFromFile(suid, ROOT_AND_NEW, true, rootDir); - sticky = GetInfoFromMessage(message); - stringres = sticky.GetText(); - position = sticky.GetPosition(); - color = sticky.GetColor(); - Spanned plainText = Html.fromHtml(stringres); - ((EditText)findViewById(R.id.bodyView)).setText(plainText); - this.ResetColors(); - //invalidateOptionsMenu(); + this.hm = (HashMap) getIntent().getExtras().get("selectedNote"); + this.usesticky = (String) getIntent().getExtras().get("useSticky"); + + suid = this.hm.get("uid").toString(); + String rootDir = (ImapNotes2.getAppContext()).getFilesDir() + "/" + + Listactivity.imapNotes2Account.GetAccountname(); + message = SyncUtils.ReadMailFromFile(suid, ROOT_AND_NEW, true, rootDir); + sticky = GetInfoFromMessage(message); + stringres = sticky.GetText(); + position = sticky.GetPosition(); + color = sticky.GetColor(); + Spanned plainText = Html.fromHtml(stringres); + ((EditText) findViewById(R.id.bodyView)).setText(plainText); + this.ResetColors(); + //invalidateOptionsMenu(); } - - public void onClick(View v){ + + public void onClick(View v) { this.isClicked = true; } - - private void ResetColors(){ - ((EditText)findViewById(R.id.bodyView)).setBackgroundColor(Color.TRANSPARENT); - ((EditText)findViewById(R.id.bodyView)).setTextColor(Color.BLACK); + + private void ResetColors() { + ((EditText) findViewById(R.id.bodyView)).setBackgroundColor(Color.TRANSPARENT); + ((EditText) findViewById(R.id.bodyView)).setTextColor(Color.BLACK); Colors currentColor = Colors.valueOf(color); switch (currentColor) { - case BLUE: + case BLUE: (findViewById(R.id.scrollView)).setBackgroundColor(0xFFA6CAFD); this.realColor = R.id.blue; break; - case WHITE: + case WHITE: (findViewById(R.id.scrollView)).setBackgroundColor(0xFFFFFFFF); this.realColor = R.id.white; break; - case YELLOW: + case YELLOW: (findViewById(R.id.scrollView)).setBackgroundColor(0xFFFFFFCC); this.realColor = R.id.yellow; break; - case PINK: + case PINK: (findViewById(R.id.scrollView)).setBackgroundColor(0xFFFFCCCC); this.realColor = R.id.pink; break; - case GREEN: + case GREEN: (findViewById(R.id.scrollView)).setBackgroundColor(0xFFCCFFCC); this.realColor = R.id.green; break; - default: + default: (findViewById(R.id.scrollView)).setBackgroundColor(Color.TRANSPARENT); } invalidateOptionsMenu(); } - public boolean onCreateOptionsMenu(Menu menu){ + public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.detail, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { - MenuItem item= menu.findItem(R.id.color); + MenuItem item = menu.findItem(R.id.color); super.onPrepareOptionsMenu(menu); //depending on your conditions, either enable/disable if (this.usesticky.equals("true")) { - item.setVisible(true); + item.setVisible(true); } else { - item.setVisible(false); + item.setVisible(false); } menu.findItem(this.realColor).setChecked(true); return true; } - - public boolean onOptionsItemSelected (MenuItem item){ - Intent intent=new Intent(); - switch (item.getItemId()){ - case R.id.delete: - //Log.d(TAG,"We ask to delete Message #"+this.currentNote.get("number")); - intent.putExtra("DELETE_ITEM_NUM_IMAP",suid); - setResult(NoteDetailActivity.DELETE_BUTTON, intent); - finish();//finishing activity - return true; - case R.id.save: - //Log.d(TAG,"We ask to modify Message #"+this.currentNote.get("number")); - intent.putExtra("EDIT_ITEM_NUM_IMAP",suid); - intent.putExtra("EDIT_ITEM_TXT", - Html.toHtml(((EditText)findViewById(R.id.bodyView)).getText())); - if (!this.usesticky.equals("true")) { - this.color="NONE"; - } - intent.putExtra("EDIT_ITEM_COLOR",this.color); - setResult(NoteDetailActivity.EDIT_BUTTON, intent); - finish();//finishing activity - return true; - case android.R.id.home: - NavUtils.navigateUpFromSameTask(this); - return true; - case R.id.blue: - item.setChecked(true); - this.color = "BLUE"; - (findViewById(R.id.scrollView)).setBackgroundColor(0xFFA6CAFD); - return true; - case R.id.white: - item.setChecked(true); - this.color = "WHITE"; - (findViewById(R.id.scrollView)).setBackgroundColor(0xFFFFFFFF); - return true; - case R.id.yellow: - item.setChecked(true); - this.color = "YELLOW"; - (findViewById(R.id.scrollView)).setBackgroundColor(0xFFFFFFCC); - return true; - case R.id.pink: - item.setChecked(true); - this.color = "PINK"; - (findViewById(R.id.scrollView)).setBackgroundColor(0xFFFFCCCC); - return true; - case R.id.green: - item.setChecked(true); - this.color = "GREEN"; - (findViewById(R.id.scrollView)).setBackgroundColor(0xFFCCFFCC); - return true; - default: - return super.onOptionsItemSelected(item); + + public boolean onOptionsItemSelected(MenuItem item) { + Intent intent = new Intent(); + switch (item.getItemId()) { + case R.id.delete: + //Log.d(TAG,"We ask to delete Message #"+this.currentNote.get("number")); + intent.putExtra("DELETE_ITEM_NUM_IMAP", suid); + setResult(NoteDetailActivity.DELETE_BUTTON, intent); + finish();//finishing activity + return true; + case R.id.save: + //Log.d(TAG,"We ask to modify Message #"+this.currentNote.get("number")); + intent.putExtra("EDIT_ITEM_NUM_IMAP", suid); + intent.putExtra("EDIT_ITEM_TXT", + Html.toHtml(((EditText) findViewById(R.id.bodyView)).getText())); + if (!this.usesticky.equals("true")) { + this.color = "NONE"; + } + intent.putExtra("EDIT_ITEM_COLOR", this.color); + setResult(NoteDetailActivity.EDIT_BUTTON, intent); + finish();//finishing activity + return true; + case android.R.id.home: + NavUtils.navigateUpFromSameTask(this); + return true; + case R.id.blue: + item.setChecked(true); + this.color = "BLUE"; + (findViewById(R.id.scrollView)).setBackgroundColor(0xFFA6CAFD); + return true; + case R.id.white: + item.setChecked(true); + this.color = "WHITE"; + (findViewById(R.id.scrollView)).setBackgroundColor(0xFFFFFFFF); + return true; + case R.id.yellow: + item.setChecked(true); + this.color = "YELLOW"; + (findViewById(R.id.scrollView)).setBackgroundColor(0xFFFFFFCC); + return true; + case R.id.pink: + item.setChecked(true); + this.color = "PINK"; + (findViewById(R.id.scrollView)).setBackgroundColor(0xFFFFCCCC); + return true; + case R.id.green: + item.setChecked(true); + this.color = "GREEN"; + (findViewById(R.id.scrollView)).setBackgroundColor(0xFFCCFFCC); + return true; + default: + return super.onOptionsItemSelected(item); } } public enum Colors { - BLUE, - WHITE, - YELLOW, - PINK, - GREEN, - NONE + BLUE, + WHITE, + YELLOW, + PINK, + GREEN, + NONE } - private Sticky GetInfoFromMessage (Message message) { + private Sticky GetInfoFromMessage(Message message) { ContentType contentType = null; String stringres = null; InputStream iis = null; @@ -203,22 +204,22 @@ private Sticky GetInfoFromMessage (Message message) { Sticky sticky = null; try { //Log.d(TAG, "Contenttype as string:"+message.getContentType()); - contentType = new ContentType(message.getContentType() ); + contentType = new ContentType(message.getContentType()); charset = contentType.getParameter("charset"); - iis = (InputStream)message.getContent(); + iis = (InputStream) message.getContent(); stringres = IOUtils.toString(iis, charset); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); - } + } //Log.d(TAG,"contentType:"+contentType); if (contentType.match("text/x-stickynote")) { - sticky = SyncUtils.ReadStickynote(stringres); + sticky = SyncUtils.ReadStickynote(stringres); } else if (contentType.match("TEXT/HTML")) { - sticky = ReadHtmlnote(stringres); + sticky = ReadHtmlnote(stringres); } else if (contentType.match("TEXT/PLAIN")) { - sticky = ReadPlainnote(stringres); + sticky = ReadPlainnote(stringres); } else if (contentType.match("multipart/related")) { // All next is a workaround // All function need to be rewritten to handle correctly multipart and images @@ -228,35 +229,35 @@ private Sticky GetInfoFromMessage (Message message) { sticky = ReadPlainnote(stringres); } } else if (contentType.getParameter("BOUNDARY") != null) { - sticky = ReadHtmlnote(stringres); + sticky = ReadHtmlnote(stringres); } return sticky; } private void GetPart(Part message) throws Exception { -if (message.isMimeType("text/plain")) { -Log.d(TAG,"+++ isMimeType text/plain (contentType):"+message.getContentType()); -} else if (message.isMimeType("multipart/*")) { -Log.d(TAG,"+++ isMimeType multipart/* (contentType):"+message.getContentType()); -Object content = message.getContent(); - Multipart mp = (Multipart) content; - int count = mp.getCount(); - for (int i = 0; i < count; i++) GetPart(mp.getBodyPart(i)); -} else if (message.isMimeType("message/rfc822")) { -Log.d(TAG,"+++ isMimeType message/rfc822/* (contentType):"+message.getContentType()); -GetPart((Part) message.getContent()); -} else if (message.isMimeType("image/jpeg")) { -Log.d(TAG,"+++ isMimeType image/jpeg (contentType):"+message.getContentType()); -} else if (message.getContentType().contains("image/")) { -Log.d(TAG,"+++ isMimeType image/jpeg (contentType):"+message.getContentType()); -} else { - Object o = message.getContent(); - if (o instanceof String) { - Log.d(TAG,"+++ instanceof String"); - } else if (o instanceof InputStream) { - Log.d(TAG,"+++ instanceof InputStream"); - } else Log.d(TAG,"+++ instanceof ???"); -} + if (message.isMimeType("text/plain")) { + Log.d(TAG, "+++ isMimeType text/plain (contentType):" + message.getContentType()); + } else if (message.isMimeType("multipart/*")) { + Log.d(TAG, "+++ isMimeType multipart/* (contentType):" + message.getContentType()); + Object content = message.getContent(); + Multipart mp = (Multipart) content; + int count = mp.getCount(); + for (int i = 0; i < count; i++) GetPart(mp.getBodyPart(i)); + } else if (message.isMimeType("message/rfc822")) { + Log.d(TAG, "+++ isMimeType message/rfc822/* (contentType):" + message.getContentType()); + GetPart((Part) message.getContent()); + } else if (message.isMimeType("image/jpeg")) { + Log.d(TAG, "+++ isMimeType image/jpeg (contentType):" + message.getContentType()); + } else if (message.getContentType().contains("image/")) { + Log.d(TAG, "+++ isMimeType image/jpeg (contentType):" + message.getContentType()); + } else { + Object o = message.getContent(); + if (o instanceof String) { + Log.d(TAG, "+++ instanceof String"); + } else if (o instanceof InputStream) { + Log.d(TAG, "+++ instanceof InputStream"); + } else Log.d(TAG, "+++ instanceof ???"); + } } private Sticky ReadHtmlnote(String stringres) { @@ -279,19 +280,18 @@ private Sticky ReadPlainnote(String stringres) { return new Sticky(stringres, "", "NONE"); } - private void WriteMailToFile (String suid, Message message) { + private void WriteMailToFile(String suid, Message message) { String directory = (ImapNotes2.getAppContext()).getFilesDir() + "/" + Listactivity.imapNotes2Account.GetAccountname(); try { - File outfile = new File (directory, suid); + File outfile = new File(directory, suid); OutputStream str = new FileOutputStream(outfile); message.writeTo(str); - } catch (Exception e) { + } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } - } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java index 2568530c..444dd499 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java @@ -24,6 +24,7 @@ import android.widget.Filter; import android.widget.Filterable; import android.widget.ImageView; +import android.widget.SimpleAdapter; import android.widget.TextView; import android.view.LayoutInflater; import android.net.Uri; @@ -38,18 +39,18 @@ * in the list. The Maps contain the data for each row. You also specify an XML file that * defines the views used to display the row, and a mapping from keys in the Map to specific * views. - * + *

* Binding data to views occurs in two phases. First, if a * {@link android.widget.SimpleAdapter.ViewBinder} is available, * {@link ViewBinder#setViewValue(android.view.View, Object, String)} - * is invoked. If the returned value is true, binding has occurred. + * is invoked. If the returned value is true, binding has occurred. * If the returned value is false, the following views are then tried in order: *

    *
  • A view that implements Checkable (e.g. CheckBox). The expected bind value is a boolean. - *
  • TextView. The expected bind value is a string and {@link #setViewText(TextView, String)} + *
  • TextView. The expected bind value is a string and {@link #setViewText(TextView, String)} * is invoked. - *
  • ImageView. The expected bind value is a resource id or a string and - * {@link #setViewImage(ImageView, int)} or {@link #setViewImage(ImageView, String)} is invoked. + *
  • ImageView. The expected bind value is a resource id or a string and + * {@link #setViewImage(ImageView, int)} or {@link #setViewImage(ImageView, String)} is invoked. *
* If no appropriate binding can be found, an {@link IllegalStateException} is thrown. */ @@ -69,21 +70,21 @@ public class NotesListAdapter extends BaseAdapter implements Filterable { /** * Constructor - * - * @param context The context where the View associated with this SimpleAdapter is running - * @param data A List of Maps. Each entry in the List corresponds to one row in the list. The - * Maps contain the data for each row, and should include all the entries specified in - * "from" + * + * @param context The context where the View associated with this SimpleAdapter is running + * @param data A List of Maps. Each entry in the List corresponds to one row in the list. The + * Maps contain the data for each row, and should include all the entries specified in + * "from" * @param resource Resource identifier of a view layout that defines the views for this list - * item. The layout file should include at least those named views defined in "to" - * @param from A list of column names that will be added to the Map associated with each - * item. - * @param to The views that should display column in the "from" parameter. These should all be - * TextViews. The first N views in this list are given the values of the first N columns - * in the from parameter. + * item. The layout file should include at least those named views defined in "to" + * @param from A list of column names that will be added to the Map associated with each + * item. + * @param to The views that should display column in the "from" parameter. These should all be + * TextViews. The first N views in this list are given the values of the first N columns + * in the from parameter. */ public NotesListAdapter(Context context, List> data, - int resource, String[] from, int[] to) { + int resource, String[] from, int[] to) { mData = data; mResource = mDropDownResource = resource; mFrom = from; @@ -91,7 +92,7 @@ public NotesListAdapter(Context context, List> data, mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } - + /** * @see android.widget.Adapter#getCount() */ @@ -121,7 +122,7 @@ public View getView(int position, View convertView, ViewGroup parent) { } private View createViewFromResource(int position, View convertView, - ViewGroup parent, int resource) { + ViewGroup parent, int resource) { View v; if (convertView == null) { v = mInflater.inflate(resource, parent, false); @@ -193,7 +194,7 @@ private void bindView(int position, View view) { setViewText((TextView) v, text); } else if (v instanceof ImageView) { if (data instanceof Integer) { - setViewImage((ImageView) v, (Integer) data); + setViewImage((ImageView) v, (Integer) data); } else { setViewImage((ImageView) v, text); } @@ -210,8 +211,7 @@ private void bindView(int position, View view) { * Returns the {@link ViewBinder} used to bind data to views. * * @return a ViewBinder or null if the binder does not exist - * - * @see #setViewBinder(android.widget.SimpleAdapter.ViewBinder) + * @see #getViewBinder(android.widget.SimpleAdapter.ViewBinder) */ public ViewBinder getViewBinder() { return mViewBinder; @@ -221,8 +221,7 @@ public ViewBinder getViewBinder() { * Sets the binder used to bind data to views. * * @param viewBinder the binder used to bind data to views, can be null to - * remove the existing binder - * + * remove the existing binder * @see #getViewBinder() */ public void setViewBinder(ViewBinder viewBinder) { @@ -233,13 +232,12 @@ public void setViewBinder(ViewBinder viewBinder) { * Called by bindView() to set the image for an ImageView but only if * there is no existing ViewBinder or if the existing ViewBinder cannot * handle binding to an ImageView. - * + *

* This method is called instead of {@link #setViewImage(ImageView, String)} * if the supplied data is an int or Integer. * - * @param v ImageView to receive an image + * @param v ImageView to receive an image * @param value the value retrieved from the data set - * * @see #setViewImage(ImageView, String) */ public void setViewImage(ImageView v, int value) { @@ -250,18 +248,17 @@ public void setViewImage(ImageView v, int value) { * Called by bindView() to set the image for an ImageView but only if * there is no existing ViewBinder or if the existing ViewBinder cannot * handle binding to an ImageView. - * + *

* By default, the value will be treated as an image resource. If the * value cannot be used as an image resource, the value is used as an * image Uri. - * + *

* This method is called instead of {@link #setViewImage(ImageView, int)} * if the supplied data is not an int or Integer. * - * @param v ImageView to receive an image + * @param v ImageView to receive an image * @param value the value retrieved from the data set - * - * @see #setViewImage(ImageView, int) + * @see #setViewImage(ImageView, int) */ public void setViewImage(ImageView v, String value) { try { @@ -276,7 +273,7 @@ public void setViewImage(ImageView v, String value) { * there is no existing ViewBinder or if the existing ViewBinder cannot * handle binding to a TextView. * - * @param v TextView to receive text + * @param v TextView to receive text * @param text the text to be set for the TextView */ public void setViewText(TextView v, String text) { @@ -293,7 +290,7 @@ public Filter getFilter() { /** * This class can be used by external clients of SimpleAdapter to bind * values to views. - * + *

* You should use this class to bind values to views that are not * directly supported by SimpleAdapter or to change the way binding * occurs for views supported by SimpleAdapter. @@ -305,17 +302,16 @@ public Filter getFilter() { public static interface ViewBinder { /** * Binds the specified data to the specified view. - * + *

* When binding is handled by this ViewBinder, this method must return true. * If this method returns false, SimpleAdapter will attempts to handle * the binding on its own. * - * @param view the view to bind the data to - * @param data the data to bind to the view + * @param view the view to bind the data to + * @param data the data to bind to the view * @param textRepresentation a safe String representation of the supplied data: - * it is either the result of data.toString() or an empty String but it - * is never null - * + * it is either the result of data.toString() or an empty String but it + * is never null * @return true if the data was bound to the view, false otherwise */ boolean setViewValue(View view, Object data, String textRepresentation); @@ -351,12 +347,12 @@ protected FilterResults performFiltering(CharSequence prefix) { for (int i = 0; i < count; i++) { Map h = unfilteredValues.get(i); if (h != null) { - + int len = mTo.length; - for (int j=0; j - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + android:layout_height="fill_parent" + android:orientation="vertical"> + android:orientation="vertical"> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - diff --git a/ImapNote2/src/main/res/layout/main.xml b/ImapNote2/src/main/res/layout/main.xml index 5104500c..3dde8ba1 100644 --- a/ImapNote2/src/main/res/layout/main.xml +++ b/ImapNote2/src/main/res/layout/main.xml @@ -1,7 +1,8 @@ + android:layout_width="fill_parent" + android:layout_height="wrap_content" + android:orientation="vertical"> + android:textColor="#000000"> + android:layout_height="wrap_content"> - + android:layout_height="fill_parent"> diff --git a/ImapNote2/src/main/res/layout/new_note.xml b/ImapNote2/src/main/res/layout/new_note.xml index 12b5bb1e..3eb189db 100644 --- a/ImapNote2/src/main/res/layout/new_note.xml +++ b/ImapNote2/src/main/res/layout/new_note.xml @@ -1,26 +1,26 @@ + android:layout_height="fill_parent"> + android:orientation="vertical"> + android:ems="10" + android:inputType="textMultiLine"> - + diff --git a/ImapNote2/src/main/res/layout/note_detail.xml b/ImapNote2/src/main/res/layout/note_detail.xml index b6e0d9a6..0b5c57f8 100644 --- a/ImapNote2/src/main/res/layout/note_detail.xml +++ b/ImapNote2/src/main/res/layout/note_detail.xml @@ -1,20 +1,25 @@ - - - - - - + + + + + + + + + diff --git a/ImapNote2/src/main/res/layout/note_element.xml b/ImapNote2/src/main/res/layout/note_element.xml index c43c4a1f..12065be7 100644 --- a/ImapNote2/src/main/res/layout/note_element.xml +++ b/ImapNote2/src/main/res/layout/note_element.xml @@ -1,31 +1,28 @@ - - + + - + android:scrollHorizontally="false" + android:singleLine="true" + android:text="Note Title" + android:textAppearance="?android:attr/textAppearanceLarge" + android:textColor="#000000"> - - + diff --git a/ImapNote2/src/main/res/menu/detail.xml b/ImapNote2/src/main/res/menu/detail.xml index 15b0e6a9..e364d3ae 100644 --- a/ImapNote2/src/main/res/menu/detail.xml +++ b/ImapNote2/src/main/res/menu/detail.xml @@ -1,35 +1,47 @@ -

+ - + android:showAsAction="ifRoom" + android:title="Save"> + - + - + android:showAsAction="ifRoom" + android:title="Delete"> + - - - - - - - - - - + android:showAsAction="ifRoom" + android:title="Color"> + + + + + + + + + - + diff --git a/ImapNote2/src/main/res/menu/list.xml b/ImapNote2/src/main/res/menu/list.xml index 69f0757d..df41ffeb 100644 --- a/ImapNote2/src/main/res/menu/list.xml +++ b/ImapNote2/src/main/res/menu/list.xml @@ -1,39 +1,34 @@ - + - - + android:showAsAction="ifRoom" + android:title="@string/account" /> + - - + android:showAsAction="ifRoom" + android:title="@string/titleNew" /> + - - + android:showAsAction="ifRoom" + android:title="@string/refresh" /> + - - + android:title="@string/search" /> + - - + android:showAsAction="ifRoom" + android:title="@string/about" /> + diff --git a/ImapNote2/src/main/res/menu/newnote.xml b/ImapNote2/src/main/res/menu/newnote.xml index 16db92cd..83b20884 100644 --- a/ImapNote2/src/main/res/menu/newnote.xml +++ b/ImapNote2/src/main/res/menu/newnote.xml @@ -1,10 +1,10 @@ - + - + android:showAsAction="ifRoom" + android:title="Save"> + diff --git a/ImapNote2/src/main/res/values-v14/styles.xml b/ImapNote2/src/main/res/values-v14/styles.xml index 48d2b67b..c57b298e 100644 --- a/ImapNote2/src/main/res/values-v14/styles.xml +++ b/ImapNote2/src/main/res/values-v14/styles.xml @@ -1,24 +1,23 @@ - - - #e8d731 - - - + + + #e8d731 + + + - diff --git a/ImapNote2/src/main/res/values/strings.xml b/ImapNote2/src/main/res/values/strings.xml index c30c1c9d..2f7a6fbb 100644 --- a/ImapNote2/src/main/res/values/strings.xml +++ b/ImapNote2/src/main/res/values/strings.xml @@ -1,4 +1,9 @@ ImapNotes2 + Account + New + Refresh + About + search diff --git a/ImapNote2/src/main/res/values/styles.xml b/ImapNote2/src/main/res/values/styles.xml index f44993ab..28929866 100644 --- a/ImapNote2/src/main/res/values/styles.xml +++ b/ImapNote2/src/main/res/values/styles.xml @@ -1,16 +1,17 @@ - - - #e8d731 - - - + + + #e8d731 + + + diff --git a/ImapNote2/src/main/res/xml/authenticator.xml b/ImapNote2/src/main/res/xml/authenticator.xml index 0fa7a20b..c213191d 100644 --- a/ImapNote2/src/main/res/xml/authenticator.xml +++ b/ImapNote2/src/main/res/xml/authenticator.xml @@ -1,8 +1,7 @@ - - + android:smallIcon="@drawable/ic_launcher" /> + diff --git a/ImapNote2/src/main/res/xml/searchable.xml b/ImapNote2/src/main/res/xml/searchable.xml index 50e59933..55c76496 100644 --- a/ImapNote2/src/main/res/xml/searchable.xml +++ b/ImapNote2/src/main/res/xml/searchable.xml @@ -1,5 +1,5 @@ + android:hint="Search notes titles" + android:label="@string/app_name" /> diff --git a/ImapNote2/src/main/res/xml/syncadapter.xml b/ImapNote2/src/main/res/xml/syncadapter.xml index 4664064c..50f570c6 100644 --- a/ImapNote2/src/main/res/xml/syncadapter.xml +++ b/ImapNote2/src/main/res/xml/syncadapter.xml @@ -1,8 +1,7 @@ + android:supportsUploading="true" + android:userVisible="true" /> diff --git a/build.gradle b/build.gradle index f4d8c542..e7e3c60b 100644 --- a/build.gradle +++ b/build.gradle @@ -4,7 +4,7 @@ buildscript { jcenter() } dependencies { - classpath 'com.android.tools.build:gradle:1.5.0' + classpath 'com.android.tools.build:gradle:2.2.2' } } diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index f23df6e4..987e8e42 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ -#Wed Oct 21 11:34:03 PDT 2015 +#Mon Oct 24 19:37:51 CEST 2016 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-2.8-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip From 5e80fc11084ee9f594f788064cd0cc683098a02c Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Wed, 2 Nov 2016 20:21:10 +0100 Subject: [PATCH 004/103] Corrected Accont -> Account. Added Security Enum, WIP to get rid of literal code numbers in configuration and replace with enum names. --- ImapNote2/src/main/AndroidManifest.xml | 8 +- .../AccountConfigurationActivity.java | 33 +- .../java/com/Pau/ImapNotes2/Listactivity.java | 6 +- .../com/Pau/ImapNotes2/Sync/Security.java | 33 + .../com/Pau/ImapNotes2/Sync/SyncAdapter.java | 39 +- .../com/Pau/ImapNotes2/Sync/SyncUtils.java | 850 +++++++++--------- 6 files changed, 520 insertions(+), 449 deletions(-) create mode 100644 ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/Security.java diff --git a/ImapNote2/src/main/AndroidManifest.xml b/ImapNote2/src/main/AndroidManifest.xml index 798abb8d..f512c98c 100644 --- a/ImapNote2/src/main/AndroidManifest.xml +++ b/ImapNote2/src/main/AndroidManifest.xml @@ -4,7 +4,7 @@ android:versionCode="40" android:versionName="4.9"> - + @@ -19,7 +19,8 @@ android:name=".ImapNotes2" android:icon="@drawable/ic_launcher" android:label="@string/app_name" - android:theme="@style/ImapNotesTheme"> + android:theme="@style/ImapNotesTheme" + android:allowBackup="true"> + android:exported="true" + android:permission=""> diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java index 221b6a80..63975b14 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java @@ -7,6 +7,7 @@ import com.Pau.ImapNotes2.Data.ImapNotes2Account; import com.Pau.ImapNotes2.Miscs.ImapNotes2Result; import com.Pau.ImapNotes2.Miscs.Imaper; +import com.Pau.ImapNotes2.Sync.Security; import android.accounts.Account; import android.accounts.AccountAuthenticatorActivity; @@ -35,7 +36,7 @@ public class AccountConfigurationActivity extends AccountAuthenticatorActivity implements OnItemSelectedListener { public static final int TO_REFRESH = 999; public static final String AUTHORITY = "com.Pau.ImapNotes2.provider"; - private static final String TAG = "AccontConfigurationActivity"; + private static final String TAG = "AccountConfigurationActivity"; private Imaper imapFolder; @@ -111,12 +112,14 @@ public void onCreate(Bundle savedInstanceState) { this.stickyCheckBox = (CheckBox) findViewById(R.id.stickyCheckBox); securitySpinner = (Spinner) findViewById(R.id.securitySpinner); - List list = new ArrayList(); + /*List list = new ArrayList(); list.add("None"); list.add("SSL/TLS"); list.add("SSL/TLS (accept all certificates)"); list.add("STARTTLS"); list.add("STARTTLS (accept all certificates)"); + */ + List list = Security.Printables(); ArrayAdapter dataAdapter = new ArrayAdapter (this, android.R.layout.simple_spinner_item, list); dataAdapter.setDropDownViewResource @@ -223,7 +226,7 @@ public void DoLogin(View v) { class LoginThread extends AsyncTask { - private AccountConfigurationActivity accontConfigurationActivity; + private AccountConfigurationActivity accountConfigurationActivity; private ImapNotes2Result res = new ImapNotes2Result(); String action; @@ -238,12 +241,12 @@ protected Boolean doInBackground(Object... stuffs) { ((ImapNotes2Account) stuffs[1]).GetSecurity(), ((ImapNotes2Account) stuffs[1]).GetUsesticky(), ((ImapNotes2Account) stuffs[1]).GetFoldername()); - accontConfigurationActivity = (AccountConfigurationActivity) stuffs[3]; + accountConfigurationActivity = (AccountConfigurationActivity) stuffs[3]; if (this.res.returnCode == 0) { Account account = new Account(((ImapNotes2Account) stuffs[1]).GetAccountname(), "com.Pau.ImapNotes2"); long SYNC_FREQUENCY = (long) stuffs[5]; AccountManager am = AccountManager.get(((AccountConfigurationActivity) stuffs[3])); - accontConfigurationActivity.setResult(AccountConfigurationActivity.TO_REFRESH); + accountConfigurationActivity.setResult(AccountConfigurationActivity.TO_REFRESH); Bundle result = null; if (this.action.equals("EDIT_ACCOUNT")) { result = new Bundle(); @@ -298,16 +301,16 @@ protected Boolean doInBackground(Object... stuffs) { protected void onPostExecute(Boolean result) { if (result) { - accontConfigurationActivity.settings.Clear(); - this.accontConfigurationActivity.accountnameTextView.setText(""); - this.accontConfigurationActivity.usernameTextView.setText(""); - this.accontConfigurationActivity.passwordTextView.setText(""); - this.accontConfigurationActivity.serverTextView.setText(""); - this.accontConfigurationActivity.portnumTextView.setText(""); - this.accontConfigurationActivity.syncintervalTextView.setText("15"); - this.accontConfigurationActivity.securitySpinner.setSelection(0); - this.accontConfigurationActivity.folderTextView.setText(""); - this.accontConfigurationActivity.stickyCheckBox.setChecked(false); + accountConfigurationActivity.settings.Clear(); + this.accountConfigurationActivity.accountnameTextView.setText(""); + this.accountConfigurationActivity.usernameTextView.setText(""); + this.accountConfigurationActivity.passwordTextView.setText(""); + this.accountConfigurationActivity.serverTextView.setText(""); + this.accountConfigurationActivity.portnumTextView.setText(""); + this.accountConfigurationActivity.syncintervalTextView.setText("15"); + this.accountConfigurationActivity.securitySpinner.setSelection(0); + this.accountConfigurationActivity.folderTextView.setText(""); + this.accountConfigurationActivity.stickyCheckBox.setChecked(false); } final Toast tag = Toast.makeText(getApplicationContext(), this.res.errorMessage, Toast.LENGTH_LONG); tag.show(); diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java index ffc28b77..42187b7d 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java @@ -90,7 +90,7 @@ public class Listactivity extends Activity implements OnItemSelectedListener, Fi public void onClick(View v) { Intent res = new Intent(); String mPackage = "com.Pau.ImapNotes2"; - String mClass = ".AccontConfigurationActivity"; + String mClass = ".AccountConfigurationActivity"; res.setComponent(new ComponentName(mPackage, mPackage + mClass)); res.putExtra("action", "EDIT_ACCOUNT"); res.putExtra("accountname", Listactivity.imapNotes2Account.GetAccountname()); @@ -266,7 +266,7 @@ public boolean onOptionsItemSelected(MenuItem item) { case R.id.login: Intent res = new Intent(); String mPackage = "com.Pau.ImapNotes2"; - String mClass = ".AccontConfigurationActivity"; + String mClass = ".AccountConfigurationActivity"; res.setComponent(new ComponentName(mPackage, mPackage + mClass)); res.putExtra("action", "CREATE_ACCOUNT"); startActivity(res); @@ -459,7 +459,7 @@ public void onAccountsUpdated(Account[] accounts) { } Intent res = new Intent(); String mPackage = "com.Pau.ImapNotes2"; - String mClass = ".AccontConfigurationActivity"; + String mClass = ".AccountConfigurationActivity"; res.setComponent(new ComponentName(mPackage, mPackage + mClass)); startActivity(res); } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/Security.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/Security.java new file mode 100644 index 00000000..f17e7c31 --- /dev/null +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/Security.java @@ -0,0 +1,33 @@ +package com.Pau.ImapNotes2.Sync; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by kj on 11/1/16. + *

+ *

+ * Use this instead of integers in the account configuration. Store the name of the security type instead. + */ + +public enum Security { + None("None"), + SSL_TLS("SSL/TLS"), + SSL_TLS_accept_all_certificates("SSL/TLS (accept all certificates)"), + STARTTLS("STARTTLS"), + STARTTLS_accept_all_certificates("STARTTLS (accept all certificates)"); + + private final String printable; + + Security(String printable) { + this.printable = printable; + } + + public static List Printables() { + List list = new ArrayList(); + for (Security e : Security.values()) { + list.add(e.printable); + } + return list; + } +} diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java index 87c50650..8e211799 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java @@ -23,6 +23,11 @@ import com.Pau.ImapNotes2.Sync.SyncUtils; import com.sun.mail.imap.AppendUID; +/// A SyncAdapter provides methods to be called by the Android +/// framework when the framework is ready for the synchronization to +/// occur. The application does not need to consider threading +/// because the sync happens under Android control not under control +/// of the application. class SyncAdapter extends AbstractThreadedSyncAdapter { public static final String TAG = "SyncAdapter"; private static Context context; @@ -32,6 +37,7 @@ class SyncAdapter extends AbstractThreadedSyncAdapter { private String[] listOfNew; private String[] listOfDeleted; private static Account account; + /// See RFC 3501: http://www.faqs.org/rfcs/rfc3501.html private Long UIDValidity = (long) -1; private static ImapNotes2Result res; private final static int NEW = 1; @@ -45,8 +51,12 @@ public SyncAdapter(Context context, boolean autoInitialize) { this.context = context; } - public SyncAdapter(Context context, boolean autoInitialize, - boolean allowParallelSyncs) { + public SyncAdapter(Context context, + boolean autoInitialize, // ? + boolean allowParallelSyncs // always false, set + // in + // syncadapter.xml + ) { super(context, autoInitialize, allowParallelSyncs); mContentResolver = context.getContentResolver(); this.context = context; @@ -54,34 +64,29 @@ public SyncAdapter(Context context, boolean autoInitialize, @Override public void onPerformSync(Account account, Bundle extras, String authority, - ContentProviderClient provider, SyncResult syncResult) { + ContentProviderClient provider, + SyncResult syncResult) { //Log.d(TAG, "Beginning network synchronization of account: "+account.name); this.account = account; isChanged = false; isSynced = false; String syncinterval; - - SyncUtils.CreateDirs (account.name, this.context); + + SyncUtils.CreateDirs(account.name, this.context); storedNotes = new NotesDb(this.context); storedNotes.OpenDb(); AccountManager am = AccountManager.get(this.context); syncinterval = am.getUserData(account, "syncinterval"); -/* -// Temporary workaround for a bug -// Portnum was put into account manager sync interval (143 or 993 or ... minutes) -if (syncinterval != null) -if (syncinterval.equals("143") || syncinterval.equals("993")) am.setUserData(account, "syncinterval", "15"); -else am.setUserData(account, "syncinterval", "15"); -*/ // Connect to remote and get UIDValidity this.res = ConnectToRemote(); if (this.res.returnCode != 0) { storedNotes.CloseDb(); - // Notify Listactivity that it's finished, but it can't refresh display + // Notify Listactivity that it's finished, but it can't + // refresh display Intent i = new Intent(SyncService.SYNC_FINISHED); i.putExtra("ACCOUNTNAME",account.name); isChanged = false; @@ -103,7 +108,9 @@ public void onPerformSync(Account account, Bundle extras, String authority, SyncUtils.ClearHomeDir(account, this.context); SyncUtils.CreateDirs (account.name, this.context); // Get all notes from remote and replace local - SyncUtils.GetNotes(account,this.res.notesFolder,this.context,storedNotes); + SyncUtils.GetNotes(account, + this.res.notesFolder, + this.context, storedNotes); storedNotes.CloseDb(); } catch (MessagingException e) { // TODO Auto-generated catch block @@ -124,7 +131,7 @@ public void onPerformSync(Account account, Bundle extras, String authority, context.sendBroadcast(i); return; } - + // Send new local messages to remote, move them to local folder // and update uids in database boolean newNotesManaged = handleNewNotes(); @@ -206,7 +213,7 @@ private boolean handleNewNotes() { } // Send this new message to remote final MimeMessage[] msg = {(MimeMessage)message}; - + try { uids = SyncUtils.sendMessageToRemote(msg); } catch (MessagingException e) { diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java index 40dad63f..76db2d9a 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java @@ -8,6 +8,7 @@ import java.io.InputStream; import java.io.OutputStream; import java.security.GeneralSecurityException; +import java.security.InvalidParameterException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; @@ -43,452 +44,477 @@ import android.util.Log; public class SyncUtils { - - static Store store; - static Session session; - static final String TAG = "IN_SyncUtils"; - static String proto; - static String acceptcrt; - static String sfolder = "Notes"; - static private String folderoverride; - static Folder notesFolder = null; - static ImapNotes2Result res; - static Long UIDValidity; - private final static int NEW = 1; - private final static int DELETED = 2; - private final static int ROOT_AND_NEW = 3; -private static Boolean useProxy = false; - - public static ImapNotes2Result ConnectToRemote(String username, String password, String server, String portnum, String security, String usesticky, String override) throws MessagingException{ - if (IsConnected()) - store.close(); - - res = new ImapNotes2Result(); - if (override==null) { - folderoverride = ""; - } else { - folderoverride = override; - } - proto = ""; - acceptcrt = ""; - int security_i = Integer.parseInt(security); - switch (security_i) { - case 0: - // None - proto = "imap"; - acceptcrt = ""; - break; - case 1: - // SSL/TLS - proto = "imaps"; - acceptcrt = "false"; - break; - case 2: - // SSL/TLS/TRUST ALL - proto = "imaps"; - acceptcrt = "true"; - break; - case 3: - // STARTTLS - proto = "imap"; - acceptcrt = "false"; - break; - case 4: - // STARTTLS/TRUST ALL - proto = "imap"; - acceptcrt = "true"; - break; -////////////////////// Change this - default: proto = "Invalid proto"; - break; - } - MailSSLSocketFactory sf = null; - try { - sf = new MailSSLSocketFactory(); - } catch (GeneralSecurityException e) { - e.printStackTrace(); - res.errorMessage = "Can't connect to server"; - res.returnCode = -1; - return res; - } - Properties props = new Properties(); - - props.setProperty(String.format("mail.%s.host", proto), server); - props.setProperty(String.format("mail.%s.port", proto), portnum); - props.setProperty("mail.store.protocol", proto); - - if ((acceptcrt.equals("true"))) { - sf.setTrustedHosts(new String[] {server}); - if (proto.equals("imap")) { - props.put("mail.imap.ssl.socketFactory", sf); - props.put("mail.imap.starttls.enable", "true"); - } - } else if (acceptcrt.equals("false")) { - props.put(String.format("mail.%s.ssl.checkserveridentity", proto), "true"); - if (proto.equals("imap")) { - props.put("mail.imap.starttls.enable", "true"); - } - } + static Store store; + static Session session; + static final String TAG = "IN_SyncUtils"; + static String proto; + static String acceptcrt; + static String sfolder = "Notes"; + static private String folderoverride; + static Folder notesFolder = null; + static ImapNotes2Result res; + static Long UIDValidity; + private final static int NEW = 1; + private final static int DELETED = 2; + private final static int ROOT_AND_NEW = 3; + private static Boolean useProxy = false; + + public static ImapNotes2Result ConnectToRemote(String username, + String password, + String server, + String portnum, + String security, + String usesticky, + String override) throws MessagingException { + if (IsConnected()) + store.close(); + + res = new ImapNotes2Result(); + + folderoverride = (override == null) ? "" : override; + + proto = ""; + acceptcrt = ""; + int security_i = Integer.parseInt(security); + switch (security_i) { + case 0: + // None + proto = "imap"; + acceptcrt = ""; + break; + case 1: + // SSL/TLS + proto = "imaps"; + acceptcrt = "false"; + break; + case 2: + // SSL/TLS/TRUST ALL + proto = "imaps"; + acceptcrt = "true"; + break; + case 3: + // STARTTLS + proto = "imap"; + acceptcrt = "false"; + break; + case 4: + // STARTTLS/TRUST ALL + proto = "imap"; + acceptcrt = "true"; + break; + default: + // TODO: Make sure that this cannot happen. + throw new InvalidParameterException("Invalid security: <" + security + ">"); + } + MailSSLSocketFactory sf = null; + try { + sf = new MailSSLSocketFactory(); + } catch (GeneralSecurityException e) { + e.printStackTrace(); + res.errorMessage = "Can't connect to server"; + res.returnCode = -1; + return res; + } - if (proto.equals("imaps")) { - props.put("mail.imaps.socketFactory", sf); - } + Properties props = new Properties(); - props.setProperty("mail.imap.connectiontimeout","1000"); - if (useProxy) { - props.put("mail.imap.socks.host","10.0.2.2"); - props.put("mail.imap.socks.port","1080"); - } - session = Session.getInstance(props, null); + props.setProperty(String.format("mail.%s.host", proto), server); + props.setProperty(String.format("mail.%s.port", proto), portnum); + props.setProperty("mail.store.protocol", proto); + + if ((acceptcrt.equals("true"))) { + sf.setTrustedHosts(new String[]{server}); + if (proto.equals("imap")) { + props.put("mail.imap.ssl.socketFactory", sf); + props.put("mail.imap.starttls.enable", "true"); + } + } else if (acceptcrt.equals("false")) { + props.put(String.format("mail.%s.ssl.checkserveridentity", proto), "true"); + if (proto.equals("imap")) { + props.put("mail.imap.starttls.enable", "true"); + } + } + + if (proto.equals("imaps")) { + props.put("mail.imaps.socketFactory", sf); + } + + props.setProperty("mail.imap.connectiontimeout", "1000"); + if (useProxy) { + props.put("mail.imap.socks.host", "10.0.2.2"); + props.put("mail.imap.socks.port", "1080"); + } + session = Session.getInstance(props, null); //this.session.setDebug(true); - store = session.getStore(proto); - try { - store.connect(server, username, password); - res.hasUIDPLUS = ((IMAPStore) store).hasCapability("UIDPLUS"); + store = session.getStore(proto); + try { + store.connect(server, username, password); + res.hasUIDPLUS = ((IMAPStore) store).hasCapability("UIDPLUS"); //Log.d(TAG, "has UIDPLUS="+res.hasUIDPLUS); - Folder[] folders = store.getPersonalNamespaces(); - Folder folder = folders[0]; + Folder[] folders = store.getPersonalNamespaces(); + Folder folder = folders[0]; //Log.d(TAG,"Personal Namespaces="+folder.getFullName()); - if (folderoverride.length() > 0) { - sfolder = folderoverride; - } else if (folder.getFullName().length() == 0) { - sfolder = "Notes"; - } else { - char separator = folder.getSeparator(); - sfolder = folder.getFullName() + separator + "Notes"; - } - // Get UIDValidity - notesFolder = store.getFolder(sfolder); - res.UIDValidity = ((IMAPFolder) notesFolder).getUIDValidity(); - res.errorMessage = ""; - res.returnCode = 0; - res.notesFolder = notesFolder; - return res; - } catch (Exception e) { - Log.d(TAG, e.getMessage()); - res.errorMessage = e.getMessage(); - res.returnCode = -2; - return res; + if (folderoverride.length() > 0) { + sfolder = folderoverride; + } else if (folder.getFullName().length() == 0) { + sfolder = "Notes"; + } else { + char separator = folder.getSeparator(); + sfolder = folder.getFullName() + separator + "Notes"; + } + // Get UIDValidity + notesFolder = store.getFolder(sfolder); + res.UIDValidity = ((IMAPFolder) notesFolder).getUIDValidity(); + res.errorMessage = ""; + res.returnCode = 0; + res.notesFolder = notesFolder; + return res; + } catch (Exception e) { + Log.d(TAG, e.getMessage()); + res.errorMessage = e.getMessage(); + res.returnCode = -2; + return res; + } + } - } - - public static void GetNotes(Account account, Folder notesFolder, Context ctx, NotesDb storedNotes) throws MessagingException, IOException{ - Long UIDM; - Message notesMessage; - File directory = new File (ctx.getFilesDir() + "/" + account.name); - if (notesFolder.isOpen()) { - if ((notesFolder.getMode() & Folder.READ_ONLY) != 0) - notesFolder.open(Folder.READ_ONLY); - } else { - notesFolder.open(Folder.READ_ONLY); + public static void GetNotes(Account account, Folder notesFolder, Context ctx, NotesDb storedNotes) throws MessagingException, IOException { + Long UIDM; + Message notesMessage; + File directory = new File(ctx.getFilesDir() + "/" + account.name); + if (notesFolder.isOpen()) { + if ((notesFolder.getMode() & Folder.READ_ONLY) != 0) + notesFolder.open(Folder.READ_ONLY); + } else { + notesFolder.open(Folder.READ_ONLY); + } + UIDValidity = GetUIDValidity(account, ctx); + SetUIDValidity(account, UIDValidity, ctx); + Message[] notesMessages = notesFolder.getMessages(); + //Log.d(TAG,"number of messages in folder="+(notesMessages.length)); + for (int index = notesMessages.length - 1; index >= 0; index--) { + notesMessage = notesMessages[index]; + // write every message in files/{accountname} directory + // filename is the original message uid + UIDM = ((IMAPFolder) notesFolder).getUID(notesMessage); + String suid = UIDM.toString(); + File outfile = new File(directory, suid); + GetOneNote(outfile, notesMessage, storedNotes, account.name, suid, true); + } } - UIDValidity = GetUIDValidity(account, ctx); - SetUIDValidity(account, UIDValidity, ctx); - Message[] notesMessages = notesFolder.getMessages(); - //Log.d(TAG,"number of messages in folder="+(notesMessages.length)); - for(int index=notesMessages.length-1; index>=0; index--) { - notesMessage = notesMessages[index]; - // write every message in files/{accountname} directory - // filename is the original message uid - UIDM=((IMAPFolder)notesFolder).getUID(notesMessage); - String suid = UIDM.toString(); - File outfile = new File (directory, suid); - GetOneNote(outfile, notesMessage, storedNotes, account.name, suid, true); + + public static Sticky ReadStickynote(String stringres) { + String color = new String(""); + String position = new String(""); + String text = new String(""); + Pattern p = null; + Matcher m = null; + + p = Pattern.compile("^COLOR:(.*?)$", Pattern.MULTILINE); + m = p.matcher(stringres); + if (m.find()) { + color = m.group(1); + } + + p = Pattern.compile("^POSITION:(.*?)$", Pattern.MULTILINE); + m = p.matcher(stringres); + if (m.find()) { + position = m.group(1); + } + + p = Pattern.compile("TEXT:(.*?)(END:|POSITION:)", Pattern.DOTALL); + m = p.matcher(stringres); + if (m.find()) { + text = m.group(1); + // Kerio Connect puts CR+LF+space every 78 characters from line 2 + // first line seem to be smaller. We remove these characters + text = text.replaceAll("\r\n ", ""); + // newline in Kerio is the string (not the character) "\n" + text = text.replaceAll("\\\\n", "
"); + } + return new Sticky(text, position, color); } - } - - public static Sticky ReadStickynote(String stringres) { - String color=new String(""); - String position=new String(""); - String text=new String(""); - Pattern p = null; - Matcher m = null; - - p = Pattern.compile("^COLOR:(.*?)$",Pattern.MULTILINE); - m = p.matcher(stringres); - if (m.find()) { color = m.group(1); } - - p = Pattern.compile("^POSITION:(.*?)$",Pattern.MULTILINE); - m = p.matcher(stringres); - if (m.find()) { position = m.group(1); } - - p = Pattern.compile("TEXT:(.*?)(END:|POSITION:)",Pattern.DOTALL); - m = p.matcher(stringres); - if (m.find()) { - text = m.group(1); - // Kerio Connect puts CR+LF+space every 78 characters from line 2 - // first line seem to be smaller. We remove these characters - text = text.replaceAll("\r\n ", ""); - // newline in Kerio is the string (not the character) "\n" - text = text.replaceAll("\\\\n", "
"); + + public static boolean IsConnected() { + return store != null && store.isConnected(); } - return new Sticky(text, position, color); - } - - public static boolean IsConnected(){ - return store!=null && store.isConnected(); - } - - public static void DeleteNote(Folder notesFolder, int numMessage) throws MessagingException, IOException { - notesFolder = store.getFolder(sfolder); - if (notesFolder.isOpen()) { - if ((notesFolder.getMode() & Folder.READ_WRITE) != 0) - notesFolder.open(Folder.READ_WRITE); - } else { - notesFolder.open(Folder.READ_WRITE); + + public static void DeleteNote(Folder notesFolder, int numMessage) throws MessagingException, IOException { + notesFolder = store.getFolder(sfolder); + if (notesFolder.isOpen()) { + if ((notesFolder.getMode() & Folder.READ_WRITE) != 0) + notesFolder.open(Folder.READ_WRITE); + } else { + notesFolder.open(Folder.READ_WRITE); + } + + //Log.d(TAG,"UID to remove:"+numMessage); + Message[] msgs = {((IMAPFolder) notesFolder).getMessageByUID(numMessage)}; + notesFolder.setFlags(msgs, new Flags(Flags.Flag.DELETED), true); + ((IMAPFolder) notesFolder).expunge(msgs); } - - //Log.d(TAG,"UID to remove:"+numMessage); - Message[] msgs = {((IMAPFolder)notesFolder).getMessageByUID(numMessage)}; - notesFolder.setFlags(msgs, new Flags(Flags.Flag.DELETED), true); - ((IMAPFolder)notesFolder).expunge(msgs); - } - - // Put values in shared preferences - public static void SetUIDValidity(Account account, Long UIDValidity, Context ctx) { - SharedPreferences preferences = ctx.getSharedPreferences(account.name, Context.MODE_MULTI_PROCESS); - SharedPreferences.Editor editor = preferences.edit(); - editor.putString("Name","valid_data"); - //Log.d(TAG, "UIDValidity set to in shared_prefs:"+UIDValidity); - editor.putLong("UIDValidity", UIDValidity); - editor.apply(); - } - - // Retrieve values from shared preferences: - public static Long GetUIDValidity(Account account, Context ctx) { - UIDValidity = (long) -1; - SharedPreferences preferences = ctx.getSharedPreferences(account.name, Context.MODE_MULTI_PROCESS); - String name = preferences.getString("Name", ""); - if(!name.equalsIgnoreCase("")) { - UIDValidity = preferences.getLong("UIDValidity", -1); - //Log.d(TAG, "UIDValidity got from shared_prefs:"+UIDValidity); + + // Put values in shared preferences + public static void SetUIDValidity(Account account, Long UIDValidity, Context ctx) { + SharedPreferences preferences = ctx.getSharedPreferences(account.name, Context.MODE_MULTI_PROCESS); + SharedPreferences.Editor editor = preferences.edit(); + editor.putString("Name", "valid_data"); + //Log.d(TAG, "UIDValidity set to in shared_prefs:"+UIDValidity); + editor.putLong("UIDValidity", UIDValidity); + editor.apply(); } - return UIDValidity; - } - - public static void DisconnectFromRemote() { - try { - store.close(); - } catch (MessagingException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + + // Retrieve values from shared preferences: + public static Long GetUIDValidity(Account account, Context ctx) { + UIDValidity = (long) -1; + SharedPreferences preferences = ctx.getSharedPreferences(account.name, Context.MODE_MULTI_PROCESS); + String name = preferences.getString("Name", ""); + if (!name.equalsIgnoreCase("")) { + UIDValidity = preferences.getLong("UIDValidity", -1); + //Log.d(TAG, "UIDValidity got from shared_prefs:"+UIDValidity); + } + return UIDValidity; } - } - - public static Message ReadMailFromFile (String uid, int where, boolean removeMinus, String nameDir) { - File mailFile; - Message message = null; - mailFile = new File (nameDir,uid); - - switch (where){ - case NEW: - nameDir = nameDir + "/new"; - if (removeMinus) uid = uid.substring(1); - break; - case DELETED: - nameDir = nameDir + "/deleted"; - break; - case ROOT_AND_NEW: - if (!mailFile.exists()) { - nameDir = nameDir + "/new"; - if (removeMinus) uid = uid.substring(1); - } - break; - default: - break; - } - - mailFile = new File (nameDir,uid); - InputStream mailFileInputStream = null; - try { - mailFileInputStream = new FileInputStream(mailFile); - } catch (FileNotFoundException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - try { - Properties props = new Properties(); - Session session = Session.getDefaultInstance(props, null); - message = new MimeMessage(session, mailFileInputStream); - } catch (MessagingException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return message; - } - - public static AppendUID[] sendMessageToRemote (Message[] message) throws MessagingException, IOException { - notesFolder = store.getFolder(sfolder); - if (notesFolder.isOpen()) { - if ((notesFolder.getMode() & Folder.READ_WRITE) != 0) - notesFolder.open(Folder.READ_WRITE); - } else { - notesFolder.open(Folder.READ_WRITE); + + public static void DisconnectFromRemote() { + try { + store.close(); + } catch (MessagingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } } - AppendUID[] uids = ((IMAPFolder) notesFolder).appendUIDMessages(message); - return uids; - } - - public static void ClearHomeDir(Account account, Context ctx) { - File directory = new File (ctx.getFilesDir() + "/" + account.name); - try { - FileUtils.deleteDirectory(directory); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + + public static Message ReadMailFromFile(String uid, int where, boolean removeMinus, String nameDir) { + File mailFile; + Message message = null; + mailFile = new File(nameDir, uid); + + switch (where) { + case NEW: + nameDir = nameDir + "/new"; + if (removeMinus) uid = uid.substring(1); + break; + case DELETED: + nameDir = nameDir + "/deleted"; + break; + case ROOT_AND_NEW: + if (!mailFile.exists()) { + nameDir = nameDir + "/new"; + if (removeMinus) uid = uid.substring(1); + } + break; + default: + break; + } + + mailFile = new File(nameDir, uid); + InputStream mailFileInputStream = null; + try { + mailFileInputStream = new FileInputStream(mailFile); + } catch (FileNotFoundException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + try { + Properties props = new Properties(); + Session session = Session.getDefaultInstance(props, null); + message = new MimeMessage(session, mailFileInputStream); + } catch (MessagingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return message; } - } - - public static void CreateDirs (String accountName, Context ctx) { - String stringDir = ctx.getFilesDir() + "/" + accountName; - File directory = new File (stringDir); - directory.mkdirs(); - directory = new File (stringDir + "/new"); - directory.mkdirs(); - directory = new File (stringDir + "/deleted"); - directory.mkdirs(); - } - - public static void GetOneNote(File outfile, Message notesMessage, NotesDb storedNotes, String accountName, String suid, boolean updateDb) { - OutputStream str=null; - - try { - str = new FileOutputStream(outfile); - } catch (FileNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - try { - notesMessage.writeTo(str); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (MessagingException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - if (!(updateDb)) return; - - String title = null; - String[] rawvalue = null; - // Some servers (such as posteo.de) don't encode non us-ascii characters in subject - // This is a workaround to handle them - // "lä ö ë" subject should be stored as =?charset?encoding?encoded-text?= - // either =?utf-8?B?bMOkIMO2IMOr?= -> Quoted printable - // or =?utf-8?Q?l=C3=A4 =C3=B6 =C3=AB?= -> Base64 - try { rawvalue = notesMessage.getHeader("Subject"); } catch (Exception e) {e.printStackTrace(); }; - try { title = notesMessage.getSubject(); } catch (Exception e) {e.printStackTrace();} - if (rawvalue[0].length() >= 2) { - if (!(rawvalue[0].substring(0,2).equals("=?"))) { - try { title = new String ( title.getBytes("ISO-8859-1")); } catch (Exception e) {e.printStackTrace();} - } - } else { - try { title = new String ( title.getBytes("ISO-8859-1")); } catch (Exception e) {e.printStackTrace();} - } - - // Get INTERNALDATE - String internaldate = null; - Date MessageInternaldate = null; - try { - MessageInternaldate = notesMessage.getReceivedDate(); - } catch (MessagingException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - String DATE_FORMAT = "yyyy-MM-dd HH:MM:ss"; - SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); - internaldate = sdf.format(MessageInternaldate); - - OneNote aNote = new OneNote( - title, - internaldate, - suid); - storedNotes.InsertANoteInDb(aNote, accountName); - } - - public static boolean handleRemoteNotes (Context context, Folder notesFolder, NotesDb storedNotes, String accountName, String usesticky) - throws MessagingException, IOException { - - Message notesMessage; - boolean result = false; - ArrayList uids = new ArrayList(); - ArrayList localListOfNotes = new ArrayList(); - String remoteInternaldate; - String localInternaldate; - Flags flags; - Boolean deleted; - - if (notesFolder.isOpen()) { - if ((notesFolder.getMode() & Folder.READ_ONLY) != 0) - notesFolder.open(Folder.READ_WRITE); - } else { - notesFolder.open(Folder.READ_WRITE); + + public static AppendUID[] sendMessageToRemote(Message[] message) throws MessagingException, IOException { + notesFolder = store.getFolder(sfolder); + if (notesFolder.isOpen()) { + if ((notesFolder.getMode() & Folder.READ_WRITE) != 0) + notesFolder.open(Folder.READ_WRITE); + } else { + notesFolder.open(Folder.READ_WRITE); + } + AppendUID[] uids = ((IMAPFolder) notesFolder).appendUIDMessages(message); + return uids; } - // Get local list of notes uids - String rootString = context.getFilesDir() + "/" + accountName; - File rootDir = new File (rootString); - File[] files = rootDir.listFiles(); - for (File file : files) { - if (file.isFile()) { - localListOfNotes.add(file.getName()); + public static void ClearHomeDir(Account account, Context ctx) { + File directory = new File(ctx.getFilesDir() + "/" + account.name); + try { + FileUtils.deleteDirectory(directory); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); } } - // Add to local device, new notes added to remote - Message[] notesMessages = ((IMAPFolder)notesFolder).getMessagesByUID(1, UIDFolder.LASTUID); - for(int index=notesMessages.length-1; index>=0; index--) { - notesMessage = notesMessages[index]; - Long uid = ((IMAPFolder)notesFolder).getUID(notesMessage); - // Get FLAGS - flags = notesMessage.getFlags(); - deleted = notesMessage.isSet(Flags.Flag.DELETED); - // Buils remote list while in the loop, but only if not deleted on remote - if (!deleted) { - uids.add(((IMAPFolder)notesFolder).getUID(notesMessage)); + public static void CreateDirs(String accountName, Context ctx) { + String stringDir = ctx.getFilesDir() + "/" + accountName; + File directory = new File(stringDir); + directory.mkdirs(); + directory = new File(stringDir + "/new"); + directory.mkdirs(); + directory = new File(stringDir + "/deleted"); + directory.mkdirs(); + } + + public static void GetOneNote(File outfile, Message notesMessage, NotesDb storedNotes, String accountName, String suid, boolean updateDb) { + OutputStream str = null; + + try { + str = new FileOutputStream(outfile); + } catch (FileNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + try { + notesMessage.writeTo(str); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (MessagingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + if (!(updateDb)) return; + + String title = null; + String[] rawvalue = null; + // Some servers (such as posteo.de) don't encode non us-ascii characters in subject + // This is a workaround to handle them + // "lä ö ë" subject should be stored as =?charset?encoding?encoded-text?= + // either =?utf-8?B?bMOkIMO2IMOr?= -> Quoted printable + // or =?utf-8?Q?l=C3=A4 =C3=B6 =C3=AB?= -> Base64 + try { + rawvalue = notesMessage.getHeader("Subject"); + } catch (Exception e) { + e.printStackTrace(); + } + ; + try { + title = notesMessage.getSubject(); + } catch (Exception e) { + e.printStackTrace(); } - String suid = uid.toString(); - if (!(localListOfNotes.contains(suid))) { - File outfile = new File (rootDir, suid); - GetOneNote(outfile, notesMessage, storedNotes, accountName, suid, true); - result = true; - } else if (usesticky.equals("true")) { - //Log.d (TAG,"MANAGE STICKY"); - remoteInternaldate = notesMessage.getSentDate().toLocaleString(); - localInternaldate = storedNotes.GetDate(suid, accountName); - if (!(remoteInternaldate.equals(localInternaldate))) { + if (rawvalue[0].length() >= 2) { + if (!(rawvalue[0].substring(0, 2).equals("=?"))) { + try { + title = new String(title.getBytes("ISO-8859-1")); + } catch (Exception e) { + e.printStackTrace(); + } + } + } else { + try { + title = new String(title.getBytes("ISO-8859-1")); + } catch (Exception e) { + e.printStackTrace(); + } + } + + // Get INTERNALDATE + String internaldate = null; + Date MessageInternaldate = null; + try { + MessageInternaldate = notesMessage.getReceivedDate(); + } catch (MessagingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + String DATE_FORMAT = "yyyy-MM-dd HH:MM:ss"; + SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); + internaldate = sdf.format(MessageInternaldate); + + OneNote aNote = new OneNote( + title, + internaldate, + suid); + storedNotes.InsertANoteInDb(aNote, accountName); + } + + public static boolean handleRemoteNotes(Context context, Folder notesFolder, NotesDb storedNotes, String accountName, String usesticky) + throws MessagingException, IOException { + + Message notesMessage; + boolean result = false; + ArrayList uids = new ArrayList(); + ArrayList localListOfNotes = new ArrayList(); + String remoteInternaldate; + String localInternaldate; + Flags flags; + Boolean deleted; + + if (notesFolder.isOpen()) { + if ((notesFolder.getMode() & Folder.READ_ONLY) != 0) + notesFolder.open(Folder.READ_WRITE); + } else { + notesFolder.open(Folder.READ_WRITE); + } + + // Get local list of notes uids + String rootString = context.getFilesDir() + "/" + accountName; + File rootDir = new File(rootString); + File[] files = rootDir.listFiles(); + for (File file : files) { + if (file.isFile()) { + localListOfNotes.add(file.getName()); + } + } + + // Add to local device, new notes added to remote + Message[] notesMessages = ((IMAPFolder) notesFolder).getMessagesByUID(1, UIDFolder.LASTUID); + for (int index = notesMessages.length - 1; index >= 0; index--) { + notesMessage = notesMessages[index]; + Long uid = ((IMAPFolder) notesFolder).getUID(notesMessage); + // Get FLAGS + flags = notesMessage.getFlags(); + deleted = notesMessage.isSet(Flags.Flag.DELETED); + // Buils remote list while in the loop, but only if not deleted on remote + if (!deleted) { + uids.add(((IMAPFolder) notesFolder).getUID(notesMessage)); + } + String suid = uid.toString(); + if (!(localListOfNotes.contains(suid))) { File outfile = new File (rootDir, suid); - GetOneNote(outfile, notesMessage, storedNotes, accountName, suid, false); + GetOneNote(outfile, notesMessage, storedNotes, accountName, suid, true); result = true; + } else if (usesticky.equals("true")) { + //Log.d (TAG,"MANAGE STICKY"); + remoteInternaldate = notesMessage.getSentDate().toLocaleString(); + localInternaldate = storedNotes.GetDate(suid, accountName); + if (!(remoteInternaldate.equals(localInternaldate))) { + File outfile = new File(rootDir, suid); + GetOneNote(outfile, notesMessage, storedNotes, accountName, suid, false); + result = true; + } } } - } - // Remove from local device, notes removed from remote - for(String suid : localListOfNotes) { - int uid = Integer.valueOf(suid); - if (!(uids.contains(new Long(uid)))) { - // remove file from deleted - File toDelete = new File (rootDir, suid); - toDelete.delete(); - // Remove note from database - storedNotes.DeleteANote(suid, accountName); - result = true; + // Remove from local device, notes removed from remote + for (String suid : localListOfNotes) { + int uid = Integer.valueOf(suid); + if (!(uids.contains(new Long(uid)))) { + // remove file from deleted + File toDelete = new File(rootDir, suid); + toDelete.delete(); + // Remove note from database + storedNotes.DeleteANote(suid, accountName); + result = true; + } } - } - return result; - } + return result; + } public static void RemoveAccount(Context context, Account account) { // remove Shared Preference file String rootString = context.getFilesDir().getParent() + - File.separator + "shared_prefs"; + File.separator + "shared_prefs"; File rootDir = new File (rootString); File toDelete = new File (rootDir, account.name + ".xml"); toDelete.delete(); From e9550869dea96c7a01a6e35f972c71aef94a1de2 Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Sat, 5 Nov 2016 00:27:48 +0100 Subject: [PATCH 005/103] Added proto and acceptcrt properties to Security enum so that there is no longer a need for a switch statement to find them. --- ImapNote2/build.gradle | 4 +- ImapNote2/src/main/AndroidManifest.xml | 2 +- .../AccountConfigurationActivity.java | 68 +++++----- .../ImapNotes2/Data/ConfigurationFile.java | 126 +++++++++--------- .../ImapNotes2/Data/ImapNotes2Account.java | 12 +- .../java/com/Pau/ImapNotes2/Miscs/Imaper.java | 17 ++- .../com/Pau/ImapNotes2/Sync/Security.java | 54 +++++++- 7 files changed, 167 insertions(+), 116 deletions(-) diff --git a/ImapNote2/build.gradle b/ImapNote2/build.gradle index 647de409..101a5c7b 100644 --- a/ImapNote2/build.gradle +++ b/ImapNote2/build.gradle @@ -6,8 +6,8 @@ android { defaultConfig { applicationId "com.Pau.ImapNotes2" - minSdkVersion 16 - targetSdkVersion 16 + minSdkVersion 19 + targetSdkVersion 19 } buildTypes { diff --git a/ImapNote2/src/main/AndroidManifest.xml b/ImapNote2/src/main/AndroidManifest.xml index f512c98c..de1ed8d9 100644 --- a/ImapNote2/src/main/AndroidManifest.xml +++ b/ImapNote2/src/main/AndroidManifest.xml @@ -4,7 +4,7 @@ android:versionCode="40" android:versionName="4.9"> - + diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java index 63975b14..a53c9d39 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java @@ -1,14 +1,5 @@ package com.Pau.ImapNotes2; -import java.util.ArrayList; -import java.util.List; - -import com.Pau.ImapNotes2.Data.ConfigurationFile; -import com.Pau.ImapNotes2.Data.ImapNotes2Account; -import com.Pau.ImapNotes2.Miscs.ImapNotes2Result; -import com.Pau.ImapNotes2.Miscs.Imaper; -import com.Pau.ImapNotes2.Sync.Security; - import android.accounts.Account; import android.accounts.AccountAuthenticatorActivity; import android.accounts.AccountManager; @@ -33,6 +24,14 @@ import android.widget.TextView; import android.widget.Toast; +import com.Pau.ImapNotes2.Data.ConfigurationFile; +import com.Pau.ImapNotes2.Data.ImapNotes2Account; +import com.Pau.ImapNotes2.Miscs.ImapNotes2Result; +import com.Pau.ImapNotes2.Miscs.Imaper; +import com.Pau.ImapNotes2.Sync.Security; + +import java.util.List; + public class AccountConfigurationActivity extends AccountAuthenticatorActivity implements OnItemSelectedListener { public static final int TO_REFRESH = 999; public static final String AUTHORITY = "com.Pau.ImapNotes2.provider"; @@ -50,8 +49,8 @@ public class AccountConfigurationActivity extends AccountAuthenticatorActivity i private CheckBox stickyCheckBox; private Spinner securitySpinner; private ImapNotes2Account imapNotes2Account; - private String security; - private int security_i; + private Security security; + //private int security_i; private String action; private String accountname; private ConfigurationFile settings; @@ -62,7 +61,7 @@ public class AccountConfigurationActivity extends AccountAuthenticatorActivity i @Override public void onClick(View v) { // Click on Login Button - if (((String) accountnameTextView.getText().toString()).contains("'")) { + if (accountnameTextView.getText().toString().contains("'")) { // Single quotation marks are not allowed in accountname Toast.makeText(getApplicationContext(), "Quotation marks are not allowed in accountname", Toast.LENGTH_LONG).show(); @@ -76,7 +75,7 @@ public void onClick(View v) { @Override public void onClick(View v) { // Click on Edit Button - if (((String) accountnameTextView.getText().toString()).contains("'")) { + if (accountnameTextView.getText().toString().contains("'")) { // Single quotation marks are not allowed in accountname Toast.makeText(getApplicationContext(), "Quotation marks are not allowed in accountname", Toast.LENGTH_LONG).show(); @@ -120,7 +119,7 @@ public void onCreate(Bundle savedInstanceState) { list.add("STARTTLS (accept all certificates)"); */ List list = Security.Printables(); - ArrayAdapter dataAdapter = new ArrayAdapter + ArrayAdapter dataAdapter = new ArrayAdapter<> (this, android.R.layout.simple_spinner_item, list); dataAdapter.setDropDownViewResource (android.R.layout.simple_spinner_dropdown_item); @@ -149,9 +148,9 @@ public void onCreate(Bundle savedInstanceState) { this.serverTextView.setText(this.settings.GetServer()); this.portnumTextView.setText(this.settings.GetPortnum()); this.security = this.settings.GetSecurity(); - if (this.security == null) this.security = "0"; - this.security_i = Integer.parseInt(this.security); - this.securitySpinner.setSelection(this.security_i); + // Can never be null. if (this.security == null) this.security = "0"; + int security_i = this.security.ordinal(); + this.securitySpinner.setSelection(security_i); this.stickyCheckBox.setChecked(Boolean.parseBoolean(this.settings.GetUsesticky())); this.syncintervalTextView.setText("15"); this.folderTextView.setText(this.settings.GetFoldername()); @@ -167,24 +166,24 @@ public void onCreate(Bundle savedInstanceState) { } } - if ((this.action == null) || (this.myAccount == null)) { + if ((this.action == null) || (myAccount == null)) { this.action = "CREATE_ACCOUNT"; } if (this.action.equals("EDIT_ACCOUNT")) { // Here we have to edit an existing account this.accountnameTextView.setText(this.accountname); - this.usernameTextView.setText(this.accountManager.getUserData(myAccount, "username")); - this.passwordTextView.setText(this.accountManager.getPassword(myAccount)); - this.serverTextView.setText(this.accountManager.getUserData(myAccount, "server")); - this.portnumTextView.setText(this.accountManager.getUserData(myAccount, "portnum")); - this.security = this.accountManager.getUserData(myAccount, "security"); - this.stickyCheckBox.setChecked(Boolean.parseBoolean(this.accountManager.getUserData(myAccount, "usesticky"))); - this.syncintervalTextView.setText(this.accountManager.getUserData(myAccount, "syncinterval")); - this.folderTextView.setText(this.accountManager.getUserData(myAccount, "imapfolder")); - if (this.security == null) this.security = "0"; - this.security_i = Integer.parseInt(this.security); - this.securitySpinner.setSelection(this.security_i); + this.usernameTextView.setText(accountManager.getUserData(myAccount, "username")); + this.passwordTextView.setText(accountManager.getPassword(myAccount)); + this.serverTextView.setText(accountManager.getUserData(myAccount, "server")); + this.portnumTextView.setText(accountManager.getUserData(myAccount, "portnum")); + this.security = Security.from(accountManager.getUserData(myAccount, "security")); + this.stickyCheckBox.setChecked(Boolean.parseBoolean(accountManager.getUserData(myAccount, "usesticky"))); + this.syncintervalTextView.setText(accountManager.getUserData(myAccount, "syncinterval")); + this.folderTextView.setText(accountManager.getUserData(myAccount, "imapfolder")); + //if (this.security == null) this.security = "0"; + int security_i = security.ordinal(); + this.securitySpinner.setSelection(security_i); Button buttonEdit = new Button(this); buttonEdit.setText("Save"); buttonEdit.setOnClickListener(clickListenerEdit); @@ -215,7 +214,7 @@ public void DoLogin(View v) { this.imapNotes2Account.SetPassword(this.passwordTextView.getText().toString().trim()); this.imapNotes2Account.SetServer(this.serverTextView.getText().toString().trim()); this.imapNotes2Account.SetPortnum(this.portnumTextView.getText().toString()); - this.imapNotes2Account.SetSecurity(this.security); + this.imapNotes2Account.SetSecurity(this.security.name()); this.imapNotes2Account.SetUsesticky(String.valueOf(this.stickyCheckBox.isChecked())); this.imapNotes2Account.SetSyncinterval(this.syncintervalTextView.getText().toString()); this.imapNotes2Account.SetFoldername(this.folderTextView.getText().toString()); @@ -247,7 +246,7 @@ protected Boolean doInBackground(Object... stuffs) { long SYNC_FREQUENCY = (long) stuffs[5]; AccountManager am = AccountManager.get(((AccountConfigurationActivity) stuffs[3])); accountConfigurationActivity.setResult(AccountConfigurationActivity.TO_REFRESH); - Bundle result = null; + Bundle result; if (this.action.equals("EDIT_ACCOUNT")) { result = new Bundle(); result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name); @@ -343,11 +342,8 @@ public boolean onOptionsItemSelected(MenuItem item) { @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { - this.security = Integer.toString(position); - if ((position == 0) || (position == 3) || (position == 4)) - this.portnumTextView.setText("143"); - if ((position == 1) || (position == 2)) - this.portnumTextView.setText("993"); + security = Security.from(position); + this.portnumTextView.setText(security.defaultPort); } @Override diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFile.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFile.java index c7b22d7c..365ee0a1 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFile.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFile.java @@ -15,6 +15,7 @@ import android.util.Xml; import com.Pau.ImapNotes2.ImapNotes2; +import com.Pau.ImapNotes2.Sync.Security; public class ConfigurationFile { @@ -31,7 +32,7 @@ public class ConfigurationFile { // Port number. private String portnum; // TLS, etc. - private String security; + private Security security = Security.None; // ? private String usesticky; // The name of the IMAP folder to be used. @@ -42,111 +43,111 @@ public ConfigurationFile() { try { Document fileToLoad = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse( new File(ImapNotes2.ConfigurationFilePath())); - this.username = this.NodeValueFromXML(fileToLoad, "username"); - this.password = this.NodeValueFromXML(fileToLoad, "password"); - this.server = this.NodeValueFromXML(fileToLoad, "server"); - this.imapfolder = this.NodeValueFromXML(fileToLoad, "imapfolder"); - this.accountname = this.username + "@" + this.server; + username = NodeValueFromXML(fileToLoad, "username"); + password = NodeValueFromXML(fileToLoad, "password"); + server = NodeValueFromXML(fileToLoad, "server"); + imapfolder = NodeValueFromXML(fileToLoad, "imapfolder"); + accountname = username + "@" + server; // All of these can be simplified by initializing the fields to the default values and // only setting when the value exists in the file. - if (this.LoadItemFromXML(fileToLoad, "portnum").getLength() == 0) + if (LoadItemFromXML(fileToLoad, "security").getLength() != 0) { + security = Security.from(NodeValueFromXML(fileToLoad, "security")); + } + if (LoadItemFromXML(fileToLoad, "portnum").getLength() == 0) { // portnum option doesn't exist - this.portnum = ""; - else - this.portnum = this.NodeValueFromXML(fileToLoad, "portnum"); - if (this.LoadItemFromXML(fileToLoad, "security").getLength() == 0) - // security option doesn't exist, say "0" - this.security = "0"; - else - this.security = this.NodeValueFromXML(fileToLoad, "security"); - if (this.LoadItemFromXML(fileToLoad, "usesticky").getLength() == 0) + portnum = security.defaultPort; + } else { + portnum = NodeValueFromXML(fileToLoad, "portnum"); + } + if (LoadItemFromXML(fileToLoad, "usesticky").getLength() == 0) // usesticky option doesn't exist, say no - this.usesticky = "false"; + usesticky = "false"; else - this.usesticky = this.NodeValueFromXML(fileToLoad, "usesticky"); + usesticky = NodeValueFromXML(fileToLoad, "usesticky"); //Log.d(TAG, "conf file present, we read data"); } catch (Exception e) { - // This catch should be turned into a simple if then and the catch + // TODO: This catch should be turned into a simple if then and the catch // reserved for conditions that cannot be checked for. //Log.d(TAG, "Conf file absent, go to the exception that initializes variables"); - this.accountname = ""; - this.username = ""; - this.password = ""; - this.server = ""; - this.portnum = ""; - this.security = "0"; - this.usesticky = "false"; - this.imapfolder = ""; + accountname = ""; + username = ""; + password = ""; + server = ""; + security = Security.None; + portnum = security.defaultPort; + usesticky = "false"; + imapfolder = ""; } } public String GetAccountname() { - return this.accountname; + return accountname; } public String GetUsername() { - return this.username; + return username; } public void SetUsername(String Username) { - this.username = Username; + username = Username; } public String GetPassword() { - return this.password; + return password; } public void SetPassword(String Password) { - this.password = Password; + password = Password; } public String GetServer() { - return this.server; + return server; } public void SetServer(String Server) { - this.server = Server; + server = Server; } public String GetPortnum() { - return this.portnum; + return portnum; } public void SetPortnum(String Portnum) { - this.portnum = Portnum; + portnum = Portnum; } - public String GetSecurity() { - return this.security; + public Security GetSecurity() { + return security; } - public void SetSecurity(String Security) { - this.security = Security; + public void SetSecurity(Security security) { + security = security; } public String GetUsesticky() { - return this.usesticky; + return usesticky; } public void SetUsesticky(String Usesticky) { - this.usesticky = Usesticky; + usesticky = Usesticky; } public String GetFoldername() { - return this.imapfolder; + return imapfolder; } public void Clear() { + //noinspection ResultOfMethodCallIgnored new File(ImapNotes2.ConfigurationFilePath()).delete(); - this.username = null; - this.password = null; - this.server = null; - this.portnum = null; - this.security = null; - this.usesticky = null; - this.imapfolder = null; + username = null; + password = null; + server = null; + portnum = null; + security = null; + usesticky = null; + imapfolder = null; } // This function could take the context as an argument. @@ -161,13 +162,13 @@ public void SaveConfigurationToXML() serializer.setOutput(configurationFile, "UTF-8"); serializer.startDocument(null, true); serializer.startTag(null, "Configuration"); - SerializeText(serializer, "username", this.username); - SerializeText(serializer, "password", this.password); - SerializeText(serializer, "server", this.server); - SerializeText(serializer, "portnum", this.portnum); - SerializeText(serializer, "security", this.security); - SerializeText(serializer, "imapfolder", this.imapfolder); - SerializeText(serializer, "usesticky", this.usesticky); + SerializeText(serializer, "username", username); + SerializeText(serializer, "password", password); + SerializeText(serializer, "server", server); + SerializeText(serializer, "portnum", portnum); + SerializeText(serializer, "security", security.name()); + SerializeText(serializer, "imapfolder", imapfolder); + SerializeText(serializer, "usesticky", usesticky); serializer.endTag(null, "Configuration"); serializer.endDocument(); serializer.flush(); @@ -175,20 +176,23 @@ public void SaveConfigurationToXML() } // Avoid repeated literal tag names. - private void SerializeText(XmlSerializer serializer, String tag, String text) + private void SerializeText(XmlSerializer serializer, + String tag, + String text) throws IOException { serializer.startTag(null, tag); serializer.text(text); serializer.endTag(null, tag); } - private NodeList LoadItemFromXML(Document fileLoaded, String tag) { + private NodeList LoadItemFromXML(Document fileLoaded, + String tag) { return fileLoaded.getElementsByTagName(tag); - } // Reduce clutter and improve maintainability. - private String NodeValueFromXML(Document fileLoaded, String tag) { + private String NodeValueFromXML(Document fileLoaded, + String tag) { return LoadItemFromXML(fileLoaded, tag).item(0).getChildNodes().item(0).getNodeValue(); } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ImapNotes2Account.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ImapNotes2Account.java index dbd55d05..a3c3a9eb 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ImapNotes2Account.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ImapNotes2Account.java @@ -2,6 +2,8 @@ import android.accounts.Account; +import com.Pau.ImapNotes2.Sync.Security; + public class ImapNotes2Account { private String accountname = ""; @@ -9,7 +11,7 @@ public class ImapNotes2Account { private String password = ""; private String server = ""; private String portnum = ""; - private String security = ""; + private Security security = null; private String usesticky = ""; private String syncinterval = "15"; private String imapfolder = ""; @@ -75,12 +77,12 @@ public void SetPortnum(String Portnum) { this.portnum = Portnum; } - public String GetSecurity() { - return this.security; + public Security GetSecurity() { + return security; } - public void SetSecurity(String Security) { - this.security = Security; + public void SetSecurity(Security Security) { + security = Security; } public String GetUsesticky() { diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Imaper.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Imaper.java index bbd09da6..d1514427 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Imaper.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Imaper.java @@ -19,6 +19,7 @@ import javax.mail.Store; import javax.mail.Flags; +import com.Pau.ImapNotes2.Sync.Security; import com.sun.mail.imap.IMAPFolder; import com.sun.mail.imap.IMAPStore; import com.sun.mail.util.MailSSLSocketFactory; @@ -45,7 +46,13 @@ public class Imaper { private Boolean useProxy = false; public static final String PREFS_NAME = "PrefsFile"; - public ImapNotes2Result ConnectToProvider(String username, String password, String server, String portnum, String security, String usesticky, String override) throws MessagingException { + public ImapNotes2Result ConnectToProvider(String username, + String password, + String server, + String portnum, + Security security, + String usesticky, + String override) throws MessagingException { if (this.IsConnected()) this.store.close(); @@ -55,9 +62,9 @@ public ImapNotes2Result ConnectToProvider(String username, String password, Stri } else { this.folderoverride = override; } - this.proto = ""; - this.acceptcrt = ""; - int security_i = Integer.parseInt(security); + this.proto = security.proto; + this.acceptcrt = security.acceptcrt; +/* int security_i = Integer.parseInt(security); switch (security_i) { case 0: // None @@ -88,7 +95,7 @@ public ImapNotes2Result ConnectToProvider(String username, String password, Stri default: this.proto = "Invalid proto"; break; - } + }*/ MailSSLSocketFactory sf = null; try { sf = new MailSSLSocketFactory(); diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/Security.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/Security.java index f17e7c31..966d8558 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/Security.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/Security.java @@ -1,7 +1,13 @@ package com.Pau.ImapNotes2.Sync; +import android.annotation.TargetApi; +import android.os.Build; + import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; +import java.util.Objects; /** * Created by kj on 11/1/16. @@ -11,16 +17,27 @@ */ public enum Security { - None("None"), - SSL_TLS("SSL/TLS"), - SSL_TLS_accept_all_certificates("SSL/TLS (accept all certificates)"), - STARTTLS("STARTTLS"), - STARTTLS_accept_all_certificates("STARTTLS (accept all certificates)"); + None("None", "", "imap", ""), + SSL_TLS("SSL/TLS", "993", "imaps", "false"), + SSL_TLS_accept_all_certificates("SSL/TLS (accept all certificates)", "993", "imaps", "true"), + STARTTLS("STARTTLS", "143", "imaps", "false"), + STARTTLS_accept_all_certificates("STARTTLS (accept all certificates)", "143", "imaps", "true"); + + public final String proto; + public final String acceptcrt; + private final String printable; + public final String defaultPort; - Security(String printable) { + Security(String printable, + String defaultPort, + String proto, + String acceptcrt) { this.printable = printable; + this.defaultPort = defaultPort; + this.proto = proto; + this.acceptcrt = acceptcrt; } public static List Printables() { @@ -30,4 +47,29 @@ public static List Printables() { } return list; } + + // Mapping from integer. See http://dan.clarke.name/2011/07/enum-in-java-with-int-conversion/ + private static final Map _map = new HashMap(); + + static { + for (Security security : Security.values()) + _map.put(security.ordinal(), security); + } + + public static Security from(int ordinal) { + return _map.get(ordinal); + } + + public static Security from(String name) { + for (Security security : Security.values()) { + if (Objects.equals(security.name(), name)) { + return security; + } + } + // Wasn't recognized, try using the ordinal instead + int i = Integer.parseInt(name); + return from(i); + } + + } From 8ae08e715ad204eed286abc1ca2a907e269266f9 Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Sat, 5 Nov 2016 01:25:06 +0100 Subject: [PATCH 006/103] Folder override can never be null so do not check for it. --- .../AccountConfigurationActivity.java | 10 +- .../ImapNotes2/Data/ImapNotes2Account.java | 8 +- .../java/com/Pau/ImapNotes2/Miscs/Imaper.java | 108 +++++++++--------- .../com/Pau/ImapNotes2/Miscs/SyncThread.java | 12 +- .../com/Pau/ImapNotes2/Sync/Security.java | 14 +-- .../com/Pau/ImapNotes2/Sync/SyncAdapter.java | 81 ++++++------- .../com/Pau/ImapNotes2/Sync/SyncUtils.java | 25 ++-- 7 files changed, 136 insertions(+), 122 deletions(-) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java index a53c9d39..a636b74e 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java @@ -32,6 +32,8 @@ import java.util.List; +import static com.Pau.ImapNotes2.Miscs.Imaper.ResultCodeSuccess; + public class AccountConfigurationActivity extends AccountAuthenticatorActivity implements OnItemSelectedListener { public static final int TO_REFRESH = 999; public static final String AUTHORITY = "com.Pau.ImapNotes2.provider"; @@ -214,7 +216,7 @@ public void DoLogin(View v) { this.imapNotes2Account.SetPassword(this.passwordTextView.getText().toString().trim()); this.imapNotes2Account.SetServer(this.serverTextView.getText().toString().trim()); this.imapNotes2Account.SetPortnum(this.portnumTextView.getText().toString()); - this.imapNotes2Account.SetSecurity(this.security.name()); + this.imapNotes2Account.SetSecurity(this.security); this.imapNotes2Account.SetUsesticky(String.valueOf(this.stickyCheckBox.isChecked())); this.imapNotes2Account.SetSyncinterval(this.syncintervalTextView.getText().toString()); this.imapNotes2Account.SetFoldername(this.folderTextView.getText().toString()); @@ -241,7 +243,7 @@ protected Boolean doInBackground(Object... stuffs) { ((ImapNotes2Account) stuffs[1]).GetUsesticky(), ((ImapNotes2Account) stuffs[1]).GetFoldername()); accountConfigurationActivity = (AccountConfigurationActivity) stuffs[3]; - if (this.res.returnCode == 0) { + if (this.res.returnCode == ResultCodeSuccess) { Account account = new Account(((ImapNotes2Account) stuffs[1]).GetAccountname(), "com.Pau.ImapNotes2"); long SYNC_FREQUENCY = (long) stuffs[5]; AccountManager am = AccountManager.get(((AccountConfigurationActivity) stuffs[3])); @@ -256,7 +258,7 @@ protected Boolean doInBackground(Object... stuffs) { am.setUserData(account, "server", ((ImapNotes2Account) stuffs[1]).GetServer()); am.setUserData(account, "portnum", ((ImapNotes2Account) stuffs[1]).GetPortnum()); am.setUserData(account, "syncinterval", ((ImapNotes2Account) stuffs[1]).GetSyncinterval()); - am.setUserData(account, "security", ((ImapNotes2Account) stuffs[1]).GetSecurity()); + am.setUserData(account, "security", ((ImapNotes2Account) stuffs[1]).GetSecurity().name()); am.setUserData(account, "usesticky", ((ImapNotes2Account) stuffs[1]).GetUsesticky()); am.setUserData(account, "imapfolder", ((ImapNotes2Account) stuffs[1]).GetFoldername()); // Run the Sync Adapter Periodically @@ -275,7 +277,7 @@ protected Boolean doInBackground(Object... stuffs) { am.setUserData(account, "server", ((ImapNotes2Account) stuffs[1]).GetServer()); am.setUserData(account, "portnum", ((ImapNotes2Account) stuffs[1]).GetPortnum()); am.setUserData(account, "syncinterval", ((ImapNotes2Account) stuffs[1]).GetSyncinterval()); - am.setUserData(account, "security", ((ImapNotes2Account) stuffs[1]).GetSecurity()); + am.setUserData(account, "security", ((ImapNotes2Account) stuffs[1]).GetSecurity().name()); am.setUserData(account, "usesticky", ((ImapNotes2Account) stuffs[1]).GetUsesticky()); am.setUserData(account, "imapfolder", ((ImapNotes2Account) stuffs[1]).GetFoldername()); // Run the Sync Adapter Periodically diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ImapNotes2Account.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ImapNotes2Account.java index a3c3a9eb..8b9321f4 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ImapNotes2Account.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ImapNotes2Account.java @@ -81,8 +81,12 @@ public Security GetSecurity() { return security; } - public void SetSecurity(Security Security) { - security = Security; + public void SetSecurity(Security security) { + this.security = security; + } + + public void SetSecurity(String security) { + SetSecurity(Security.from(security)); } public String GetUsesticky() { diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Imaper.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Imaper.java index d1514427..3cbe2667 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Imaper.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Imaper.java @@ -36,64 +36,60 @@ public class Imaper { private Store store; private Session session; private static final String TAG = "IN_Imaper"; - private String proto; - private String acceptcrt; private static String sfolder = "Notes"; - private String folderoverride; - private Folder notesFolder = null; + //private Folder notesFolder = null; private ImapNotes2Result res; private Long UIDValidity; - private Boolean useProxy = false; public static final String PREFS_NAME = "PrefsFile"; + public static final int ResultCodeSuccess = 0; + public static final int ResultCodeException = -2; + public static final int ResultCodeCantConnect = -1; + public ImapNotes2Result ConnectToProvider(String username, String password, String server, String portnum, Security security, String usesticky, - String override) throws MessagingException { - if (this.IsConnected()) - this.store.close(); + String folderoverride) throws MessagingException { + if (IsConnected()) { + store.close(); + } res = new ImapNotes2Result(); - if (override == null) { - this.folderoverride = ""; - } else { - this.folderoverride = override; - } - this.proto = security.proto; - this.acceptcrt = security.acceptcrt; + String proto = security.proto; + boolean acceptcrt = security.acceptcrt; /* int security_i = Integer.parseInt(security); switch (security_i) { case 0: // None - this.proto = "imap"; - this.acceptcrt = ""; + proto = "imap"; + acceptcrt = ""; break; case 1: // SSL/TLS - this.proto = "imaps"; - this.acceptcrt = "false"; + proto = "imaps"; + acceptcrt = "false"; break; case 2: // SSL/TLS/TRUST ALL - this.proto = "imaps"; - this.acceptcrt = "true"; + proto = "imaps"; + acceptcrt = "true"; break; case 3: // STARTTLS - this.proto = "imap"; - this.acceptcrt = "false"; + proto = "imap"; + acceptcrt = "false"; break; case 4: // STARTTLS/TRUST ALL - this.proto = "imap"; - this.acceptcrt = "true"; + proto = "imap"; + acceptcrt = "true"; break; ////////////////////// Change this default: - this.proto = "Invalid proto"; + proto = "Invalid proto"; break; }*/ MailSSLSocketFactory sf = null; @@ -101,36 +97,38 @@ public ImapNotes2Result ConnectToProvider(String username, sf = new MailSSLSocketFactory(); } catch (GeneralSecurityException e) { e.printStackTrace(); - this.res.errorMessage = "Can't connect to server"; - this.res.returnCode = -1; - return this.res; + res.errorMessage = "Can't connect to server"; + res.returnCode = -1; + return res; } Properties props = new Properties(); - props.setProperty(String.format("mail.%s.host", this.proto), server); - props.setProperty(String.format("mail.%s.port", this.proto), portnum); - props.setProperty("mail.store.protocol", this.proto); + props.setProperty(String.format("mail.%s.host", proto), server); + props.setProperty(String.format("mail.%s.port", proto), portnum); + props.setProperty("mail.store.protocol", proto); - if ((this.acceptcrt.equals("true"))) { + if (acceptcrt) { sf.setTrustedHosts(new String[]{server}); - if (this.proto.equals("imap")) { + if (proto.equals("imap")) { props.put("mail.imap.ssl.socketFactory", sf); props.put("mail.imap.starttls.enable", "true"); } - } else if (this.acceptcrt.equals("false")) { - props.put(String.format("mail.%s.ssl.checkserveridentity", this.proto), "true"); - if (this.proto.equals("imap")) { + } else if (security != Security.None) { + props.put(String.format("mail.%s.ssl.checkserveridentity", proto), "true"); + if (proto.equals("imap")) { props.put("mail.imap.starttls.enable", "true"); } } - if (this.proto.equals("imaps")) { + if (proto.equals("imaps")) { props.put("mail.imaps.socketFactory", sf); } props.setProperty("mail.imap.connectiontimeout", "1000"); - if (this.useProxy) { + // TODO: implement proxy handling properly. + Boolean useProxy = false; + if (useProxy) { props.put("mail.imap.socks.host", "10.0.2.2"); props.put("mail.imap.socks.port", "1080"); /* @@ -141,40 +139,40 @@ public ImapNotes2Result ConnectToProvider(String username, props.put("sun.net.spi.nameservice.nameservers", "192.168.0.99"); */ } - this.session = Session.getInstance(props, null); -//this.session.setDebug(true); - this.store = this.session.getStore(this.proto); + session = Session.getInstance(props, null); +//session.setDebug(true); + store = session.getStore(proto); try { - this.store.connect(server, username, password); - Boolean hasUIDPLUS = ((IMAPStore) this.store).hasCapability("UIDPLUS"); + store.connect(server, username, password); + Boolean hasUIDPLUS = ((IMAPStore) store).hasCapability("UIDPLUS"); //Log.d(TAG, "has UIDPLUS="+hasUIDPLUS); Folder[] folders = store.getPersonalNamespaces(); Folder folder = folders[0]; //Log.d(TAG,"Personal Namespaces="+folder.getFullName()); - if (this.folderoverride.length() > 0) { - Imaper.sfolder = this.folderoverride; + if (folderoverride.length() > 0) { + Imaper.sfolder = folderoverride; } else if (folder.getFullName().length() == 0) { Imaper.sfolder = "Notes"; } else { char separator = folder.getSeparator(); Imaper.sfolder = folder.getFullName() + separator + "Notes"; } - this.res.errorMessage = ""; - this.res.returnCode = 0; - return this.res; + res.errorMessage = ""; + res.returnCode = ResultCodeSuccess; + return res; } catch (Exception e) { e.printStackTrace(); Log.d(TAG, e.getMessage()); - this.res.errorMessage = e.getMessage(); - this.res.returnCode = -2; - return this.res; + res.errorMessage = e.getMessage(); + res.returnCode = ResultCodeException; + return res; } } public boolean IsConnected() { - return this.store != null && this.store.isConnected(); + return store != null && store.isConnected(); } // Put values in shared preferences: @@ -182,7 +180,7 @@ public void SetPrefs() { SharedPreferences preferences = ImapNotes2.getAppContext().getSharedPreferences(Listactivity.imapNotes2Account.GetAccountname(), Context.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putString("Name", "valid_data"); - editor.putLong("UIDValidity", this.UIDValidity); + editor.putLong("UIDValidity", UIDValidity); editor.apply(); } @@ -191,7 +189,7 @@ public void GetPrefs() { SharedPreferences preferences = (ImapNotes2.getAppContext()).getSharedPreferences(Listactivity.imapNotes2Account.GetAccountname(), Context.MODE_PRIVATE); String name = preferences.getString("Name", ""); if (!name.equalsIgnoreCase("")) { - this.UIDValidity = preferences.getLong("UIDValidity", -1); + UIDValidity = preferences.getLong("UIDValidity", -1); } } } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/SyncThread.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/SyncThread.java index 3f926be1..edcf25a3 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/SyncThread.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/SyncThread.java @@ -35,12 +35,12 @@ protected Boolean doInBackground(Object... stuffs) { this.notesList = ((ArrayList) stuffs[2]); this.storedNotes = ((NotesDb) stuffs[5]); this.ctx = (Context) stuffs[6]; - username = ((ImapNotes2Account) stuffs[1]).GetUsername(); - password = ((ImapNotes2Account) stuffs[1]).GetPassword(); - server = ((ImapNotes2Account) stuffs[1]).GetServer(); - portnum = ((ImapNotes2Account) stuffs[1]).GetPortnum(); - security = ((ImapNotes2Account) stuffs[1]).GetSecurity(); - usesticky = ((ImapNotes2Account) stuffs[1]).GetUsesticky(); + //username = ((ImapNotes2Account) stuffs[1]).GetUsername(); + //password = ((ImapNotes2Account) stuffs[1]).GetPassword(); + //server = ((ImapNotes2Account) stuffs[1]).GetServer(); + //portnum = ((ImapNotes2Account) stuffs[1]).GetPortnum(); + //security = ((ImapNotes2Account) stuffs[1]).GetSecurity(); + //usesticky = ((ImapNotes2Account) stuffs[1]).GetUsesticky(); if (this.storedNotes == null) this.storedNotes = new NotesDb(this.ctx); diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/Security.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/Security.java index 966d8558..f9a88216 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/Security.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/Security.java @@ -17,14 +17,14 @@ */ public enum Security { - None("None", "", "imap", ""), - SSL_TLS("SSL/TLS", "993", "imaps", "false"), - SSL_TLS_accept_all_certificates("SSL/TLS (accept all certificates)", "993", "imaps", "true"), - STARTTLS("STARTTLS", "143", "imaps", "false"), - STARTTLS_accept_all_certificates("STARTTLS (accept all certificates)", "143", "imaps", "true"); + None("None", "", "imap", false), + SSL_TLS("SSL/TLS", "993", "imaps", false), + SSL_TLS_accept_all_certificates("SSL/TLS (accept all certificates)", "993", "imaps", true), + STARTTLS("STARTTLS", "143", "imaps", false), + STARTTLS_accept_all_certificates("STARTTLS (accept all certificates)", "143", "imaps", true); public final String proto; - public final String acceptcrt; + public final boolean acceptcrt; private final String printable; @@ -33,7 +33,7 @@ public enum Security { Security(String printable, String defaultPort, String proto, - String acceptcrt) { + boolean acceptcrt) { this.printable = printable; this.defaultPort = defaultPort; this.proto = proto; diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java index 8e211799..403edc8a 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java @@ -13,6 +13,7 @@ import java.io.File; import java.io.IOException; + import javax.mail.Flags; import javax.mail.Message; import javax.mail.MessagingException; @@ -23,6 +24,8 @@ import com.Pau.ImapNotes2.Sync.SyncUtils; import com.sun.mail.imap.AppendUID; +import static com.Pau.ImapNotes2.Miscs.Imaper.ResultCodeSuccess; + /// A SyncAdapter provides methods to be called by the Android /// framework when the framework is ready for the synchronization to /// occur. The application does not need to consider threading @@ -82,13 +85,13 @@ public void onPerformSync(Account account, Bundle extras, String authority, // Connect to remote and get UIDValidity this.res = ConnectToRemote(); - if (this.res.returnCode != 0) { + if (this.res.returnCode != ResultCodeSuccess) { storedNotes.CloseDb(); // Notify Listactivity that it's finished, but it can't // refresh display Intent i = new Intent(SyncService.SYNC_FINISHED); - i.putExtra("ACCOUNTNAME",account.name); + i.putExtra("ACCOUNTNAME", account.name); isChanged = false; isSynced = false; i.putExtra("CHANGED", isChanged); @@ -106,23 +109,23 @@ public void onPerformSync(Account account, Bundle extras, String authority, storedNotes.ClearDb(account.name); // delete notes in folders for this account and recreate dirs SyncUtils.ClearHomeDir(account, this.context); - SyncUtils.CreateDirs (account.name, this.context); + SyncUtils.CreateDirs(account.name, this.context); // Get all notes from remote and replace local SyncUtils.GetNotes(account, this.res.notesFolder, this.context, storedNotes); storedNotes.CloseDb(); } catch (MessagingException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + // TODO Auto-generated catch block + e.printStackTrace(); } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + // TODO Auto-generated catch block + e.printStackTrace(); } SyncUtils.SetUIDValidity(account, this.res.UIDValidity, this.context); // Notify Listactivity that it's finished, and that it can refresh display Intent i = new Intent(SyncService.SYNC_FINISHED); - i.putExtra("ACCOUNTNAME",account.name); + i.putExtra("ACCOUNTNAME", account.name); isChanged = true; isSynced = true; i.putExtra("CHANGED", isChanged); @@ -144,15 +147,15 @@ public void onPerformSync(Account account, Bundle extras, String authority, // handle notes created or removed on remote boolean remoteNotesManaged = false; String usesticky = am.getUserData(account, "usesticky"); - try { - remoteNotesManaged = SyncUtils.handleRemoteNotes(context, res.notesFolder, storedNotes, account.name, usesticky); - } catch (MessagingException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + try { + remoteNotesManaged = SyncUtils.handleRemoteNotes(context, res.notesFolder, storedNotes, account.name, usesticky); + } catch (MessagingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } if (remoteNotesManaged) isChanged = true; storedNotes.CloseDb(); @@ -162,11 +165,11 @@ public void onPerformSync(Account account, Bundle extras, String authority, //Log.d(TAG, "Network synchronization complete of account: "+account.name); // Notify Listactivity that it's finished, and that it can refresh display Intent i = new Intent(SyncService.SYNC_FINISHED); - i.putExtra("ACCOUNTNAME",account.name); + i.putExtra("ACCOUNTNAME", account.name); i.putExtra("CHANGED", isChanged); isSynced = true; i.putExtra("SYNCED", isSynced); - i.putExtra("SYNCINTERVAL", syncinterval); + i.putExtra("SYNCINTERVAL", syncinterval); context.sendBroadcast(i); } @@ -174,20 +177,20 @@ ImapNotes2Result ConnectToRemote() { AccountManager am = AccountManager.get(this.context); ImapNotes2Result res = null; try { - res = SyncUtils.ConnectToRemote( - am.getUserData(account, "username"), - am.getPassword(account), - am.getUserData(account, "server"), - am.getUserData(account, "portnum"), - am.getUserData(account, "security"), - am.getUserData(account, "usesticky"), - am.getUserData(account, "imapfolder")); + res = SyncUtils.ConnectToRemote( + am.getUserData(account, "username"), + am.getPassword(account), + am.getUserData(account, "server"), + am.getUserData(account, "portnum"), + Security.from(am.getUserData(account, "security")), + am.getUserData(account, "usesticky"), + am.getUserData(account, "imapfolder")); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } - if (res.returnCode != 0) { - Log.d(TAG,"Connection problem !!!"); + if (res.returnCode != ResultCodeSuccess) { + Log.d(TAG, "Connection problem !!!"); } return res; } @@ -197,8 +200,8 @@ private boolean handleNewNotes() { boolean newNotesManaged = false; AppendUID[] uids = null; String rootString = context.getFilesDir() + "/" + account.name; - File rootDir = new File (rootString); - File dirNew = new File (rootDir + "/new"); + File rootDir = new File(rootString); + File dirNew = new File(rootDir + "/new"); listOfNew = dirNew.list(); for (String fileNew : listOfNew) { //Log.d(TAG,"New Note to process:"+fileNew); @@ -206,13 +209,13 @@ private boolean handleNewNotes() { // Read local new message from file message = SyncUtils.ReadMailFromFile(fileNew, NEW, false, rootString); try { - message.setFlag(Flags.Flag.SEEN,true); // set message as seen + message.setFlag(Flags.Flag.SEEN, true); // set message as seen } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Send this new message to remote - final MimeMessage[] msg = {(MimeMessage)message}; + final MimeMessage[] msg = {(MimeMessage) message}; try { uids = SyncUtils.sendMessageToRemote(msg); @@ -225,10 +228,10 @@ private boolean handleNewNotes() { } // Update uid in database entry String newuid = Long.toString(uids[0].uid); - storedNotes.UpdateANote(fileNew,newuid,account.name); + storedNotes.UpdateANote(fileNew, newuid, account.name); // move new note from new dir, one level up - File fileInNew = new File (dirNew, fileNew); - File to = new File (rootDir, newuid); + File fileInNew = new File(dirNew, fileNew); + File to = new File(rootDir, newuid); fileInNew.renameTo(to); } return newNotesManaged; @@ -238,8 +241,8 @@ private boolean handleDeletedNotes() { Message message = null; boolean deletedNotesManaged = false; String rootString = context.getFilesDir() + "/" + account.name; - File rootDir = new File (rootString); - File dirDeleted = new File (rootDir + "/deleted"); + File rootDir = new File(rootString); + File dirDeleted = new File(rootDir + "/deleted"); listOfDeleted = dirDeleted.list(); for (String fileDeleted : listOfDeleted) { try { @@ -249,7 +252,7 @@ private boolean handleDeletedNotes() { } // remove file from deleted - File toDelete = new File (dirDeleted, fileDeleted); + File toDelete = new File(dirDeleted, fileDeleted); toDelete.delete(); deletedNotesManaged = true; } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java index 76db2d9a..1218b4db 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java @@ -30,6 +30,7 @@ import javax.mail.Session; import com.Pau.ImapNotes2.Data.NotesDb; import com.Pau.ImapNotes2.Miscs.ImapNotes2Result; +import com.Pau.ImapNotes2.Miscs.Imaper; import com.Pau.ImapNotes2.Miscs.OneNote; import com.Pau.ImapNotes2.Miscs.Sticky; import com.sun.mail.util.MailSSLSocketFactory; @@ -43,13 +44,16 @@ import android.content.SharedPreferences; import android.util.Log; +import static com.Pau.ImapNotes2.Miscs.Imaper.ResultCodeException; +import static com.Pau.ImapNotes2.Miscs.Imaper.ResultCodeSuccess; + public class SyncUtils { static Store store; static Session session; static final String TAG = "IN_SyncUtils"; static String proto; - static String acceptcrt; + private static boolean acceptcrt; static String sfolder = "Notes"; static private String folderoverride; static Folder notesFolder = null; @@ -64,7 +68,7 @@ public static ImapNotes2Result ConnectToRemote(String username, String password, String server, String portnum, - String security, + Security security, String usesticky, String override) throws MessagingException { if (IsConnected()) @@ -74,8 +78,9 @@ public static ImapNotes2Result ConnectToRemote(String username, folderoverride = (override == null) ? "" : override; - proto = ""; - acceptcrt = ""; + proto = security.proto; + acceptcrt = security.acceptcrt; +/* int security_i = Integer.parseInt(security); switch (security_i) { case 0: @@ -107,13 +112,14 @@ public static ImapNotes2Result ConnectToRemote(String username, // TODO: Make sure that this cannot happen. throw new InvalidParameterException("Invalid security: <" + security + ">"); } +*/ MailSSLSocketFactory sf = null; try { sf = new MailSSLSocketFactory(); } catch (GeneralSecurityException e) { e.printStackTrace(); res.errorMessage = "Can't connect to server"; - res.returnCode = -1; + res.returnCode = Imaper.ResultCodeCantConnect; return res; } @@ -123,13 +129,13 @@ public static ImapNotes2Result ConnectToRemote(String username, props.setProperty(String.format("mail.%s.port", proto), portnum); props.setProperty("mail.store.protocol", proto); - if ((acceptcrt.equals("true"))) { + if ((acceptcrt)) { sf.setTrustedHosts(new String[]{server}); if (proto.equals("imap")) { props.put("mail.imap.ssl.socketFactory", sf); props.put("mail.imap.starttls.enable", "true"); } - } else if (acceptcrt.equals("false")) { + } else if (security != Security.None) { props.put(String.format("mail.%s.ssl.checkserveridentity", proto), "true"); if (proto.equals("imap")) { props.put("mail.imap.starttls.enable", "true"); @@ -141,6 +147,7 @@ public static ImapNotes2Result ConnectToRemote(String username, } props.setProperty("mail.imap.connectiontimeout", "1000"); + // TODO: use user defined proxy. if (useProxy) { props.put("mail.imap.socks.host", "10.0.2.2"); props.put("mail.imap.socks.port", "1080"); @@ -168,13 +175,13 @@ public static ImapNotes2Result ConnectToRemote(String username, notesFolder = store.getFolder(sfolder); res.UIDValidity = ((IMAPFolder) notesFolder).getUIDValidity(); res.errorMessage = ""; - res.returnCode = 0; + res.returnCode = ResultCodeSuccess; res.notesFolder = notesFolder; return res; } catch (Exception e) { Log.d(TAG, e.getMessage()); res.errorMessage = e.getMessage(); - res.returnCode = -2; + res.returnCode = ResultCodeException; return res; } From e70bb2199430dc227de14511e2c7eca8cc3ee446 Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Sun, 6 Nov 2016 19:17:35 +0100 Subject: [PATCH 007/103] Add notes to README.md to explain the reason for the fork and briefly describe what has been done. --- .../ImapNotes2/Data/ImapNotes2Account.java | 8 +-- .../com/Pau/ImapNotes2/Miscs/OneNote.java | 24 +++---- .../Pau/ImapNotes2/Miscs/UpdateThread.java | 21 +++--- .../com/Pau/ImapNotes2/NewNoteActivity.java | 1 + .../Pau/ImapNotes2/NoteDetailActivity.java | 64 +++++++++++++------ ImapNote2/src/main/res/layout/note_detail.xml | 2 + .../src/main/res/layout/note_element.xml | 4 ++ README.md | 26 ++++++++ 8 files changed, 104 insertions(+), 46 deletions(-) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ImapNotes2Account.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ImapNotes2Account.java index 8b9321f4..6a92e1a0 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ImapNotes2Account.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ImapNotes2Account.java @@ -12,7 +12,7 @@ public class ImapNotes2Account { private String server = ""; private String portnum = ""; private Security security = null; - private String usesticky = ""; + private boolean usesticky = false; private String syncinterval = "15"; private String imapfolder = ""; private Boolean accountHasChanged = false; @@ -89,11 +89,11 @@ public void SetSecurity(String security) { SetSecurity(Security.from(security)); } - public String GetUsesticky() { + public boolean GetUsesticky() { return this.usesticky; } - public void SetUsesticky(String Usesticky) { + public void SetUsesticky(boolean Usesticky) { this.usesticky = Usesticky; } @@ -131,7 +131,7 @@ public void Clear() { this.server = null; this.portnum = null; this.security = null; - this.usesticky = null; + this.usesticky = false; this.imapfolder = null; this.accountHasChanged = false; } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/OneNote.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/OneNote.java index d3951ee8..dd13f78b 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/OneNote.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/OneNote.java @@ -2,6 +2,7 @@ import java.util.HashMap; +/* Represents metadata aboit a note. */ public class OneNote extends HashMap { /** @@ -9,14 +10,14 @@ public class OneNote extends HashMap { */ private static final long serialVersionUID = 1L; - public OneNote() { - super(); - this.put("title", "No Title"); - this.put("date", "No Date"); - this.put("uid", "0"); - - } + /* public OneNote() { + super(); + this.put("title", "No Title"); + this.put("date", "No Date"); + this.put("uid", "0"); + } + */ public OneNote(String title, String date, String uid) { super(); this.put("title", title); @@ -37,10 +38,11 @@ public String GetUid() { return this.get("uid"); } - public void SetTitle(String title) { - this.put("title", title); - } - + /* + public void SetTitle(String title) { + this.put("title", title); + } + */ public void SetDate(String date) { this.put("date", date); } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java index 9c2cece7..ec37274e 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java @@ -39,10 +39,9 @@ public class UpdateThread extends AsyncTask { Imaper imapFolder; boolean bool_to_return; OneNote currentNote = null; - NotesDb storedNotes; - Context ctx; + private NotesDb storedNotes; + private Context ctx; ProgressDialog pDialog; - String body = null; String action; private static final String TAG = "UpdateThread"; @@ -81,11 +80,9 @@ protected Boolean doInBackground(Object... stuffs) { String[] tok = noteTxt.split("\n", 2); String title = tok[0]; String position = "0 0 0 0"; - if (((ImapNotes2Account) stuffs[1]).GetUsesticky().equals("true")) - body = noteTxt.replaceAll("\n", "\\\\n"); - else - body = "" + this.noteBody + ""; - + String body = (((ImapNotes2Account) stuffs[1]).GetUsesticky()) ? + noteTxt.replaceAll("\n", "\\\\n") : + "" + this.noteBody + ""; String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; Date date = new Date(); @@ -149,7 +146,9 @@ private void MoveMailToDeleted(String suid) { } } - public void WriteMailToNew(OneNote note, String usesticky, String noteBody) throws MessagingException, IOException { + public void WriteMailToNew(OneNote note, + boolean usesticky, + String noteBody) throws MessagingException, IOException { String body = null; // Here we add the new note to the "new" folder @@ -157,7 +156,7 @@ public void WriteMailToNew(OneNote note, String usesticky, String noteBody) thro Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); - if (usesticky.equals("true")) { + if (usesticky) { body = "BEGIN:STICKYNOTE\nCOLOR:" + this.color + "\nTEXT:" + noteBody + "\nPOSITION:0 0 0 0\nEND:STICKYNOTE"; message.setText(body); @@ -182,7 +181,7 @@ public void WriteMailToNew(OneNote note, String usesticky, String noteBody) thro // Remove (CET) or (GMT+1) part as asked in github issue #13 String headerDate = (mailDateFormat.format(new Date())).replaceAll("\\(.*$", ""); message.addHeader("Date", headerDate); - //déterminer l'uid temporaire + // Get temporary UID String uid = Integer.toString(Math.abs(Integer.parseInt(note.GetUid()))); File directory = new File((ImapNotes2.getAppContext()).getFilesDir() + "/" + Listactivity.imapNotes2Account.GetAccountname() + "/new"); diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NewNoteActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NewNoteActivity.java index 87b7e2c7..20854c31 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NewNoteActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NewNoteActivity.java @@ -54,4 +54,5 @@ public boolean onOptionsItemSelected(MenuItem item) { return super.onOptionsItemSelected(item); } } + } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java index 1149019b..c34da882 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java @@ -26,8 +26,10 @@ import android.graphics.Color; import android.os.Bundle; import android.support.v4.app.NavUtils; +import android.text.Editable; import android.text.Html; import android.text.Spanned; +import android.text.TextWatcher; import android.util.Log; import android.view.Menu; import android.view.MenuItem; @@ -40,7 +42,7 @@ public class NoteDetailActivity extends Activity { private static final int DELETE_BUTTON = 3; private static final int EDIT_BUTTON = 6; private HashMap hm; - private String usesticky; + private boolean usesticky; private Sticky sticky; private String stringres; private String color; @@ -61,9 +63,9 @@ public void onCreate(Bundle savedInstanceState) { WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN ); - this.hm = (HashMap) getIntent().getExtras().get("selectedNote"); - this.usesticky = (String) getIntent().getExtras().get("useSticky"); - + Bundle extras = getIntent().getExtras(); + this.hm = (HashMap) extras.get("selectedNote"); + this.usesticky = "true".equals((String) extras.get("useSticky")); suid = this.hm.get("uid").toString(); String rootDir = (ImapNotes2.getAppContext()).getFilesDir() + "/" + Listactivity.imapNotes2Account.GetAccountname(); @@ -73,7 +75,28 @@ public void onCreate(Bundle savedInstanceState) { position = sticky.GetPosition(); color = sticky.GetColor(); Spanned plainText = Html.fromHtml(stringres); - ((EditText) findViewById(R.id.bodyView)).setText(plainText); + EditText editText = ((EditText) findViewById(R.id.bodyView)); + editText.setText(plainText); + // Watch for changes to that we can auto save. + // See http://stackoverflow.com/questions/7117209/how-to-know-key-presses-in-edittext#14251047 + editText.addTextChangedListener(new TextWatcher() { + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + //here is your code + } + + @Override + public void beforeTextChanged(CharSequence s, int start, int count, + int after) { + // TODO Auto-generated method stub + } + + @Override + public void afterTextChanged(Editable s) { + // TODO Auto-generated method stub + } + + }); this.ResetColors(); //invalidateOptionsMenu(); } @@ -123,11 +146,7 @@ public boolean onPrepareOptionsMenu(Menu menu) { MenuItem item = menu.findItem(R.id.color); super.onPrepareOptionsMenu(menu); //depending on your conditions, either enable/disable - if (this.usesticky.equals("true")) { - item.setVisible(true); - } else { - item.setVisible(false); - } + item.setVisible(usesticky); menu.findItem(this.realColor).setChecked(true); return true; } @@ -142,16 +161,7 @@ public boolean onOptionsItemSelected(MenuItem item) { finish();//finishing activity return true; case R.id.save: - //Log.d(TAG,"We ask to modify Message #"+this.currentNote.get("number")); - intent.putExtra("EDIT_ITEM_NUM_IMAP", suid); - intent.putExtra("EDIT_ITEM_TXT", - Html.toHtml(((EditText) findViewById(R.id.bodyView)).getText())); - if (!this.usesticky.equals("true")) { - this.color = "NONE"; - } - intent.putExtra("EDIT_ITEM_COLOR", this.color); - setResult(NoteDetailActivity.EDIT_BUTTON, intent); - finish();//finishing activity + Save(); return true; case android.R.id.home: NavUtils.navigateUpFromSameTask(this); @@ -186,6 +196,20 @@ public boolean onOptionsItemSelected(MenuItem item) { } } + private void Save() { + Log.d(TAG, "Save"); + Intent intent = new Intent(); + intent.putExtra("EDIT_ITEM_NUM_IMAP", suid); + intent.putExtra("EDIT_ITEM_TXT", + Html.toHtml(((EditText) findViewById(R.id.bodyView)).getText())); + if (!usesticky) { + this.color = "NONE"; + } + intent.putExtra("EDIT_ITEM_COLOR", this.color); + setResult(NoteDetailActivity.EDIT_BUTTON, intent); + finish();//finishing activity + + } public enum Colors { BLUE, WHITE, diff --git a/ImapNote2/src/main/res/layout/note_detail.xml b/ImapNote2/src/main/res/layout/note_detail.xml index 0b5c57f8..9bb603ff 100644 --- a/ImapNote2/src/main/res/layout/note_detail.xml +++ b/ImapNote2/src/main/res/layout/note_detail.xml @@ -1,4 +1,6 @@ + + + + + + Date: Sun, 6 Nov 2016 22:59:33 +0100 Subject: [PATCH 008/103] Start moving arguments from execute to constructor to avoid the need to cast. Moved notes.org to root. --- .../AccountConfigurationActivity.java | 101 ++++++++++++------ .../ImapNotes2/Data/ConfigurationFile.java | 21 ++-- .../java/com/Pau/ImapNotes2/Listactivity.java | 38 +++---- .../java/com/Pau/ImapNotes2/Miscs/Imaper.java | 2 +- .../Pau/ImapNotes2/Miscs/UpdateThread.java | 1 + notes.org | 77 +++++++++++++ 6 files changed, 177 insertions(+), 63 deletions(-) create mode 100644 notes.org diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java index a636b74e..40bc12d4 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java @@ -153,7 +153,7 @@ public void onCreate(Bundle savedInstanceState) { // Can never be null. if (this.security == null) this.security = "0"; int security_i = this.security.ordinal(); this.securitySpinner.setSelection(security_i); - this.stickyCheckBox.setChecked(Boolean.parseBoolean(this.settings.GetUsesticky())); + this.stickyCheckBox.setChecked(this.settings.GetUsesticky()); this.syncintervalTextView.setText("15"); this.folderTextView.setText(this.settings.GetFoldername()); } @@ -217,36 +217,67 @@ public void DoLogin(View v) { this.imapNotes2Account.SetServer(this.serverTextView.getText().toString().trim()); this.imapNotes2Account.SetPortnum(this.portnumTextView.getText().toString()); this.imapNotes2Account.SetSecurity(this.security); - this.imapNotes2Account.SetUsesticky(String.valueOf(this.stickyCheckBox.isChecked())); + this.imapNotes2Account.SetUsesticky(this.stickyCheckBox.isChecked()); this.imapNotes2Account.SetSyncinterval(this.syncintervalTextView.getText().toString()); this.imapNotes2Account.SetFoldername(this.folderTextView.getText().toString()); long SYNC_FREQUENCY = Long.parseLong(syncintervalTextView.getText().toString(), 10) * 60; - new LoginThread().execute(this.imapFolder, this.imapNotes2Account, loadingDialog, this, this.action, SYNC_FREQUENCY); - + new LoginThread( + this.imapFolder, + this.imapNotes2Account, + loadingDialog, + this, + this.action, + SYNC_FREQUENCY).execute(); } - class LoginThread extends AsyncTask { + class LoginThread extends AsyncTask { + /* + private final int ParamImapFolder = 0; + private final int ParamImapNotes2Account = 1; + private final int ParamImapLoadingDialog = 2; + private final int ParamAccountConfigurationActivity = 3; + private final int ParamAction = 4; + private final int ParamSyncPeriod = 5; + */ + private final ImapNotes2Account imapNotes2Account; + private final ProgressDialog progressDialog; + private final long SYNC_FREQUENCY; private AccountConfigurationActivity accountConfigurationActivity; private ImapNotes2Result res = new ImapNotes2Result(); String action; - protected Boolean doInBackground(Object... stuffs) { - this.action = (String) stuffs[4]; + public LoginThread(Imaper mapFolder, + ImapNotes2Account imapNotes2Account, + ProgressDialog loadingDialog, + AccountConfigurationActivity accountConfigurationActivity, + String action, + long SYNC_FREQUENCY) { + this.imapNotes2Account = imapNotes2Account; + this.progressDialog = loadingDialog; + this.accountConfigurationActivity = accountConfigurationActivity; + this.action = action; + this.SYNC_FREQUENCY = SYNC_FREQUENCY; + + } + + protected Boolean doInBackground(Void... none) { + //this.action = (String) stuffs[ParamAction]; try { - this.res = ((Imaper) stuffs[0]).ConnectToProvider( - ((ImapNotes2Account) stuffs[1]).GetUsername(), - ((ImapNotes2Account) stuffs[1]).GetPassword(), - ((ImapNotes2Account) stuffs[1]).GetServer(), - ((ImapNotes2Account) stuffs[1]).GetPortnum(), - ((ImapNotes2Account) stuffs[1]).GetSecurity(), - ((ImapNotes2Account) stuffs[1]).GetUsesticky(), - ((ImapNotes2Account) stuffs[1]).GetFoldername()); - accountConfigurationActivity = (AccountConfigurationActivity) stuffs[3]; + //ImapNotes2Account imapNotes2Account= ((ImapNotes2Account) stuffs[ParamImapNotes2Account]); + this.res = imapFolder.ConnectToProvider( + imapNotes2Account.GetUsername(), + imapNotes2Account.GetPassword(), + imapNotes2Account.GetServer(), + imapNotes2Account.GetPortnum(), + imapNotes2Account.GetSecurity(), + imapNotes2Account.GetUsesticky(), + imapNotes2Account.GetFoldername()); + //accountConfigurationActivity = acountConfigurationActivity; if (this.res.returnCode == ResultCodeSuccess) { - Account account = new Account(((ImapNotes2Account) stuffs[1]).GetAccountname(), "com.Pau.ImapNotes2"); - long SYNC_FREQUENCY = (long) stuffs[5]; - AccountManager am = AccountManager.get(((AccountConfigurationActivity) stuffs[3])); + Account account = new Account(imapNotes2Account.GetAccountname(), "com.Pau.ImapNotes2"); + //long SYNC_FREQUENCY = (long) stuffs[ParamSyncPeriod]; + AccountManager am = AccountManager.get(accountConfigurationActivity); accountConfigurationActivity.setResult(AccountConfigurationActivity.TO_REFRESH); Bundle result; if (this.action.equals("EDIT_ACCOUNT")) { @@ -254,13 +285,13 @@ protected Boolean doInBackground(Object... stuffs) { result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name); result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type); setAccountAuthenticatorResult(result); - am.setUserData(account, "username", ((ImapNotes2Account) stuffs[1]).GetUsername()); - am.setUserData(account, "server", ((ImapNotes2Account) stuffs[1]).GetServer()); - am.setUserData(account, "portnum", ((ImapNotes2Account) stuffs[1]).GetPortnum()); - am.setUserData(account, "syncinterval", ((ImapNotes2Account) stuffs[1]).GetSyncinterval()); - am.setUserData(account, "security", ((ImapNotes2Account) stuffs[1]).GetSecurity().name()); - am.setUserData(account, "usesticky", ((ImapNotes2Account) stuffs[1]).GetUsesticky()); - am.setUserData(account, "imapfolder", ((ImapNotes2Account) stuffs[1]).GetFoldername()); + am.setUserData(account, "username", imapNotes2Account.GetUsername()); + am.setUserData(account, "server", imapNotes2Account.GetServer()); + am.setUserData(account, "portnum", imapNotes2Account.GetPortnum()); + am.setUserData(account, "syncinterval", imapNotes2Account.GetSyncinterval()); + am.setUserData(account, "security", imapNotes2Account.GetSecurity().name()); + am.setUserData(account, "usesticky", String.valueOf(imapNotes2Account.GetUsesticky())); + am.setUserData(account, "imapfolder", imapNotes2Account.GetFoldername()); // Run the Sync Adapter Periodically ContentResolver.setIsSyncable(account, AUTHORITY, 1); ContentResolver.setSyncAutomatically(account, AUTHORITY, true); @@ -268,18 +299,18 @@ protected Boolean doInBackground(Object... stuffs) { this.res.errorMessage = "Account has been modified"; return true; } else { - if (am.addAccountExplicitly(account, ((ImapNotes2Account) stuffs[1]).GetPassword(), null)) { + if (am.addAccountExplicitly(account, imapNotes2Account.GetPassword(), null)) { result = new Bundle(); result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name); result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type); setAccountAuthenticatorResult(result); - am.setUserData(account, "username", ((ImapNotes2Account) stuffs[1]).GetUsername()); - am.setUserData(account, "server", ((ImapNotes2Account) stuffs[1]).GetServer()); - am.setUserData(account, "portnum", ((ImapNotes2Account) stuffs[1]).GetPortnum()); - am.setUserData(account, "syncinterval", ((ImapNotes2Account) stuffs[1]).GetSyncinterval()); - am.setUserData(account, "security", ((ImapNotes2Account) stuffs[1]).GetSecurity().name()); - am.setUserData(account, "usesticky", ((ImapNotes2Account) stuffs[1]).GetUsesticky()); - am.setUserData(account, "imapfolder", ((ImapNotes2Account) stuffs[1]).GetFoldername()); + am.setUserData(account, "username", imapNotes2Account.GetUsername()); + am.setUserData(account, "server", imapNotes2Account.GetServer()); + am.setUserData(account, "portnum", imapNotes2Account.GetPortnum()); + am.setUserData(account, "syncinterval", imapNotes2Account.GetSyncinterval()); + am.setUserData(account, "security", imapNotes2Account.GetSecurity().name()); + am.setUserData(account, "usesticky", String.valueOf(imapNotes2Account.GetUsesticky())); + am.setUserData(account, "imapfolder", imapNotes2Account.GetFoldername()); // Run the Sync Adapter Periodically ContentResolver.setIsSyncable(account, AUTHORITY, 1); ContentResolver.setSyncAutomatically(account, AUTHORITY, true); @@ -295,7 +326,7 @@ protected Boolean doInBackground(Object... stuffs) { } catch (Exception e) { e.printStackTrace(); } finally { - ((ProgressDialog) stuffs[2]).dismiss(); + progressDialog.dismiss(); } return false; } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFile.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFile.java index 365ee0a1..68b5e2dd 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFile.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFile.java @@ -22,6 +22,7 @@ public class ConfigurationFile { // For logging. private static final String TAG = "IN_ConfigurationFile"; + // TODO: make all fields final. // The account name is the concatenation of the username and server. private String accountname; // User name on the IMAP server. @@ -34,7 +35,7 @@ public class ConfigurationFile { // TLS, etc. private Security security = Security.None; // ? - private String usesticky; + private boolean usesticky; // The name of the IMAP folder to be used. private String imapfolder; @@ -61,9 +62,9 @@ public ConfigurationFile() { } if (LoadItemFromXML(fileToLoad, "usesticky").getLength() == 0) // usesticky option doesn't exist, say no - usesticky = "false"; + usesticky = false; else - usesticky = NodeValueFromXML(fileToLoad, "usesticky"); + usesticky = Boolean.parseBoolean(NodeValueFromXML(fileToLoad, "usesticky")); //Log.d(TAG, "conf file present, we read data"); } catch (Exception e) { @@ -76,7 +77,7 @@ public ConfigurationFile() { server = ""; security = Security.None; portnum = security.defaultPort; - usesticky = "false"; + usesticky = false; imapfolder = ""; } } @@ -125,13 +126,15 @@ public void SetSecurity(Security security) { security = security; } - public String GetUsesticky() { + public boolean GetUsesticky() { return usesticky; } +/* - public void SetUsesticky(String Usesticky) { - usesticky = Usesticky; + public void SetUsesticky(boolean usesticky) { + this.usesticky = usesticky; } +*/ public String GetFoldername() { return imapfolder; @@ -146,7 +149,7 @@ public void Clear() { server = null; portnum = null; security = null; - usesticky = null; + usesticky = false; imapfolder = null; } @@ -168,7 +171,7 @@ public void SaveConfigurationToXML() SerializeText(serializer, "portnum", portnum); SerializeText(serializer, "security", security.name()); SerializeText(serializer, "imapfolder", imapfolder); - SerializeText(serializer, "usesticky", usesticky); + SerializeText(serializer, "usesticky", String.valueOf(usesticky)); serializer.endTag(null, "Configuration"); serializer.endDocument(); serializer.flush(); diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java index 42187b7d..9e34e26b 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java @@ -352,17 +352,18 @@ public void onItemSelected(AdapterView parent, View view, int pos, long id) { } } // End of code - Listactivity.imapNotes2Account.SetAccountname(account.name); - Listactivity.imapNotes2Account.SetUsername(Listactivity.accountManager.getUserData(account, "username")); + ImapNotes2Account imapNotes2Account = Listactivity.imapNotes2Account; + imapNotes2Account.SetAccountname(account.name); + imapNotes2Account.SetUsername(Listactivity.accountManager.getUserData(account, "username")); String pwd = Listactivity.accountManager.getPassword(account); - Listactivity.imapNotes2Account.SetPassword(pwd); - Listactivity.imapNotes2Account.SetServer(Listactivity.accountManager.getUserData(account, "server")); - Listactivity.imapNotes2Account.SetPortnum(Listactivity.accountManager.getUserData(account, "portnum")); - Listactivity.imapNotes2Account.SetSecurity(Listactivity.accountManager.getUserData(account, "security")); - Listactivity.imapNotes2Account.SetUsesticky(accountManager.getUserData(account, "usesticky")); - Listactivity.imapNotes2Account.SetSyncinterval(Listactivity.accountManager.getUserData(account, "syncinterval")); - Listactivity.imapNotes2Account.SetaccountHasChanged(); - Listactivity.imapNotes2Account.SetAccount(account); + imapNotes2Account.SetPassword(pwd); + imapNotes2Account.SetServer(Listactivity.accountManager.getUserData(account, "server")); + imapNotes2Account.SetPortnum(Listactivity.accountManager.getUserData(account, "portnum")); + imapNotes2Account.SetSecurity(Listactivity.accountManager.getUserData(account, "security")); + imapNotes2Account.SetUsesticky("true".equals(accountManager.getUserData(account, "usesticky"))); + imapNotes2Account.SetSyncinterval(Listactivity.accountManager.getUserData(account, "syncinterval")); + imapNotes2Account.SetaccountHasChanged(); + imapNotes2Account.SetAccount(account); this.RefreshList(); } @@ -382,15 +383,16 @@ private void updateAccountSpinner() { if (Listactivity.currentList.size() == 1) { Account account = Listactivity.accounts[0]; - Listactivity.imapNotes2Account.SetUsername(Listactivity.accountManager.getUserData(account, "username")); + ImapNotes2Account imapNotes2Account = Listactivity.imapNotes2Account; + imapNotes2Account.SetUsername(Listactivity.accountManager.getUserData(account, "username")); String pwd = Listactivity.accountManager.getPassword(account); - Listactivity.imapNotes2Account.SetPassword(pwd); - Listactivity.imapNotes2Account.SetServer(Listactivity.accountManager.getUserData(account, "server")); - Listactivity.imapNotes2Account.SetPortnum(Listactivity.accountManager.getUserData(account, "portnum")); - Listactivity.imapNotes2Account.SetSecurity(Listactivity.accountManager.getUserData(account, "security")); - Listactivity.imapNotes2Account.SetUsesticky(accountManager.getUserData(account, "usesticky")); - Listactivity.imapNotes2Account.SetSyncinterval(Listactivity.accountManager.getUserData(account, "syncinterval")); - Listactivity.imapNotes2Account.SetaccountHasChanged(); + imapNotes2Account.SetPassword(pwd); + imapNotes2Account.SetServer(Listactivity.accountManager.getUserData(account, "server")); + imapNotes2Account.SetPortnum(Listactivity.accountManager.getUserData(account, "portnum")); + imapNotes2Account.SetSecurity(Listactivity.accountManager.getUserData(account, "security")); + imapNotes2Account.SetUsesticky("true".equals(accountManager.getUserData(account, "usesticky"))); + imapNotes2Account.SetSyncinterval(Listactivity.accountManager.getUserData(account, "syncinterval")); + imapNotes2Account.SetaccountHasChanged(); } } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Imaper.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Imaper.java index 3cbe2667..1eb1ec83 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Imaper.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Imaper.java @@ -51,7 +51,7 @@ public ImapNotes2Result ConnectToProvider(String username, String server, String portnum, Security security, - String usesticky, + boolean usesticky, String folderoverride) throws MessagingException { if (IsConnected()) { store.close(); diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java index ec37274e..61491dea 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java @@ -30,6 +30,7 @@ import android.util.Log; import android.widget.SimpleAdapter; +// TODO: move arguments from execute to constructor. public class UpdateThread extends AsyncTask { NotesListAdapter adapter; ArrayList notesList; diff --git a/notes.org b/notes.org new file mode 100644 index 00000000..8566e932 --- /dev/null +++ b/notes.org @@ -0,0 +1,77 @@ +* To do + +Add configuration for directory synchronization. + +Implement synchronization. + +Implement text file merging + +Implement Unix and Windows desktop versions. + +* Directory synchronization + +Use the already implemented accounts. + +One sync. definition consists of the following: + +- Account to be used + +- Root directory on the server + +- Root directory on the local system. Use a directory chooser dialog. + +- Include sub-directories or not. Checkbox. + +- A list of glob patterns defining the files to be included. Simple + text field. Use white space as separator. + +- A list of glob patterns defining the files to be excluded. Simple + text field. Use white space as separator. + +- The maximum allowed network transfer rate. + +- The length of time allowed for a complete scan of the directory. + + +Use android.os.PatternMatcher to implement the globbing. + + +* Merge + +Should be a three way merge so that we can automatically resolve as +many conflicts as possible. This means keeping two copies on the +server. + +We can avoid worrying about race conditions by recognizing that this +is essentially a single user system so simultaneous access will be +unlikely (not impossible though) + +https://gist.github.com/stepchowfun/4713315 + + +* Sync adapters + +See: + +- https://developer.android.com/training/sync-adapters/creating-sync-adapter.html + +- src/main/res/xml/syncadapter.xml + +- src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java + +- src/main/java/com/Pau/ImapNotes2/Sync/SyncService.java + + + +* Auto save + +First question is how is the note saved in the first place. + +Then can we do it automatically and then can we start the sync early? + + +* SQLite database + +This is used to store metadata about the notes. The notes themselves +are stored as files in a sub-directory named after the account to +which they belong. From 357d6f2d05ae591c3d6abf49cfc60dda266e6e8f Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Mon, 7 Nov 2016 17:03:55 +0100 Subject: [PATCH 009/103] Created ConfigurationFieldNames class to name the fields in the config. file. --- .../AccountConfigurationActivity.java | 82 +++++++++---------- .../Data/ConfigurationFieldNames.java | 17 ++++ .../ImapNotes2/Data/ConfigurationFile.java | 34 ++++---- .../java/com/Pau/ImapNotes2/Listactivity.java | 30 +++---- .../Pau/ImapNotes2/NoteDetailActivity.java | 4 +- .../com/Pau/ImapNotes2/Sync/SyncAdapter.java | 15 ++-- 6 files changed, 100 insertions(+), 82 deletions(-) create mode 100644 ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFieldNames.java diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java index 40bc12d4..846f2a68 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java @@ -24,6 +24,7 @@ import android.widget.TextView; import android.widget.Toast; +import com.Pau.ImapNotes2.Data.ConfigurationFieldNames; import com.Pau.ImapNotes2.Data.ConfigurationFile; import com.Pau.ImapNotes2.Data.ImapNotes2Account; import com.Pau.ImapNotes2.Miscs.ImapNotes2Result; @@ -175,14 +176,14 @@ public void onCreate(Bundle savedInstanceState) { if (this.action.equals("EDIT_ACCOUNT")) { // Here we have to edit an existing account this.accountnameTextView.setText(this.accountname); - this.usernameTextView.setText(accountManager.getUserData(myAccount, "username")); + this.usernameTextView.setText(GetConfigValue(ConfigurationFieldNames.UserName)); this.passwordTextView.setText(accountManager.getPassword(myAccount)); - this.serverTextView.setText(accountManager.getUserData(myAccount, "server")); - this.portnumTextView.setText(accountManager.getUserData(myAccount, "portnum")); - this.security = Security.from(accountManager.getUserData(myAccount, "security")); - this.stickyCheckBox.setChecked(Boolean.parseBoolean(accountManager.getUserData(myAccount, "usesticky"))); - this.syncintervalTextView.setText(accountManager.getUserData(myAccount, "syncinterval")); - this.folderTextView.setText(accountManager.getUserData(myAccount, "imapfolder")); + this.serverTextView.setText(GetConfigValue(ConfigurationFieldNames.Server)); + this.portnumTextView.setText(GetConfigValue(ConfigurationFieldNames.PortNumber)); + this.security = Security.from(GetConfigValue(ConfigurationFieldNames.Security)); + this.stickyCheckBox.setChecked(Boolean.parseBoolean(GetConfigValue(ConfigurationFieldNames.UseSticky))); + this.syncintervalTextView.setText(GetConfigValue(ConfigurationFieldNames.SyncInterval)); + this.folderTextView.setText(GetConfigValue(ConfigurationFieldNames.ImapFolder)); //if (this.security == null) this.security = "0"; int security_i = security.ordinal(); this.securitySpinner.setSelection(security_i); @@ -208,44 +209,41 @@ public void onCreate(Bundle savedInstanceState) { ); } + private String GetConfigValue(String name) { + return accountManager.getUserData(myAccount, name); + } + // DoLogin method is defined in account_selection.xml (account_selection layout) public void DoLogin(View v) { ProgressDialog loadingDialog = ProgressDialog.show(this, "ImapNotes2", "Logging into your account... ", true); - this.imapNotes2Account.SetAccountname(this.accountnameTextView.getText().toString().trim()); - this.imapNotes2Account.SetUsername(this.usernameTextView.getText().toString().trim()); - this.imapNotes2Account.SetPassword(this.passwordTextView.getText().toString().trim()); - this.imapNotes2Account.SetServer(this.serverTextView.getText().toString().trim()); - this.imapNotes2Account.SetPortnum(this.portnumTextView.getText().toString()); - this.imapNotes2Account.SetSecurity(this.security); - this.imapNotes2Account.SetUsesticky(this.stickyCheckBox.isChecked()); - this.imapNotes2Account.SetSyncinterval(this.syncintervalTextView.getText().toString()); - this.imapNotes2Account.SetFoldername(this.folderTextView.getText().toString()); + imapNotes2Account.SetAccountname(accountnameTextView.getText().toString().trim()); + imapNotes2Account.SetUsername(usernameTextView.getText().toString().trim()); + imapNotes2Account.SetPassword(passwordTextView.getText().toString().trim()); + imapNotes2Account.SetServer(serverTextView.getText().toString().trim()); + imapNotes2Account.SetPortnum(portnumTextView.getText().toString()); + imapNotes2Account.SetSecurity(security); + imapNotes2Account.SetUsesticky(stickyCheckBox.isChecked()); + imapNotes2Account.SetSyncinterval(syncintervalTextView.getText().toString()); + imapNotes2Account.SetFoldername(folderTextView.getText().toString()); long SYNC_FREQUENCY = Long.parseLong(syncintervalTextView.getText().toString(), 10) * 60; new LoginThread( - this.imapFolder, - this.imapNotes2Account, + imapFolder, + imapNotes2Account, loadingDialog, this, - this.action, + action, SYNC_FREQUENCY).execute(); } class LoginThread extends AsyncTask { - /* - private final int ParamImapFolder = 0; - private final int ParamImapNotes2Account = 1; - private final int ParamImapLoadingDialog = 2; - private final int ParamAccountConfigurationActivity = 3; - private final int ParamAction = 4; - private final int ParamSyncPeriod = 5; - */ + private final ImapNotes2Account imapNotes2Account; private final ProgressDialog progressDialog; private final long SYNC_FREQUENCY; private AccountConfigurationActivity accountConfigurationActivity; private ImapNotes2Result res = new ImapNotes2Result(); - String action; + private String action; public LoginThread(Imaper mapFolder, ImapNotes2Account imapNotes2Account, @@ -285,13 +283,13 @@ protected Boolean doInBackground(Void... none) { result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name); result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type); setAccountAuthenticatorResult(result); - am.setUserData(account, "username", imapNotes2Account.GetUsername()); - am.setUserData(account, "server", imapNotes2Account.GetServer()); - am.setUserData(account, "portnum", imapNotes2Account.GetPortnum()); - am.setUserData(account, "syncinterval", imapNotes2Account.GetSyncinterval()); - am.setUserData(account, "security", imapNotes2Account.GetSecurity().name()); - am.setUserData(account, "usesticky", String.valueOf(imapNotes2Account.GetUsesticky())); - am.setUserData(account, "imapfolder", imapNotes2Account.GetFoldername()); + am.setUserData(account, ConfigurationFieldNames.UserName, imapNotes2Account.GetUsername()); + am.setUserData(account, ConfigurationFieldNames.Server, imapNotes2Account.GetServer()); + am.setUserData(account, ConfigurationFieldNames.PortNumber, imapNotes2Account.GetPortnum()); + am.setUserData(account, ConfigurationFieldNames.SyncInterval, imapNotes2Account.GetSyncinterval()); + am.setUserData(account, ConfigurationFieldNames.Security, imapNotes2Account.GetSecurity().name()); + am.setUserData(account, ConfigurationFieldNames.UseSticky, String.valueOf(imapNotes2Account.GetUsesticky())); + am.setUserData(account, ConfigurationFieldNames.ImapFolder, imapNotes2Account.GetFoldername()); // Run the Sync Adapter Periodically ContentResolver.setIsSyncable(account, AUTHORITY, 1); ContentResolver.setSyncAutomatically(account, AUTHORITY, true); @@ -304,13 +302,13 @@ protected Boolean doInBackground(Void... none) { result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name); result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type); setAccountAuthenticatorResult(result); - am.setUserData(account, "username", imapNotes2Account.GetUsername()); - am.setUserData(account, "server", imapNotes2Account.GetServer()); - am.setUserData(account, "portnum", imapNotes2Account.GetPortnum()); - am.setUserData(account, "syncinterval", imapNotes2Account.GetSyncinterval()); - am.setUserData(account, "security", imapNotes2Account.GetSecurity().name()); - am.setUserData(account, "usesticky", String.valueOf(imapNotes2Account.GetUsesticky())); - am.setUserData(account, "imapfolder", imapNotes2Account.GetFoldername()); + am.setUserData(account, ConfigurationFieldNames.UserName, imapNotes2Account.GetUsername()); + am.setUserData(account, ConfigurationFieldNames.Server, imapNotes2Account.GetServer()); + am.setUserData(account, ConfigurationFieldNames.PortNumber, imapNotes2Account.GetPortnum()); + am.setUserData(account, ConfigurationFieldNames.SyncInterval, imapNotes2Account.GetSyncinterval()); + am.setUserData(account, ConfigurationFieldNames.Security, imapNotes2Account.GetSecurity().name()); + am.setUserData(account, ConfigurationFieldNames.UseSticky, String.valueOf(imapNotes2Account.GetUsesticky())); + am.setUserData(account, ConfigurationFieldNames.ImapFolder, imapNotes2Account.GetFoldername()); // Run the Sync Adapter Periodically ContentResolver.setIsSyncable(account, AUTHORITY, 1); ContentResolver.setSyncAutomatically(account, AUTHORITY, true); diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFieldNames.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFieldNames.java new file mode 100644 index 00000000..558b4e91 --- /dev/null +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFieldNames.java @@ -0,0 +1,17 @@ +package com.Pau.ImapNotes2.Data; + +/** + * Created by kj on 11/7/16. + */ + +public final class ConfigurationFieldNames { + public static final String UserName = "username"; + public static final String Password = "password"; + public static final String UseSticky = "usesticky"; + public static final String ImapFolder = "imapfolder"; + public static final String Server = "server"; + public static final String PortNumber = "portnum"; + public static final String SyncInterval = "syncinterval"; + public static final String Security = "security"; + +} diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFile.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFile.java index 68b5e2dd..15b3d598 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFile.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFile.java @@ -44,27 +44,27 @@ public ConfigurationFile() { try { Document fileToLoad = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse( new File(ImapNotes2.ConfigurationFilePath())); - username = NodeValueFromXML(fileToLoad, "username"); - password = NodeValueFromXML(fileToLoad, "password"); - server = NodeValueFromXML(fileToLoad, "server"); - imapfolder = NodeValueFromXML(fileToLoad, "imapfolder"); + username = NodeValueFromXML(fileToLoad, ConfigurationFieldNames.UserName); + password = NodeValueFromXML(fileToLoad, ConfigurationFieldNames.Password); + server = NodeValueFromXML(fileToLoad, ConfigurationFieldNames.Server); + imapfolder = NodeValueFromXML(fileToLoad, ConfigurationFieldNames.ImapFolder); accountname = username + "@" + server; // All of these can be simplified by initializing the fields to the default values and // only setting when the value exists in the file. - if (LoadItemFromXML(fileToLoad, "security").getLength() != 0) { - security = Security.from(NodeValueFromXML(fileToLoad, "security")); + if (LoadItemFromXML(fileToLoad, ConfigurationFieldNames.Security).getLength() != 0) { + security = Security.from(NodeValueFromXML(fileToLoad, ConfigurationFieldNames.Security)); } - if (LoadItemFromXML(fileToLoad, "portnum").getLength() == 0) { + if (LoadItemFromXML(fileToLoad, ConfigurationFieldNames.PortNumber).getLength() == 0) { // portnum option doesn't exist portnum = security.defaultPort; } else { - portnum = NodeValueFromXML(fileToLoad, "portnum"); + portnum = NodeValueFromXML(fileToLoad, ConfigurationFieldNames.PortNumber); } - if (LoadItemFromXML(fileToLoad, "usesticky").getLength() == 0) + if (LoadItemFromXML(fileToLoad, ConfigurationFieldNames.UseSticky).getLength() == 0) // usesticky option doesn't exist, say no usesticky = false; else - usesticky = Boolean.parseBoolean(NodeValueFromXML(fileToLoad, "usesticky")); + usesticky = Boolean.parseBoolean(NodeValueFromXML(fileToLoad, ConfigurationFieldNames.UseSticky)); //Log.d(TAG, "conf file present, we read data"); } catch (Exception e) { @@ -165,13 +165,13 @@ public void SaveConfigurationToXML() serializer.setOutput(configurationFile, "UTF-8"); serializer.startDocument(null, true); serializer.startTag(null, "Configuration"); - SerializeText(serializer, "username", username); - SerializeText(serializer, "password", password); - SerializeText(serializer, "server", server); - SerializeText(serializer, "portnum", portnum); - SerializeText(serializer, "security", security.name()); - SerializeText(serializer, "imapfolder", imapfolder); - SerializeText(serializer, "usesticky", String.valueOf(usesticky)); + SerializeText(serializer, ConfigurationFieldNames.UserName, username); + SerializeText(serializer, ConfigurationFieldNames.Password, password); + SerializeText(serializer, ConfigurationFieldNames.Server, server); + SerializeText(serializer, ConfigurationFieldNames.PortNumber, portnum); + SerializeText(serializer, ConfigurationFieldNames.Security, security.name()); + SerializeText(serializer, ConfigurationFieldNames.ImapFolder, imapfolder); + SerializeText(serializer, ConfigurationFieldNames.UseSticky, String.valueOf(usesticky)); serializer.endTag(null, "Configuration"); serializer.endDocument(); serializer.flush(); diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java index 9e34e26b..5a8b4df7 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java @@ -13,6 +13,7 @@ import org.apache.commons.io.FileUtils; //import com.Pau.ImapNotes2.R; +import com.Pau.ImapNotes2.Data.ConfigurationFieldNames; import com.Pau.ImapNotes2.Data.NotesDb; import com.Pau.ImapNotes2.Miscs.Imaper; import com.Pau.ImapNotes2.Miscs.OneNote; @@ -58,6 +59,7 @@ import android.widget.TextView; import android.widget.Toast; + public class Listactivity extends Activity implements OnItemSelectedListener, Filterable { private static final int SEE_DETAIL = 2; private static final int DELETE_BUTTON = 3; @@ -145,9 +147,9 @@ public void onCreate(Bundle savedInstanceState) { // When item is clicked, we go to NoteDetailActivity listview.setOnItemClickListener(new OnItemClickListener() { - public void onItemClick(AdapterView arg0, View widget, int selectedNote, long arg3) { + public void onItemClick(AdapterView parent, View widget, int selectedNote, long rowId) { Intent toDetail = new Intent(widget.getContext(), NoteDetailActivity.class); - toDetail.putExtra("selectedNote", (OneNote) arg0.getItemAtPosition(selectedNote)); + toDetail.putExtra("selectedNote", (OneNote) parent.getItemAtPosition(selectedNote)); toDetail.putExtra("useSticky", Listactivity.imapNotes2Account.GetUsesticky()); startActivityForResult(toDetail, SEE_DETAIL); } @@ -354,14 +356,14 @@ public void onItemSelected(AdapterView parent, View view, int pos, long id) { // End of code ImapNotes2Account imapNotes2Account = Listactivity.imapNotes2Account; imapNotes2Account.SetAccountname(account.name); - imapNotes2Account.SetUsername(Listactivity.accountManager.getUserData(account, "username")); + imapNotes2Account.SetUsername(Listactivity.accountManager.getUserData(account, ConfigurationFieldNames.UserName)); String pwd = Listactivity.accountManager.getPassword(account); imapNotes2Account.SetPassword(pwd); - imapNotes2Account.SetServer(Listactivity.accountManager.getUserData(account, "server")); - imapNotes2Account.SetPortnum(Listactivity.accountManager.getUserData(account, "portnum")); - imapNotes2Account.SetSecurity(Listactivity.accountManager.getUserData(account, "security")); - imapNotes2Account.SetUsesticky("true".equals(accountManager.getUserData(account, "usesticky"))); - imapNotes2Account.SetSyncinterval(Listactivity.accountManager.getUserData(account, "syncinterval")); + imapNotes2Account.SetServer(Listactivity.accountManager.getUserData(account, ConfigurationFieldNames.Server)); + imapNotes2Account.SetPortnum(Listactivity.accountManager.getUserData(account, ConfigurationFieldNames.PortNumber)); + imapNotes2Account.SetSecurity(Listactivity.accountManager.getUserData(account, ConfigurationFieldNames.Security)); + imapNotes2Account.SetUsesticky("true".equals(accountManager.getUserData(account, ConfigurationFieldNames.UseSticky))); + imapNotes2Account.SetSyncinterval(Listactivity.accountManager.getUserData(account, ConfigurationFieldNames.SyncInterval)); imapNotes2Account.SetaccountHasChanged(); imapNotes2Account.SetAccount(account); this.RefreshList(); @@ -384,14 +386,14 @@ private void updateAccountSpinner() { if (Listactivity.currentList.size() == 1) { Account account = Listactivity.accounts[0]; ImapNotes2Account imapNotes2Account = Listactivity.imapNotes2Account; - imapNotes2Account.SetUsername(Listactivity.accountManager.getUserData(account, "username")); + imapNotes2Account.SetUsername(Listactivity.accountManager.getUserData(account, ConfigurationFieldNames.UserName)); String pwd = Listactivity.accountManager.getPassword(account); imapNotes2Account.SetPassword(pwd); - imapNotes2Account.SetServer(Listactivity.accountManager.getUserData(account, "server")); - imapNotes2Account.SetPortnum(Listactivity.accountManager.getUserData(account, "portnum")); - imapNotes2Account.SetSecurity(Listactivity.accountManager.getUserData(account, "security")); - imapNotes2Account.SetUsesticky("true".equals(accountManager.getUserData(account, "usesticky"))); - imapNotes2Account.SetSyncinterval(Listactivity.accountManager.getUserData(account, "syncinterval")); + imapNotes2Account.SetServer(Listactivity.accountManager.getUserData(account, ConfigurationFieldNames.Server)); + imapNotes2Account.SetPortnum(Listactivity.accountManager.getUserData(account, ConfigurationFieldNames.PortNumber)); + imapNotes2Account.SetSecurity(Listactivity.accountManager.getUserData(account, ConfigurationFieldNames.Security)); + imapNotes2Account.SetUsesticky("true".equals(accountManager.getUserData(account, ConfigurationFieldNames.UseSticky))); + imapNotes2Account.SetSyncinterval(Listactivity.accountManager.getUserData(account, ConfigurationFieldNames.SyncInterval)); imapNotes2Account.SetaccountHasChanged(); } } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java index c34da882..33f7a406 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java @@ -65,7 +65,7 @@ public void onCreate(Bundle savedInstanceState) { Bundle extras = getIntent().getExtras(); this.hm = (HashMap) extras.get("selectedNote"); - this.usesticky = "true".equals((String) extras.get("useSticky")); + this.usesticky = (boolean) extras.get("useSticky"); suid = this.hm.get("uid").toString(); String rootDir = (ImapNotes2.getAppContext()).getFilesDir() + "/" + Listactivity.imapNotes2Account.GetAccountname(); @@ -77,7 +77,7 @@ public void onCreate(Bundle savedInstanceState) { Spanned plainText = Html.fromHtml(stringres); EditText editText = ((EditText) findViewById(R.id.bodyView)); editText.setText(plainText); - // Watch for changes to that we can auto save. + // TODO: Watch for changes to that we can auto save. // See http://stackoverflow.com/questions/7117209/how-to-know-key-presses-in-edittext#14251047 editText.addTextChangedListener(new TextWatcher() { @Override diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java index 403edc8a..09e91072 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java @@ -19,6 +19,7 @@ import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; +import com.Pau.ImapNotes2.Data.ConfigurationFieldNames; import com.Pau.ImapNotes2.Data.NotesDb; import com.Pau.ImapNotes2.Miscs.ImapNotes2Result; import com.Pau.ImapNotes2.Sync.SyncUtils; @@ -146,7 +147,7 @@ public void onPerformSync(Account account, Bundle extras, String authority, // handle notes created or removed on remote boolean remoteNotesManaged = false; - String usesticky = am.getUserData(account, "usesticky"); + String usesticky = am.getUserData(account, ConfigurationFieldNames.UseSticky); try { remoteNotesManaged = SyncUtils.handleRemoteNotes(context, res.notesFolder, storedNotes, account.name, usesticky); } catch (MessagingException e) { @@ -178,13 +179,13 @@ ImapNotes2Result ConnectToRemote() { ImapNotes2Result res = null; try { res = SyncUtils.ConnectToRemote( - am.getUserData(account, "username"), + am.getUserData(account, ConfigurationFieldNames.UserName), am.getPassword(account), - am.getUserData(account, "server"), - am.getUserData(account, "portnum"), - Security.from(am.getUserData(account, "security")), - am.getUserData(account, "usesticky"), - am.getUserData(account, "imapfolder")); + am.getUserData(account, ConfigurationFieldNames.Server), + am.getUserData(account, ConfigurationFieldNames.PortNumber), + Security.from(am.getUserData(account, ConfigurationFieldNames.Security)), + am.getUserData(account, ConfigurationFieldNames.UseSticky), + am.getUserData(account, ConfigurationFieldNames.ImapFolder)); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); From 296883935c514d91683b08d79b1ee2f8c12de717 Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Mon, 7 Nov 2016 17:27:50 +0100 Subject: [PATCH 010/103] Fixed bug introduced by changes. Bug was incorrect casting of useSticky. --- .../src/main/java/com/Pau/ImapNotes2/NewNoteActivity.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NewNoteActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NewNoteActivity.java index 20854c31..3525d630 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NewNoteActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NewNoteActivity.java @@ -14,7 +14,7 @@ public class NewNoteActivity extends Activity { private static final int SAVE_BUTTON = 5; private static final String TAG = "IN_NewNoteActivity"; - private String sticky; + private boolean sticky; private String color = "NONE"; public void onCreate(Bundle savedInstanceState) { @@ -22,7 +22,7 @@ public void onCreate(Bundle savedInstanceState) { setContentView(R.layout.new_note); getActionBar().setDisplayHomeAsUpEnabled(true); this.ResetColors(); - this.sticky = (String) getIntent().getExtras().get("usesSticky"); + this.sticky = (boolean) getIntent().getExtras().get("usesSticky"); } private void ResetColors() { @@ -40,7 +40,7 @@ public boolean onOptionsItemSelected(MenuItem item) { case R.id.save: Intent intent = new Intent(); intent.putExtra("SAVE_ITEM", Html.toHtml(((EditText) findViewById(R.id.editNote)).getText())); - if (this.sticky.equals("true")) { + if (this.sticky) { this.color = "YELLOW"; } intent.putExtra("SAVE_ITEM_COLOR", this.color); From 74e5e2e5b11fa14557e89fe081bae1830d1010a1 Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Mon, 7 Nov 2016 19:05:30 +0100 Subject: [PATCH 011/103] Make patterns for analysing sticky notes static final so that we do not reuse variables and so that we do not compile them every time. --- .../java/com/Pau/ImapNotes2/Miscs/Sticky.java | 13 ++-- .../Pau/ImapNotes2/NoteDetailActivity.java | 62 +++++++++---------- .../com/Pau/ImapNotes2/Sync/SyncUtils.java | 27 +++++--- 3 files changed, 56 insertions(+), 46 deletions(-) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Sticky.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Sticky.java index 4adcdf59..6e2be475 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Sticky.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Sticky.java @@ -1,18 +1,21 @@ package com.Pau.ImapNotes2.Miscs; +import static com.Pau.ImapNotes2.NoteDetailActivity.Colors; + public class Sticky { private static String text; private static String position; - private static String color; + private static Colors color; public Sticky() { Sticky.text = ""; Sticky.position = "0 0 0 0"; - Sticky.color = "YELLOW"; + Sticky.color = Colors.YELLOW; } - public Sticky(String text, String position, String color) { + public Sticky(String text, String position, + Colors color) { Sticky.text = text; Sticky.position = position; Sticky.color = color; @@ -26,7 +29,7 @@ public String GetText() { return Sticky.text; } - public String GetColor() { + public Colors GetColor() { return Sticky.color; } @@ -38,7 +41,7 @@ public void SetPosition(String position) { Sticky.position = position; } - public void SetColor(String color) { + public void SetColor(Colors color) { Sticky.color = color; } } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java index 33f7a406..a5f113d4 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java @@ -1,26 +1,5 @@ package com.Pau.ImapNotes2; -import java.util.HashMap; - -import javax.mail.Message; -import javax.mail.MessagingException; -import javax.mail.Multipart; -import javax.mail.Part; -import javax.mail.internet.ContentType; -import javax.mail.internet.MimeMessage; - -import org.apache.commons.io.IOUtils; - -import com.Pau.ImapNotes2.Miscs.OneNote; -import com.Pau.ImapNotes2.Miscs.Sticky; -import com.Pau.ImapNotes2.Sync.SyncUtils; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - import android.app.Activity; import android.content.Intent; import android.graphics.Color; @@ -37,6 +16,24 @@ import android.view.WindowManager; import android.widget.EditText; +import com.Pau.ImapNotes2.Miscs.Sticky; +import com.Pau.ImapNotes2.Sync.SyncUtils; + +import org.apache.commons.io.IOUtils; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.HashMap; + +import javax.mail.Message; +import javax.mail.Multipart; +import javax.mail.Part; +import javax.mail.internet.ContentType; + +import static com.Pau.ImapNotes2.NoteDetailActivity.Colors.BLUE; + public class NoteDetailActivity extends Activity { private static final int DELETE_BUTTON = 3; @@ -45,7 +42,7 @@ public class NoteDetailActivity extends Activity { private boolean usesticky; private Sticky sticky; private String stringres; - private String color; + private Colors color; private String position; private int realColor = R.id.yellow; private Boolean isClicked = false; @@ -105,10 +102,11 @@ public void onClick(View v) { this.isClicked = true; } + // TODO: Find out what this is for. private void ResetColors() { - ((EditText) findViewById(R.id.bodyView)).setBackgroundColor(Color.TRANSPARENT); + findViewById(R.id.bodyView).setBackgroundColor(Color.TRANSPARENT); ((EditText) findViewById(R.id.bodyView)).setTextColor(Color.BLACK); - Colors currentColor = Colors.valueOf(color); + Colors currentColor = color; switch (currentColor) { case BLUE: (findViewById(R.id.scrollView)).setBackgroundColor(0xFFA6CAFD); @@ -168,27 +166,27 @@ public boolean onOptionsItemSelected(MenuItem item) { return true; case R.id.blue: item.setChecked(true); - this.color = "BLUE"; + this.color = BLUE; (findViewById(R.id.scrollView)).setBackgroundColor(0xFFA6CAFD); return true; case R.id.white: item.setChecked(true); - this.color = "WHITE"; + this.color = Colors.WHITE; (findViewById(R.id.scrollView)).setBackgroundColor(0xFFFFFFFF); return true; case R.id.yellow: item.setChecked(true); - this.color = "YELLOW"; + this.color = Colors.YELLOW; (findViewById(R.id.scrollView)).setBackgroundColor(0xFFFFFFCC); return true; case R.id.pink: item.setChecked(true); - this.color = "PINK"; + this.color = Colors.PINK; (findViewById(R.id.scrollView)).setBackgroundColor(0xFFFFCCCC); return true; case R.id.green: item.setChecked(true); - this.color = "GREEN"; + this.color = Colors.GREEN; (findViewById(R.id.scrollView)).setBackgroundColor(0xFFCCFFCC); return true; default: @@ -203,7 +201,7 @@ private void Save() { intent.putExtra("EDIT_ITEM_TXT", Html.toHtml(((EditText) findViewById(R.id.bodyView)).getText())); if (!usesticky) { - this.color = "NONE"; + this.color = Colors.NONE; } intent.putExtra("EDIT_ITEM_COLOR", this.color); setResult(NoteDetailActivity.EDIT_BUTTON, intent); @@ -294,14 +292,14 @@ private Sticky ReadHtmlnote(String stringres) { stringres = stringres.replaceAll("

", "
"); stringres = stringres.replaceAll("

", ""); - return new Sticky(stringres, "", "NONE"); + return new Sticky(stringres, "", Colors.NONE); } private Sticky ReadPlainnote(String stringres) { // Log.d(TAG,"From server (plain):"+stringres); stringres = stringres.replaceAll("\n", "
"); - return new Sticky(stringres, "", "NONE"); + return new Sticky(stringres, "", Colors.NONE); } private void WriteMailToFile(String suid, Message message) { diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java index 1218b4db..9572cd7b 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java @@ -33,6 +33,7 @@ import com.Pau.ImapNotes2.Miscs.Imaper; import com.Pau.ImapNotes2.Miscs.OneNote; import com.Pau.ImapNotes2.Miscs.Sticky; +import com.Pau.ImapNotes2.NoteDetailActivity; import com.sun.mail.util.MailSSLSocketFactory; import com.sun.mail.imap.IMAPStore; @@ -46,6 +47,8 @@ import static com.Pau.ImapNotes2.Miscs.Imaper.ResultCodeException; import static com.Pau.ImapNotes2.Miscs.Imaper.ResultCodeSuccess; +import static com.Pau.ImapNotes2.NoteDetailActivity.*; +import static com.Pau.ImapNotes2.NoteDetailActivity.Colors.NONE; public class SyncUtils { @@ -212,27 +215,33 @@ public static void GetNotes(Account account, Folder notesFolder, Context ctx, No } } + private static final Pattern patternColor = Pattern.compile("^COLOR:(.*?)$", Pattern.MULTILINE); + private static final Pattern patternPosition = Pattern.compile("^POSITION:(.*?)$", Pattern.MULTILINE); + private static final Pattern patternText = Pattern.compile("TEXT:(.*?)(END:|POSITION:)", Pattern.DOTALL); + + public static Sticky ReadStickynote(String stringres) { - String color = new String(""); + Colors color = NONE; String position = new String(""); String text = new String(""); - Pattern p = null; + //Pattern p = null; Matcher m = null; - p = Pattern.compile("^COLOR:(.*?)$", Pattern.MULTILINE); - m = p.matcher(stringres); + m = patternColor.matcher(stringres); if (m.find()) { - color = m.group(1); + String colorName = m.group(1); + Log.d(TAG, " Color: " + colorName + " " + (colorName == null)); + color = ((colorName == null) || colorName.equals("null")) ? + Colors.NONE : + Colors.valueOf(m.group(1)); } - p = Pattern.compile("^POSITION:(.*?)$", Pattern.MULTILINE); - m = p.matcher(stringres); + m = patternPosition.matcher(stringres); if (m.find()) { position = m.group(1); } - p = Pattern.compile("TEXT:(.*?)(END:|POSITION:)", Pattern.DOTALL); - m = p.matcher(stringres); + m = patternText.matcher(stringres); if (m.find()) { text = m.group(1); // Kerio Connect puts CR+LF+space every 78 characters from line 2 From f8816bb04c77a45abf93a3b6876d8af7367bef38 Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Mon, 7 Nov 2016 19:20:05 +0100 Subject: [PATCH 012/103] Made notesFolder local instead of argument in DeleteNote. --- .../com/Pau/ImapNotes2/Sync/SyncAdapter.java | 3 +- .../com/Pau/ImapNotes2/Sync/SyncUtils.java | 98 +++++++++---------- 2 files changed, 50 insertions(+), 51 deletions(-) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java index 09e91072..1b8db084 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java @@ -22,7 +22,6 @@ import com.Pau.ImapNotes2.Data.ConfigurationFieldNames; import com.Pau.ImapNotes2.Data.NotesDb; import com.Pau.ImapNotes2.Miscs.ImapNotes2Result; -import com.Pau.ImapNotes2.Sync.SyncUtils; import com.sun.mail.imap.AppendUID; import static com.Pau.ImapNotes2.Miscs.Imaper.ResultCodeSuccess; @@ -247,7 +246,7 @@ private boolean handleDeletedNotes() { listOfDeleted = dirDeleted.list(); for (String fileDeleted : listOfDeleted) { try { - SyncUtils.DeleteNote(this.res.notesFolder, Integer.parseInt(fileDeleted)); + SyncUtils.DeleteNote(Integer.parseInt(fileDeleted)); } catch (Exception e) { e.printStackTrace(); } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java index 9572cd7b..41d9421d 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java @@ -1,5 +1,22 @@ package com.Pau.ImapNotes2.Sync; +import android.accounts.Account; +import android.content.Context; +import android.content.SharedPreferences; +import android.util.Log; + +import com.Pau.ImapNotes2.Data.NotesDb; +import com.Pau.ImapNotes2.Miscs.ImapNotes2Result; +import com.Pau.ImapNotes2.Miscs.Imaper; +import com.Pau.ImapNotes2.Miscs.OneNote; +import com.Pau.ImapNotes2.Miscs.Sticky; +import com.sun.mail.imap.AppendUID; +import com.sun.mail.imap.IMAPFolder; +import com.sun.mail.imap.IMAPStore; +import com.sun.mail.util.MailSSLSocketFactory; + +import org.apache.commons.io.FileUtils; + import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; @@ -8,10 +25,8 @@ import java.io.InputStream; import java.io.OutputStream; import java.security.GeneralSecurityException; -import java.security.InvalidParameterException; import java.text.SimpleDateFormat; import java.util.ArrayList; -import java.util.Arrays; import java.util.Date; import java.util.Properties; import java.util.regex.Matcher; @@ -19,35 +34,16 @@ import javax.mail.Flags; import javax.mail.Folder; +import javax.mail.Message; import javax.mail.MessagingException; +import javax.mail.Session; import javax.mail.Store; import javax.mail.UIDFolder; import javax.mail.internet.MimeMessage; -import org.apache.commons.io.FileUtils; - -import javax.mail.Message; -import javax.mail.Session; -import com.Pau.ImapNotes2.Data.NotesDb; -import com.Pau.ImapNotes2.Miscs.ImapNotes2Result; -import com.Pau.ImapNotes2.Miscs.Imaper; -import com.Pau.ImapNotes2.Miscs.OneNote; -import com.Pau.ImapNotes2.Miscs.Sticky; -import com.Pau.ImapNotes2.NoteDetailActivity; -import com.sun.mail.util.MailSSLSocketFactory; - -import com.sun.mail.imap.IMAPStore; -import com.sun.mail.imap.AppendUID; -import com.sun.mail.imap.IMAPFolder; - -import android.accounts.Account; -import android.content.Context; -import android.content.SharedPreferences; -import android.util.Log; - import static com.Pau.ImapNotes2.Miscs.Imaper.ResultCodeException; import static com.Pau.ImapNotes2.Miscs.Imaper.ResultCodeSuccess; -import static com.Pau.ImapNotes2.NoteDetailActivity.*; +import static com.Pau.ImapNotes2.NoteDetailActivity.Colors; import static com.Pau.ImapNotes2.NoteDetailActivity.Colors.NONE; public class SyncUtils { @@ -60,7 +56,7 @@ public class SyncUtils { static String sfolder = "Notes"; static private String folderoverride; static Folder notesFolder = null; - static ImapNotes2Result res; + static ImapNotes2Result res = new ImapNotes2Result(); static Long UIDValidity; private final static int NEW = 1; private final static int DELETED = 2; @@ -77,8 +73,6 @@ public static ImapNotes2Result ConnectToRemote(String username, if (IsConnected()) store.close(); - res = new ImapNotes2Result(); - folderoverride = (override == null) ? "" : override; proto = security.proto; @@ -190,9 +184,15 @@ public static ImapNotes2Result ConnectToRemote(String username, } - public static void GetNotes(Account account, Folder notesFolder, Context ctx, NotesDb storedNotes) throws MessagingException, IOException { - Long UIDM; - Message notesMessage; + /* Copy all notes from the IMAP server to the local directory using the UID as the file name. + + */ + public static void GetNotes(Account account, + Folder notesFolder, + Context ctx, + NotesDb storedNotes) throws MessagingException, IOException { + //Long UIDM; + //Message notesMessage; File directory = new File(ctx.getFilesDir() + "/" + account.name); if (notesFolder.isOpen()) { if ((notesFolder.getMode() & Folder.READ_ONLY) != 0) @@ -205,10 +205,10 @@ public static void GetNotes(Account account, Folder notesFolder, Context ctx, No Message[] notesMessages = notesFolder.getMessages(); //Log.d(TAG,"number of messages in folder="+(notesMessages.length)); for (int index = notesMessages.length - 1; index >= 0; index--) { - notesMessage = notesMessages[index]; + Message notesMessage = notesMessages[index]; // write every message in files/{accountname} directory // filename is the original message uid - UIDM = ((IMAPFolder) notesFolder).getUID(notesMessage); + Long UIDM = ((IMAPFolder) notesFolder).getUID(notesMessage); String suid = UIDM.toString(); File outfile = new File(directory, suid); GetOneNote(outfile, notesMessage, storedNotes, account.name, suid, true); @@ -219,31 +219,30 @@ public static void GetNotes(Account account, Folder notesFolder, Context ctx, No private static final Pattern patternPosition = Pattern.compile("^POSITION:(.*?)$", Pattern.MULTILINE); private static final Pattern patternText = Pattern.compile("TEXT:(.*?)(END:|POSITION:)", Pattern.DOTALL); - public static Sticky ReadStickynote(String stringres) { Colors color = NONE; - String position = new String(""); - String text = new String(""); + String position = ""; + String text = ""; //Pattern p = null; - Matcher m = null; - m = patternColor.matcher(stringres); - if (m.find()) { - String colorName = m.group(1); + + Matcher matcherColor = patternColor.matcher(stringres); + if (matcherColor.find()) { + String colorName = matcherColor.group(1); Log.d(TAG, " Color: " + colorName + " " + (colorName == null)); color = ((colorName == null) || colorName.equals("null")) ? Colors.NONE : - Colors.valueOf(m.group(1)); + Colors.valueOf(colorName); } - m = patternPosition.matcher(stringres); - if (m.find()) { - position = m.group(1); + Matcher matcherPosition = patternPosition.matcher(stringres); + if (matcherPosition.find()) { + position = matcherPosition.group(1); } - m = patternText.matcher(stringres); - if (m.find()) { - text = m.group(1); + Matcher matcherText = patternText.matcher(stringres); + if (matcherText.find()) { + text = matcherText.group(1); // Kerio Connect puts CR+LF+space every 78 characters from line 2 // first line seem to be smaller. We remove these characters text = text.replaceAll("\r\n ", ""); @@ -257,11 +256,12 @@ public static boolean IsConnected() { return store != null && store.isConnected(); } - public static void DeleteNote(Folder notesFolder, int numMessage) throws MessagingException, IOException { - notesFolder = store.getFolder(sfolder); + public static void DeleteNote(int numMessage) throws MessagingException, IOException { + Folder notesFolder = store.getFolder(sfolder); if (notesFolder.isOpen()) { - if ((notesFolder.getMode() & Folder.READ_WRITE) != 0) + if ((notesFolder.getMode() & Folder.READ_WRITE) != 0) { notesFolder.open(Folder.READ_WRITE); + } } else { notesFolder.open(Folder.READ_WRITE); } From fb7d5fcad3ef0e189c9dd75a2bf3266fa5a04609 Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Mon, 7 Nov 2016 20:48:18 +0100 Subject: [PATCH 013/103] Move arguments from execute to constructor of UpdateThread to enforce type safety. --- ImapNote2/src/main/AndroidManifest.xml | 2 +- .../AccountConfigurationActivity.java | 2 +- .../ImapNotes2/Data/ConfigurationFile.java | 8 +- .../{ImapNotes2.java => ImapNotes2k.java} | 14 +- .../java/com/Pau/ImapNotes2/Listactivity.java | 25 ++-- .../java/com/Pau/ImapNotes2/Miscs/Imaper.java | 18 +-- .../Pau/ImapNotes2/Miscs/UpdateThread.java | 129 +++++++++++------- .../Pau/ImapNotes2/NoteDetailActivity.java | 4 +- ImapNote2/src/main/res/values/strings.xml | 2 +- 9 files changed, 119 insertions(+), 85 deletions(-) rename ImapNote2/src/main/java/com/Pau/ImapNotes2/{ImapNotes2.java => ImapNotes2k.java} (83%) diff --git a/ImapNote2/src/main/AndroidManifest.xml b/ImapNote2/src/main/AndroidManifest.xml index de1ed8d9..4b47dad2 100644 --- a/ImapNote2/src/main/AndroidManifest.xml +++ b/ImapNote2/src/main/AndroidManifest.xml @@ -16,7 +16,7 @@ (); - ((ImapNotes2) this.getApplicationContext()).SetNotesList(this.noteList); + ((ImapNotes2k) this.getApplicationContext()).SetNotesList(this.noteList); this.listToView = new NotesListAdapter( getApplicationContext(), this.noteList, @@ -140,7 +142,7 @@ public void onCreate(Bundle savedInstanceState) { listview.setTextFilterEnabled(true); this.imapFolder = new Imaper(); - ((ImapNotes2) this.getApplicationContext()).SetImaper(this.imapFolder); + ((ImapNotes2k) this.getApplicationContext()).SetImaper(this.imapFolder); if (Listactivity.storedNotes == null) storedNotes = new NotesDb(getApplicationContext()); @@ -226,10 +228,15 @@ public void RefreshList() { status.setText("Welcome"); } - public void UpdateList(String suid, String noteBody, String color, String action) { + public void UpdateList(String suid, + String noteBody, + Colors color, + String action) { ProgressDialog loadingDialog = ProgressDialog.show(this, "imapnote2", "Updating notes list... ", true); - new UpdateThread().execute(this.imapFolder, Listactivity.imapNotes2Account, this.noteList, this.listToView, loadingDialog, suid, noteBody, color, this.getApplicationContext(), action, storedNotes); + new UpdateThread(this.imapFolder, Listactivity.imapNotes2Account, this.noteList, + this.listToView, loadingDialog, suid, noteBody, + color, this.getApplicationContext(), action, storedNotes).execute(); } @@ -319,7 +326,7 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Listactivity.EDIT_BUTTON) { String txt = data.getStringExtra("EDIT_ITEM_TXT"); String suid = data.getStringExtra("EDIT_ITEM_NUM_IMAP"); - String color = data.getStringExtra("EDIT_ITEM_COLOR"); + Colors color = (Colors) data.getSerializableExtra("EDIT_ITEM_COLOR"); //Log.d(TAG,"Received request to delete message:"+suid); //Log.d(TAG,"Received request to replace message with:"+txt); this.UpdateList(suid, txt, color, "update"); @@ -329,7 +336,7 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Listactivity.SAVE_BUTTON) { String res = data.getStringExtra("SAVE_ITEM"); //Log.d(TAG,"Received request to save message:"+res); - String color = data.getStringExtra("SAVE_ITEM_COLOR"); + Colors color = (Colors) data.getSerializableExtra("SAVE_ITEM_COLOR"); this.UpdateList(null, res, color, "insert"); } } @@ -434,7 +441,7 @@ public void onAccountsUpdated(Account[] accounts) { iter.remove(); // Why try here? try { - String stringDir = ImapNotes2.ConfigurationDirPath() + "/" + s; + String stringDir = ImapNotes2k.ConfigurationDirPath() + "/" + s; FileUtils.deleteDirectory(new File(stringDir)); } catch (IOException e) { // TODO Auto-generated catch block @@ -446,7 +453,7 @@ public void onAccountsUpdated(Account[] accounts) { for (String accountName : newList) { if (!(Listactivity.currentList.contains(accountName))) { Listactivity.currentList.add(accountName); - SyncUtils.CreateDirs(accountName, ImapNotes2.getAppContext()); + SyncUtils.CreateDirs(accountName, ImapNotes2k.getAppContext()); equalLists = false; } @@ -454,7 +461,7 @@ public void onAccountsUpdated(Account[] accounts) { if (equalLists) return; updateAccountSpinner(); } else { - File filesDir = ImapNotes2.ConfigurationDir(); + File filesDir = ImapNotes2k.ConfigurationDir(); try { FileUtils.cleanDirectory(filesDir); } catch (IOException e) { diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Imaper.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Imaper.java index 1eb1ec83..e05abe95 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Imaper.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Imaper.java @@ -1,11 +1,6 @@ package com.Pau.ImapNotes2.Miscs; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; import java.security.GeneralSecurityException; -import java.util.ArrayList; import java.util.Properties; import android.content.Context; @@ -13,23 +8,16 @@ import android.util.Log; import javax.mail.Folder; -import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Store; -import javax.mail.Flags; import com.Pau.ImapNotes2.Sync.Security; -import com.sun.mail.imap.IMAPFolder; import com.sun.mail.imap.IMAPStore; import com.sun.mail.util.MailSSLSocketFactory; -import java.util.regex.*; - -import com.Pau.ImapNotes2.Miscs.Sticky; -import com.Pau.ImapNotes2.ImapNotes2; +import com.Pau.ImapNotes2.ImapNotes2k; import com.Pau.ImapNotes2.Listactivity; -import com.Pau.ImapNotes2.Miscs.ImapNotes2Result; public class Imaper { @@ -177,7 +165,7 @@ public boolean IsConnected() { // Put values in shared preferences: public void SetPrefs() { - SharedPreferences preferences = ImapNotes2.getAppContext().getSharedPreferences(Listactivity.imapNotes2Account.GetAccountname(), Context.MODE_PRIVATE); + SharedPreferences preferences = ImapNotes2k.getAppContext().getSharedPreferences(Listactivity.imapNotes2Account.GetAccountname(), Context.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putString("Name", "valid_data"); editor.putLong("UIDValidity", UIDValidity); @@ -186,7 +174,7 @@ public void SetPrefs() { // Retrieve values from shared preferences: public void GetPrefs() { - SharedPreferences preferences = (ImapNotes2.getAppContext()).getSharedPreferences(Listactivity.imapNotes2Account.GetAccountname(), Context.MODE_PRIVATE); + SharedPreferences preferences = (ImapNotes2k.getAppContext()).getSharedPreferences(Listactivity.imapNotes2Account.GetAccountname(), Context.MODE_PRIVATE); String name = preferences.getString("Name", ""); if (!name.equalsIgnoreCase("")) { UIDValidity = preferences.getLong("UIDValidity", -1); diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java index 61491dea..3f19904d 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java @@ -8,6 +8,7 @@ import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; +import java.util.Objects; import java.util.Properties; import java.util.UUID; @@ -17,8 +18,9 @@ import javax.mail.internet.MimeMessage; import javax.mail.internet.MailDateFormat; -import com.Pau.ImapNotes2.ImapNotes2; +import com.Pau.ImapNotes2.ImapNotes2k; import com.Pau.ImapNotes2.Listactivity; +import com.Pau.ImapNotes2.NoteDetailActivity; import com.Pau.ImapNotes2.NotesListAdapter; import com.Pau.ImapNotes2.Data.ImapNotes2Account; import com.Pau.ImapNotes2.Data.NotesDb; @@ -27,27 +29,59 @@ import android.content.Context; import android.os.AsyncTask; import android.text.Html; -import android.util.Log; -import android.widget.SimpleAdapter; +import android.widget.Adapter; + +import static com.Pau.ImapNotes2.NoteDetailActivity.*; // TODO: move arguments from execute to constructor. public class UpdateThread extends AsyncTask { - NotesListAdapter adapter; - ArrayList notesList; - String suid; - String noteBody; - String color; - Imaper imapFolder; + private final ImapNotes2Account imapNotes2Account; + private final ProgressDialog progressDialog; + private final NotesListAdapter adapter; + private final ArrayList notesList; + private String suid; + private final String noteBody; + private final Colors color; + private final Imaper imapFolder; boolean bool_to_return; OneNote currentNote = null; private NotesDb storedNotes; - private Context ctx; - ProgressDialog pDialog; - String action; + private final Context ctx; + private final String action; private static final String TAG = "UpdateThread"; + /* + Assign all fields in the constructor because we never reuse this object. This makes the code + typesafe. Make them final to preven accidental reuse. + */ + public UpdateThread(Imaper imapFolder, + ImapNotes2Account imapNotes2Account, + ArrayList noteList, + NotesListAdapter listToView, + ProgressDialog loadingDialog, + String suid, + String noteBody, + Colors color, + Context applicationContext, + String action, + NotesDb storedNotes) { + + this.imapFolder = imapFolder; + this.imapNotes2Account = imapNotes2Account; + this.notesList = noteList; + this.adapter = listToView; + this.progressDialog = loadingDialog; + this.suid = suid; + this.noteBody = noteBody; + this.color = color; + this.ctx = applicationContext; + this.action = action; + this.storedNotes = storedNotes; + + } @Override protected Boolean doInBackground(Object... stuffs) { +/* this.adapter = ((NotesListAdapter) stuffs[3]); this.notesList = ((ArrayList) stuffs[2]); this.suid = ((String) stuffs[5]); @@ -57,84 +91,85 @@ protected Boolean doInBackground(Object... stuffs) { this.ctx = (Context) stuffs[8]; this.action = (String) stuffs[9]; this.storedNotes = (NotesDb) stuffs[10]; +*/ try { // Do we have a note to remove? - if (this.action.equals("delete") || this.action.equals("update")) { + if (action.equals("delete") || action.equals("update")) { //Log.d(TAG,"Received request to delete message #"+suid); // Here we delete the note from the local notes list //Log.d(TAG,"Delete note in Listview"); - this.notesList.remove(getIndexByNumber(this.suid)); - MoveMailToDeleted(this.suid); - this.storedNotes.OpenDb(); - this.storedNotes.DeleteANote(this.suid, Listactivity.imapNotes2Account.GetAccountname()); - this.storedNotes.CloseDb(); - this.bool_to_return = true; + notesList.remove(getIndexByNumber(suid)); + MoveMailToDeleted(suid); + storedNotes.OpenDb(); + storedNotes.DeleteANote(suid, Listactivity.imapNotes2Account.GetAccountname()); + storedNotes.CloseDb(); + bool_to_return = true; } // Do we have a note to add? - if (this.action.equals("insert") || this.action.equals("update")) { + if (action.equals("insert") || action.equals("update")) { //Log.d(TAG,"Sticky ? "+((ImapNotes2Account)stuffs[1]).GetUsesticky()); -//Log.d(TAG,"Color:"+this.color); - //Log.d(TAG,"Received request to add new message"+this.noteBody+"==="); - String noteTxt = Html.fromHtml(this.noteBody).toString(); +//Log.d(TAG,"Color:"+color); + //Log.d(TAG,"Received request to add new message"+noteBody+"==="); + String noteTxt = Html.fromHtml(noteBody).toString(); String[] tok = noteTxt.split("\n", 2); String title = tok[0]; String position = "0 0 0 0"; - String body = (((ImapNotes2Account) stuffs[1]).GetUsesticky()) ? + String body = (imapNotes2Account.GetUsesticky()) ? noteTxt.replaceAll("\n", "\\\\n") : - "" + this.noteBody + ""; + "" + noteBody + ""; String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); String stringDate = sdf.format(date); - this.currentNote = new OneNote(title, stringDate, ""); + currentNote = new OneNote(title, stringDate, ""); // Add note to database - if (this.storedNotes == null) this.storedNotes = new NotesDb(this.ctx); - this.storedNotes.OpenDb(); - this.suid = this.storedNotes.GetTempNumber(Listactivity.imapNotes2Account.GetAccountname()); - this.currentNote.SetUid(this.suid); + if (storedNotes == null) storedNotes = new NotesDb(ctx); + storedNotes.OpenDb(); + suid = storedNotes.GetTempNumber(Listactivity.imapNotes2Account.GetAccountname()); + currentNote.SetUid(suid); // Here we ask to add the new note to the "new" folder // Must be done AFTER uid has been set in currenteNote WriteMailToNew(currentNote, - ((ImapNotes2Account) stuffs[1]).GetUsesticky(), body); - this.storedNotes.InsertANoteInDb(this.currentNote, Listactivity.imapNotes2Account.GetAccountname()); - this.storedNotes.CloseDb(); + imapNotes2Account.GetUsesticky(), body); + storedNotes.InsertANoteInDb(currentNote, Listactivity.imapNotes2Account.GetAccountname()); + storedNotes.CloseDb(); // Add note to noteList but chage date format before - DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(this.ctx); + DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(ctx); String sdate = DateFormat.getDateTimeInstance().format(date); - this.currentNote.SetDate(sdate); - this.notesList.add(0, this.currentNote); - this.bool_to_return = true; + currentNote.SetDate(sdate); + notesList.add(0, currentNote); + bool_to_return = true; } } catch (Exception e) { e.printStackTrace(); - this.bool_to_return = false; + bool_to_return = false; } finally { - ((ProgressDialog) stuffs[4]).dismiss(); + progressDialog.dismiss(); } - return this.bool_to_return; + return bool_to_return; } protected void onPostExecute(Boolean result) { if (result) { - if (this.bool_to_return) /* note added or removed */ - this.adapter.notifyDataSetChanged(); + if (bool_to_return) /* note added or removed */ + adapter.notifyDataSetChanged(); } } public int getIndexByNumber(String pNumber) { - for (OneNote _item : this.notesList) { + for (OneNote _item : notesList) { if (_item.GetUid().equals(pNumber)) - return this.notesList.indexOf(_item); + return notesList.indexOf(_item); } return -1; } private void MoveMailToDeleted(String suid) { - String directory = (ImapNotes2.getAppContext()).getFilesDir() + "/" + + String directory = (ImapNotes2k.getAppContext()).getFilesDir() + "/" + Listactivity.imapNotes2Account.GetAccountname(); String positiveUid = suid.substring(1); File from = new File(directory, suid); @@ -158,7 +193,7 @@ public void WriteMailToNew(OneNote note, Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); if (usesticky) { - body = "BEGIN:STICKYNOTE\nCOLOR:" + this.color + "\nTEXT:" + noteBody + + body = "BEGIN:STICKYNOTE\nCOLOR:" + color.name() + "\nTEXT:" + noteBody + "\nPOSITION:0 0 0 0\nEND:STICKYNOTE"; message.setText(body); message.setHeader("Content-Transfer-Encoding", "8bit"); @@ -184,7 +219,7 @@ public void WriteMailToNew(OneNote note, message.addHeader("Date", headerDate); // Get temporary UID String uid = Integer.toString(Math.abs(Integer.parseInt(note.GetUid()))); - File directory = new File((ImapNotes2.getAppContext()).getFilesDir() + "/" + + File directory = new File((ImapNotes2k.getAppContext()).getFilesDir() + "/" + Listactivity.imapNotes2Account.GetAccountname() + "/new"); //message.setFrom(new InternetAddress("ImapNotes2", Listactivity.imapNotes2Account.GetAccountname())); message.setFrom(Listactivity.imapNotes2Account.GetAccountname()); diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java index a5f113d4..d50adccf 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java @@ -64,7 +64,7 @@ public void onCreate(Bundle savedInstanceState) { this.hm = (HashMap) extras.get("selectedNote"); this.usesticky = (boolean) extras.get("useSticky"); suid = this.hm.get("uid").toString(); - String rootDir = (ImapNotes2.getAppContext()).getFilesDir() + "/" + + String rootDir = (ImapNotes2k.getAppContext()).getFilesDir() + "/" + Listactivity.imapNotes2Account.GetAccountname(); message = SyncUtils.ReadMailFromFile(suid, ROOT_AND_NEW, true, rootDir); sticky = GetInfoFromMessage(message); @@ -303,7 +303,7 @@ private Sticky ReadPlainnote(String stringres) { } private void WriteMailToFile(String suid, Message message) { - String directory = (ImapNotes2.getAppContext()).getFilesDir() + "/" + + String directory = (ImapNotes2k.getAppContext()).getFilesDir() + "/" + Listactivity.imapNotes2Account.GetAccountname(); try { File outfile = new File(directory, suid); diff --git a/ImapNote2/src/main/res/values/strings.xml b/ImapNote2/src/main/res/values/strings.xml index 2f7a6fbb..1910f6ff 100644 --- a/ImapNote2/src/main/res/values/strings.xml +++ b/ImapNote2/src/main/res/values/strings.xml @@ -1,6 +1,6 @@ - ImapNotes2 + ImapNotes2k Account New Refresh From fc35bfad2225d710edc7d3f568d8a9096127f93b Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Tue, 8 Nov 2016 10:56:38 +0100 Subject: [PATCH 014/103] Ran Field can be local analysis and fixed almost all. --- .../java/com/Pau/ImapNotes2/Listactivity.java | 6 ++--- .../java/com/Pau/ImapNotes2/Miscs/Imaper.java | 7 ++---- .../Pau/ImapNotes2/Miscs/UpdateThread.java | 8 +++---- .../Pau/ImapNotes2/NoteDetailActivity.java | 20 ++++++---------- .../com/Pau/ImapNotes2/Sync/SyncAdapter.java | 23 ++++++++----------- .../com/Pau/ImapNotes2/Sync/SyncUtils.java | 8 +++---- notes.org | 13 +++++++++++ 7 files changed, 39 insertions(+), 46 deletions(-) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java index d057fcd4..79c06c66 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java @@ -83,8 +83,6 @@ public class Listactivity extends Activity implements OnItemSelectedListener, Fi private static List currentList; private TextView status = null; private static String OldStatus; - private Button editAccountButton = null; - private ListView listview; public static final String AUTHORITY = "com.Pau.ImapNotes2.provider"; private static final String TAG = "IN_Listactivity"; @@ -136,7 +134,7 @@ public void onCreate(Bundle savedInstanceState) { R.layout.note_element, new String[]{"title", "date"}, new int[]{R.id.noteTitle, R.id.noteInformation}); - listview = (ListView) findViewById(R.id.notesList); + ListView listview = (ListView) findViewById(R.id.notesList); listview.setAdapter(this.listToView); listview.setTextFilterEnabled(true); @@ -157,7 +155,7 @@ public void onItemClick(AdapterView parent, View widget, int selectedNote, lo } }); - editAccountButton = (Button) findViewById(R.id.editAccountButton); + Button editAccountButton = (Button) findViewById(R.id.editAccountButton); editAccountButton.setOnClickListener(clickListenerEditAccount); } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Imaper.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Imaper.java index e05abe95..cf893ea7 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Imaper.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Imaper.java @@ -22,11 +22,8 @@ public class Imaper { private Store store; - private Session session; private static final String TAG = "IN_Imaper"; private static String sfolder = "Notes"; - //private Folder notesFolder = null; - private ImapNotes2Result res; private Long UIDValidity; public static final String PREFS_NAME = "PrefsFile"; @@ -45,7 +42,7 @@ public ImapNotes2Result ConnectToProvider(String username, store.close(); } - res = new ImapNotes2Result(); + ImapNotes2Result res = new ImapNotes2Result(); String proto = security.proto; boolean acceptcrt = security.acceptcrt; /* int security_i = Integer.parseInt(security); @@ -127,7 +124,7 @@ public ImapNotes2Result ConnectToProvider(String username, props.put("sun.net.spi.nameservice.nameservers", "192.168.0.99"); */ } - session = Session.getInstance(props, null); + Session session = Session.getInstance(props, null); //session.setDebug(true); store = session.getStore(proto); try { diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java index 3f19904d..b90d12a6 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java @@ -42,9 +42,7 @@ public class UpdateThread extends AsyncTask { private String suid; private final String noteBody; private final Colors color; - private final Imaper imapFolder; - boolean bool_to_return; - OneNote currentNote = null; + private boolean bool_to_return; private NotesDb storedNotes; private final Context ctx; private final String action; @@ -66,7 +64,7 @@ public UpdateThread(Imaper imapFolder, String action, NotesDb storedNotes) { - this.imapFolder = imapFolder; + Imaper imapFolder1 = imapFolder; this.imapNotes2Account = imapNotes2Account; this.notesList = noteList; this.adapter = listToView; @@ -124,7 +122,7 @@ protected Boolean doInBackground(Object... stuffs) { Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); String stringDate = sdf.format(date); - currentNote = new OneNote(title, stringDate, ""); + OneNote currentNote = new OneNote(title, stringDate, ""); // Add note to database if (storedNotes == null) storedNotes = new NotesDb(ctx); storedNotes.OpenDb(); diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java index d50adccf..fdd27c65 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java @@ -38,15 +38,9 @@ public class NoteDetailActivity extends Activity { private static final int DELETE_BUTTON = 3; private static final int EDIT_BUTTON = 6; - private HashMap hm; private boolean usesticky; - private Sticky sticky; - private String stringres; private Colors color; - private String position; private int realColor = R.id.yellow; - private Boolean isClicked = false; - private Message message; private String suid; // uid as string private final static int ROOT_AND_NEW = 3; private static final String TAG = "IN_NoteDetailActivity"; @@ -61,15 +55,15 @@ public void onCreate(Bundle savedInstanceState) { ); Bundle extras = getIntent().getExtras(); - this.hm = (HashMap) extras.get("selectedNote"); + HashMap hm = (HashMap) extras.get("selectedNote"); this.usesticky = (boolean) extras.get("useSticky"); - suid = this.hm.get("uid").toString(); + suid = hm.get("uid").toString(); String rootDir = (ImapNotes2k.getAppContext()).getFilesDir() + "/" + Listactivity.imapNotes2Account.GetAccountname(); - message = SyncUtils.ReadMailFromFile(suid, ROOT_AND_NEW, true, rootDir); - sticky = GetInfoFromMessage(message); - stringres = sticky.GetText(); - position = sticky.GetPosition(); + Message message = SyncUtils.ReadMailFromFile(suid, ROOT_AND_NEW, true, rootDir); + Sticky sticky = GetInfoFromMessage(message); + String stringres = sticky.GetText(); + String position = sticky.GetPosition(); color = sticky.GetColor(); Spanned plainText = Html.fromHtml(stringres); EditText editText = ((EditText) findViewById(R.id.bodyView)); @@ -99,7 +93,7 @@ public void afterTextChanged(Editable s) { } public void onClick(View v) { - this.isClicked = true; + Boolean isClicked = true; } // TODO: Find out what this is for. diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java index 1b8db084..0ebff4d2 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java @@ -34,15 +34,10 @@ class SyncAdapter extends AbstractThreadedSyncAdapter { public static final String TAG = "SyncAdapter"; private static Context context; - private static Boolean isChanged; - private static Boolean isSynced; private NotesDb storedNotes; - private String[] listOfNew; - private String[] listOfDeleted; private static Account account; /// See RFC 3501: http://www.faqs.org/rfcs/rfc3501.html private Long UIDValidity = (long) -1; - private static ImapNotes2Result res; private final static int NEW = 1; private final static int DELETED = 2; @@ -71,8 +66,8 @@ public void onPerformSync(Account account, Bundle extras, String authority, SyncResult syncResult) { //Log.d(TAG, "Beginning network synchronization of account: "+account.name); this.account = account; - isChanged = false; - isSynced = false; + Boolean isChanged = false; + Boolean isSynced = false; String syncinterval; SyncUtils.CreateDirs(account.name, this.context); @@ -84,8 +79,8 @@ public void onPerformSync(Account account, Bundle extras, String authority, syncinterval = am.getUserData(account, "syncinterval"); // Connect to remote and get UIDValidity - this.res = ConnectToRemote(); - if (this.res.returnCode != ResultCodeSuccess) { + ImapNotes2Result res = ConnectToRemote(); + if (res.returnCode != ResultCodeSuccess) { storedNotes.CloseDb(); // Notify Listactivity that it's finished, but it can't @@ -101,7 +96,7 @@ public void onPerformSync(Account account, Bundle extras, String authority, return; } // Compare UIDValidity to old saved one - if (!(this.res.UIDValidity.equals + if (!(res.UIDValidity.equals (SyncUtils.GetUIDValidity(this.account, this.context)))) { // Replace local data by remote try { @@ -112,7 +107,7 @@ public void onPerformSync(Account account, Bundle extras, String authority, SyncUtils.CreateDirs(account.name, this.context); // Get all notes from remote and replace local SyncUtils.GetNotes(account, - this.res.notesFolder, + res.notesFolder, this.context, storedNotes); storedNotes.CloseDb(); } catch (MessagingException e) { @@ -122,7 +117,7 @@ public void onPerformSync(Account account, Bundle extras, String authority, // TODO Auto-generated catch block e.printStackTrace(); } - SyncUtils.SetUIDValidity(account, this.res.UIDValidity, this.context); + SyncUtils.SetUIDValidity(account, res.UIDValidity, this.context); // Notify Listactivity that it's finished, and that it can refresh display Intent i = new Intent(SyncService.SYNC_FINISHED); i.putExtra("ACCOUNTNAME", account.name); @@ -202,7 +197,7 @@ private boolean handleNewNotes() { String rootString = context.getFilesDir() + "/" + account.name; File rootDir = new File(rootString); File dirNew = new File(rootDir + "/new"); - listOfNew = dirNew.list(); + String[] listOfNew = dirNew.list(); for (String fileNew : listOfNew) { //Log.d(TAG,"New Note to process:"+fileNew); newNotesManaged = true; @@ -243,7 +238,7 @@ private boolean handleDeletedNotes() { String rootString = context.getFilesDir() + "/" + account.name; File rootDir = new File(rootString); File dirDeleted = new File(rootDir + "/deleted"); - listOfDeleted = dirDeleted.list(); + String[] listOfDeleted = dirDeleted.list(); for (String fileDeleted : listOfDeleted) { try { SyncUtils.DeleteNote(Integer.parseInt(fileDeleted)); diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java index 41d9421d..ef565d16 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java @@ -52,16 +52,13 @@ public class SyncUtils { static Session session; static final String TAG = "IN_SyncUtils"; static String proto; - private static boolean acceptcrt; static String sfolder = "Notes"; - static private String folderoverride; static Folder notesFolder = null; static ImapNotes2Result res = new ImapNotes2Result(); static Long UIDValidity; private final static int NEW = 1; private final static int DELETED = 2; private final static int ROOT_AND_NEW = 3; - private static Boolean useProxy = false; public static ImapNotes2Result ConnectToRemote(String username, String password, @@ -73,10 +70,10 @@ public static ImapNotes2Result ConnectToRemote(String username, if (IsConnected()) store.close(); - folderoverride = (override == null) ? "" : override; + String folderoverride = (override == null) ? "" : override; proto = security.proto; - acceptcrt = security.acceptcrt; + boolean acceptcrt = security.acceptcrt; /* int security_i = Integer.parseInt(security); switch (security_i) { @@ -145,6 +142,7 @@ public static ImapNotes2Result ConnectToRemote(String username, props.setProperty("mail.imap.connectiontimeout", "1000"); // TODO: use user defined proxy. + Boolean useProxy = false; if (useProxy) { props.put("mail.imap.socks.host", "10.0.2.2"); props.put("mail.imap.socks.port", "1080"); diff --git a/notes.org b/notes.org index 8566e932..8f95566a 100644 --- a/notes.org +++ b/notes.org @@ -75,3 +75,16 @@ Then can we do it automatically and then can we start the sync early? This is used to store metadata about the notes. The notes themselves are stored as files in a sub-directory named after the account to which they belong. + +* Code analysis + +Run Android lint to discover opportunities to get rid of warnings, +convert fields to local variables, etc. + +** Analyses done + +| Analysis | Notes | +|--------------------+----------------------------------------------------------------------| +| Field can be local | Some of these seem to be work in progress so have been left unfixed. | +| | | + From 60036d39796c9ec171376e8122d733d936d8d2ce Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Tue, 8 Nov 2016 13:38:55 +0100 Subject: [PATCH 015/103] ConstantConditions analyser. Some possible null references remain. Moved code inside try in some cases, use Log.d instead of exception.printStackTrace. Suppress MessagingException when closing connection because the connection is always closed after the call even if the execption is thrown. --- .../AccountConfigurationActivity.java | 1 + .../java/com/Pau/ImapNotes2/Miscs/Imaper.java | 3 +- .../com/Pau/ImapNotes2/NewNoteActivity.java | 1 + .../Pau/ImapNotes2/NoteDetailActivity.java | 2 + .../com/Pau/ImapNotes2/Sync/SyncAdapter.java | 47 ++++++------ .../com/Pau/ImapNotes2/Sync/SyncUtils.java | 74 +++++++------------ notes.org | 37 ++++++---- 7 files changed, 77 insertions(+), 88 deletions(-) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java index b55098f3..eeaa1fdb 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java @@ -103,6 +103,7 @@ public void onClick(View v) { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.account_selection); + //noinspection ConstantConditions getActionBar().setDisplayHomeAsUpEnabled(true); this.accountnameTextView = (TextView) (findViewById(R.id.accountnameEdit)); this.usernameTextView = (TextView) findViewById(R.id.usernameEdit); diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Imaper.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Imaper.java index cf893ea7..6182c2d5 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Imaper.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Imaper.java @@ -111,8 +111,9 @@ public ImapNotes2Result ConnectToProvider(String username, } props.setProperty("mail.imap.connectiontimeout", "1000"); - // TODO: implement proxy handling properly. Boolean useProxy = false; + //noinspection ConstantConditions + // TODO: implement proxy handling properly. if (useProxy) { props.put("mail.imap.socks.host", "10.0.2.2"); props.put("mail.imap.socks.port", "1080"); diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NewNoteActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NewNoteActivity.java index 3525d630..a0ac19ef 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NewNoteActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NewNoteActivity.java @@ -20,6 +20,7 @@ public class NewNoteActivity extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.new_note); + //noinspection ConstantConditions getActionBar().setDisplayHomeAsUpEnabled(true); this.ResetColors(); this.sticky = (boolean) getIntent().getExtras().get("usesSticky"); diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java index fdd27c65..f5fb180a 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java @@ -48,6 +48,7 @@ public class NoteDetailActivity extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.note_detail); + //noinspection ConstantConditions getActionBar().setDisplayHomeAsUpEnabled(true); // Don't display keyboard when on note detail, only if user touches the screen getWindow().setSoftInputMode( @@ -57,6 +58,7 @@ public void onCreate(Bundle savedInstanceState) { Bundle extras = getIntent().getExtras(); HashMap hm = (HashMap) extras.get("selectedNote"); this.usesticky = (boolean) extras.get("useSticky"); + assert hm != null; suid = hm.get("uid").toString(); String rootDir = (ImapNotes2k.getAppContext()).getFilesDir() + "/" + Listactivity.imapNotes2Account.GetAccountname(); diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java index 0ebff4d2..755f4494 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java @@ -89,8 +89,8 @@ public void onPerformSync(Account account, Bundle extras, String authority, i.putExtra("ACCOUNTNAME", account.name); isChanged = false; isSynced = false; - i.putExtra("CHANGED", isChanged); - i.putExtra("SYNCED", isSynced); + i.putExtra("CHANGED", false); + i.putExtra("SYNCED", false); i.putExtra("SYNCINTERVAL", syncinterval); context.sendBroadcast(i); return; @@ -123,8 +123,8 @@ public void onPerformSync(Account account, Bundle extras, String authority, i.putExtra("ACCOUNTNAME", account.name); isChanged = true; isSynced = true; - i.putExtra("CHANGED", isChanged); - i.putExtra("SYNCED", isSynced); + i.putExtra("CHANGED", true); + i.putExtra("SYNCED", true); i.putExtra("SYNCINTERVAL", syncinterval); context.sendBroadcast(i); return; @@ -168,11 +168,15 @@ public void onPerformSync(Account account, Bundle extras, String authority, context.sendBroadcast(i); } + /* It is possible for this function to throw exceptions; the original code caught + MessagingException but just logged it instead of handling it. This results in a possibility of + returning null. Removing the catch fixies the possible null reference but of course means that + the caller becomes responsible. This is the correct approach. + + */ ImapNotes2Result ConnectToRemote() { AccountManager am = AccountManager.get(this.context); - ImapNotes2Result res = null; - try { - res = SyncUtils.ConnectToRemote( + ImapNotes2Result res = SyncUtils.ConnectToRemote( am.getUserData(account, ConfigurationFieldNames.UserName), am.getPassword(account), am.getUserData(account, ConfigurationFieldNames.Server), @@ -180,12 +184,8 @@ ImapNotes2Result ConnectToRemote() { Security.from(am.getUserData(account, ConfigurationFieldNames.Security)), am.getUserData(account, ConfigurationFieldNames.UseSticky), am.getUserData(account, ConfigurationFieldNames.ImapFolder)); - } catch (MessagingException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } if (res.returnCode != ResultCodeSuccess) { - Log.d(TAG, "Connection problem !!!"); + Log.d(TAG, "Connection problem: " + res.errorMessage); } return res; } @@ -214,20 +214,17 @@ private boolean handleNewNotes() { try { uids = SyncUtils.sendMessageToRemote(msg); - } catch (MessagingException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + // Update uid in database entry + String newuid = Long.toString(uids[0].uid); + storedNotes.UpdateANote(fileNew, newuid, account.name); + // move new note from new dir, one level up + File fileInNew = new File(dirNew, fileNew); + File to = new File(rootDir, newuid); + fileInNew.renameTo(to); + } catch (Exception e) { + // TODO: Handle message properly. + Log.d(TAG, e.getMessage()); } - // Update uid in database entry - String newuid = Long.toString(uids[0].uid); - storedNotes.UpdateANote(fileNew, newuid, account.name); - // move new note from new dir, one level up - File fileInNew = new File(dirNew, fileNew); - File to = new File(rootDir, newuid); - fileInNew.renameTo(to); } return newNotesManaged; } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java index ef565d16..465d4961 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java @@ -49,70 +49,47 @@ public class SyncUtils { static Store store; - static Session session; static final String TAG = "IN_SyncUtils"; static String proto; static String sfolder = "Notes"; static Folder notesFolder = null; - static ImapNotes2Result res = new ImapNotes2Result(); + private static ImapNotes2Result res = new ImapNotes2Result(); static Long UIDValidity; private final static int NEW = 1; private final static int DELETED = 2; private final static int ROOT_AND_NEW = 3; - public static ImapNotes2Result ConnectToRemote(String username, - String password, - String server, - String portnum, - Security security, - String usesticky, - String override) throws MessagingException { - if (IsConnected()) - store.close(); + /* This function cannot return null. Can we mark it so that the analysers can use this + information? + */ + static ImapNotes2Result ConnectToRemote(String username, + String password, + String server, + String portnum, + Security security, + String usesticky, + String override) { + if (IsConnected()) { + try { + store.close(); + } catch (MessagingException e) { + // Log the error but do not propagate the exception because the connection is now + // closed even if an exception was thrown. + Log.d(TAG, e.getMessage()); + } + } String folderoverride = (override == null) ? "" : override; proto = security.proto; boolean acceptcrt = security.acceptcrt; -/* - int security_i = Integer.parseInt(security); - switch (security_i) { - case 0: - // None - proto = "imap"; - acceptcrt = ""; - break; - case 1: - // SSL/TLS - proto = "imaps"; - acceptcrt = "false"; - break; - case 2: - // SSL/TLS/TRUST ALL - proto = "imaps"; - acceptcrt = "true"; - break; - case 3: - // STARTTLS - proto = "imap"; - acceptcrt = "false"; - break; - case 4: - // STARTTLS/TRUST ALL - proto = "imap"; - acceptcrt = "true"; - break; - default: - // TODO: Make sure that this cannot happen. - throw new InvalidParameterException("Invalid security: <" + security + ">"); - } -*/ + MailSSLSocketFactory sf = null; try { sf = new MailSSLSocketFactory(); } catch (GeneralSecurityException e) { e.printStackTrace(); - res.errorMessage = "Can't connect to server"; + res.errorMessage = "Can't connect to server: " + e.getMessage(); res.returnCode = Imaper.ResultCodeCantConnect; return res; } @@ -143,14 +120,15 @@ public static ImapNotes2Result ConnectToRemote(String username, props.setProperty("mail.imap.connectiontimeout", "1000"); // TODO: use user defined proxy. Boolean useProxy = false; + //noinspection ConstantConditions if (useProxy) { props.put("mail.imap.socks.host", "10.0.2.2"); props.put("mail.imap.socks.port", "1080"); } - session = Session.getInstance(props, null); -//this.session.setDebug(true); - store = session.getStore(proto); try { + Session session = Session.getInstance(props, null); +//this.session.setDebug(true); + store = session.getStore(proto); store.connect(server, username, password); res.hasUIDPLUS = ((IMAPStore) store).hasCapability("UIDPLUS"); //Log.d(TAG, "has UIDPLUS="+res.hasUIDPLUS); diff --git a/notes.org b/notes.org index 8f95566a..b6029f5a 100644 --- a/notes.org +++ b/notes.org @@ -1,12 +1,21 @@ * To do -Add configuration for directory synchronization. +** Add configuration for directory synchronization. -Implement synchronization. +** Implement synchronization. -Implement text file merging +** Implement text file merging -Implement Unix and Windows desktop versions. +** Implement Unix and Windows desktop versions. + +** Implement undo delete + +** Implement Autosave + + +First question is how is the note saved in the first place. + +Then can we do it automatically and then can we start the sync early? * Directory synchronization @@ -63,18 +72,13 @@ See: -* Auto save - -First question is how is the note saved in the first place. - -Then can we do it automatically and then can we start the sync early? * SQLite database This is used to store metadata about the notes. The notes themselves are stored as files in a sub-directory named after the account to -which they belong. +which they belong. The file names are the IMAP UIDs. * Code analysis @@ -83,8 +87,13 @@ convert fields to local variables, etc. ** Analyses done -| Analysis | Notes | -|--------------------+----------------------------------------------------------------------| -| Field can be local | Some of these seem to be work in progress so have been left unfixed. | -| | | +Ran whole project default profile to get an overview and then picked +one analysis at a time to be fixed, tested and committed. + +| Group | Analysis | Synopsis | Notes | +|---------------+----------------------------------+--------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------| +| | Field can be local | | Some of these seem to be work in progress so have been left unfixed. | +| | Parameter can be local | | No suspicious code found. | +| Probable bugs | Constant conditions & exceptions | Method invocation 'setDisplayHomeAsUpEnabled' at line 106 may produce 'java.lang.NullPointerException' | Suppressed because result is not used. | +| | | ConstantConditions | Some possible null pointers remain. | From ea7c88c292b4fe71a584b62285891af38c3b1076 Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Tue, 8 Nov 2016 13:58:22 +0100 Subject: [PATCH 016/103] Code Maturity analysis. --- ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java | 5 +++++ .../src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java | 2 +- .../src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java | 1 - 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java index 15dfb45c..69398b19 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java @@ -65,11 +65,16 @@ public void DeleteANote(String number, String accountname) { } public void UpdateANote(String olduid, String newuid, String accountname) { + /* TODO: use sql template and placeholders instead of string concatenation. + */ String req = "update notesTable set number='" + newuid + "' where number='-" + olduid + "' and accountname='" + accountname + "'"; this.notesDb.execSQL(req); } public String GetDate(String uid, String accountname) { + /* Returns a string representing the modification time of the note. + TODO: use date class. + */ String selectQuery = "select date from notesTable where number = '" + uid + "' and accountname='" + accountname + "'"; Cursor c = this.notesDb.rawQuery(selectQuery, null); if (c.moveToFirst()) { diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java index 444dd499..4ddf2221 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java @@ -299,7 +299,7 @@ public Filter getFilter() { * @see SimpleAdapter#setViewImage(ImageView, String) * @see SimpleAdapter#setViewText(TextView, String) */ - public static interface ViewBinder { + public interface ViewBinder { /** * Binds the specified data to the specified view. *

diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java index 465d4961..68a139d8 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java @@ -387,7 +387,6 @@ public static void GetOneNote(File outfile, Message notesMessage, NotesDb stored } catch (Exception e) { e.printStackTrace(); } - ; try { title = notesMessage.getSubject(); } catch (Exception e) { From c455f199d9b1c97d3957a6222f774354ac15db39 Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Tue, 8 Nov 2016 14:09:39 +0100 Subject: [PATCH 017/103] Pass arguments via constructor instead of execute; thi means that we do not need to cast or convert. --- .../com/Pau/ImapNotes2/Miscs/SyncThread.java | 26 +++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/SyncThread.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/SyncThread.java index edcf25a3..c29c9063 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/SyncThread.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/SyncThread.java @@ -23,18 +23,40 @@ public class SyncThread extends AsyncTask { Context ctx; private static final String TAG = "SyncThread"; + // TODO: remove unused arguments. + public SyncThread(Object imapFolder, + ImapNotes2Account imapNotes2Account, + ArrayList noteList, + NotesListAdapter listToView, + ProgressDialog loadingDialog, + NotesDb storedNotes, + Context applicationContext) { + //this.imapFolder = imapFolder; + //this.imapNotes2Account = imapNotes2Account; + this.notesList = noteList; + this.adapter = listToView; + //this.loadingDialog = loadingDialog; + this.storedNotes = storedNotes; + this.ctx = applicationContext; + + } + + // Do not pass arguments via execute; the object is never reused so it is quite safe to pass + // the arguments in the constructor. @Override protected Boolean doInBackground(Object... stuffs) { - String username = null; + /*String username = null; String password = null; String server = null; String portnum = null; String security = null; String usesticky = null; - this.adapter = ((NotesListAdapter) stuffs[3]); +*/ + /* this.adapter = ((NotesListAdapter) stuffs[3]); this.notesList = ((ArrayList) stuffs[2]); this.storedNotes = ((NotesDb) stuffs[5]); this.ctx = (Context) stuffs[6]; + */ //username = ((ImapNotes2Account) stuffs[1]).GetUsername(); //password = ((ImapNotes2Account) stuffs[1]).GetPassword(); //server = ((ImapNotes2Account) stuffs[1]).GetServer(); From 50e9d13900bf7f6d18bef6a8b14eb781b5b50662 Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Tue, 8 Nov 2016 14:15:03 +0100 Subject: [PATCH 018/103] Removed all unused imports. --- ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java | 2 -- .../src/main/java/com/Pau/ImapNotes2/Miscs/SyncThread.java | 4 ---- .../src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java | 3 --- ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/Security.java | 3 --- 4 files changed, 12 deletions(-) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java index 69398b19..75545c95 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java @@ -4,7 +4,6 @@ import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; -import java.util.Arrays; import java.util.Date; import com.Pau.ImapNotes2.Miscs.OneNote; @@ -14,7 +13,6 @@ import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; -import android.util.Log; public class NotesDb { diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/SyncThread.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/SyncThread.java index c29c9063..a671739b 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/SyncThread.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/SyncThread.java @@ -4,15 +4,11 @@ import com.Pau.ImapNotes2.Listactivity; import com.Pau.ImapNotes2.NotesListAdapter; -import com.Pau.ImapNotes2.Data.ImapNotes2Account; import com.Pau.ImapNotes2.Data.NotesDb; import android.app.ProgressDialog; import android.content.Context; import android.os.AsyncTask; -import android.util.Log; -import android.widget.SimpleAdapter; -import android.widget.Toast; public class SyncThread extends AsyncTask { NotesListAdapter adapter; diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java index b90d12a6..3d353c4a 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java @@ -8,7 +8,6 @@ import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; -import java.util.Objects; import java.util.Properties; import java.util.UUID; @@ -20,7 +19,6 @@ import com.Pau.ImapNotes2.ImapNotes2k; import com.Pau.ImapNotes2.Listactivity; -import com.Pau.ImapNotes2.NoteDetailActivity; import com.Pau.ImapNotes2.NotesListAdapter; import com.Pau.ImapNotes2.Data.ImapNotes2Account; import com.Pau.ImapNotes2.Data.NotesDb; @@ -29,7 +27,6 @@ import android.content.Context; import android.os.AsyncTask; import android.text.Html; -import android.widget.Adapter; import static com.Pau.ImapNotes2.NoteDetailActivity.*; diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/Security.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/Security.java index f9a88216..2ca90695 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/Security.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/Security.java @@ -1,8 +1,5 @@ package com.Pau.ImapNotes2.Sync; -import android.annotation.TargetApi; -import android.os.Build; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; From 20c7ac50c0cdc690817cf846b5dd48efa444cd68 Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Tue, 8 Nov 2016 14:22:36 +0100 Subject: [PATCH 019/103] Removed redundant local variables. --- .../java/com/Pau/ImapNotes2/Data/ConfigurationFieldNames.java | 2 +- .../src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java | 1 - ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java | 3 +-- 3 files changed, 2 insertions(+), 4 deletions(-) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFieldNames.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFieldNames.java index 558b4e91..3c9dae59 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFieldNames.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFieldNames.java @@ -1,7 +1,7 @@ package com.Pau.ImapNotes2.Data; /** - * Created by kj on 11/7/16. + * Created by kj on 2016-11-08 14:18. */ public final class ConfigurationFieldNames { diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java index 3d353c4a..37d208c4 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java @@ -61,7 +61,6 @@ public UpdateThread(Imaper imapFolder, String action, NotesDb storedNotes) { - Imaper imapFolder1 = imapFolder; this.imapNotes2Account = imapNotes2Account; this.notesList = noteList; this.adapter = listToView; diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java index 68a139d8..69f5008a 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java @@ -329,8 +329,7 @@ public static AppendUID[] sendMessageToRemote(Message[] message) throws Messagin } else { notesFolder.open(Folder.READ_WRITE); } - AppendUID[] uids = ((IMAPFolder) notesFolder).appendUIDMessages(message); - return uids; + return ((IMAPFolder) notesFolder).appendUIDMessages(message); } public static void ClearHomeDir(Account account, Context ctx) { From 2283aa8ad509fe860edb54bb8c0aa1b7861537c8 Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Tue, 8 Nov 2016 14:32:24 +0100 Subject: [PATCH 020/103] Use class instead of instance to refer to static fields. --- .../com/Pau/ImapNotes2/Miscs/SyncThread.java | 1 + .../com/Pau/ImapNotes2/Sync/SyncAdapter.java | 39 +++++++++++-------- 2 files changed, 23 insertions(+), 17 deletions(-) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/SyncThread.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/SyncThread.java index a671739b..1f644fcf 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/SyncThread.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/SyncThread.java @@ -2,6 +2,7 @@ import java.util.ArrayList; +import com.Pau.ImapNotes2.Data.ImapNotes2Account; import com.Pau.ImapNotes2.Listactivity; import com.Pau.ImapNotes2.NotesListAdapter; import com.Pau.ImapNotes2.Data.NotesDb; diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java index 755f4494..8385427a 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java @@ -43,39 +43,43 @@ class SyncAdapter extends AbstractThreadedSyncAdapter { private final ContentResolver mContentResolver; - public SyncAdapter(Context context, boolean autoInitialize) { + public SyncAdapter(Context context, + boolean autoInitialize) { super(context, autoInitialize); mContentResolver = context.getContentResolver(); - this.context = context; + // TODO: do we really need a copy of the context reference? + SyncAdapter.context = context; } public SyncAdapter(Context context, boolean autoInitialize, // ? - boolean allowParallelSyncs // always false, set - // in - // syncadapter.xml + boolean allowParallelSyncs // always false, set in syncadapter.xml ) { super(context, autoInitialize, allowParallelSyncs); mContentResolver = context.getContentResolver(); - this.context = context; + SyncAdapter.context = context; } @Override - public void onPerformSync(Account account, Bundle extras, String authority, + public void onPerformSync(Account account, + Bundle extras, + String authority, ContentProviderClient provider, SyncResult syncResult) { //Log.d(TAG, "Beginning network synchronization of account: "+account.name); - this.account = account; + // TODO: should the account be static? Should it be local? If static then why do we not + // provide it in the constructor? + SyncAdapter.account = account; Boolean isChanged = false; Boolean isSynced = false; String syncinterval; - SyncUtils.CreateDirs(account.name, this.context); + SyncUtils.CreateDirs(account.name, context); - storedNotes = new NotesDb(this.context); + storedNotes = new NotesDb(context); storedNotes.OpenDb(); - AccountManager am = AccountManager.get(this.context); + AccountManager am = AccountManager.get(context); syncinterval = am.getUserData(account, "syncinterval"); // Connect to remote and get UIDValidity @@ -96,19 +100,20 @@ public void onPerformSync(Account account, Bundle extras, String authority, return; } // Compare UIDValidity to old saved one + // if (!(res.UIDValidity.equals - (SyncUtils.GetUIDValidity(this.account, this.context)))) { + (SyncUtils.GetUIDValidity(SyncAdapter.account, context)))) { // Replace local data by remote try { // delete notes in NotesDb for this account storedNotes.ClearDb(account.name); // delete notes in folders for this account and recreate dirs - SyncUtils.ClearHomeDir(account, this.context); - SyncUtils.CreateDirs(account.name, this.context); + SyncUtils.ClearHomeDir(account, context); + SyncUtils.CreateDirs(account.name, context); // Get all notes from remote and replace local SyncUtils.GetNotes(account, res.notesFolder, - this.context, storedNotes); + context, storedNotes); storedNotes.CloseDb(); } catch (MessagingException e) { // TODO Auto-generated catch block @@ -117,7 +122,7 @@ public void onPerformSync(Account account, Bundle extras, String authority, // TODO Auto-generated catch block e.printStackTrace(); } - SyncUtils.SetUIDValidity(account, res.UIDValidity, this.context); + SyncUtils.SetUIDValidity(account, res.UIDValidity, context); // Notify Listactivity that it's finished, and that it can refresh display Intent i = new Intent(SyncService.SYNC_FINISHED); i.putExtra("ACCOUNTNAME", account.name); @@ -175,7 +180,7 @@ public void onPerformSync(Account account, Bundle extras, String authority, */ ImapNotes2Result ConnectToRemote() { - AccountManager am = AccountManager.get(this.context); + AccountManager am = AccountManager.get(context); ImapNotes2Result res = SyncUtils.ConnectToRemote( am.getUserData(account, ConfigurationFieldNames.UserName), am.getPassword(account), From 42a2756d0acbe2cdcb19658c82fdbd6457b78f42 Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Tue, 8 Nov 2016 14:34:53 +0100 Subject: [PATCH 021/103] Accepted all Declaration access can be weaker suggestions. --- .../ImapNotes2/AccountConfigurationActivity.java | 6 +++--- .../java/com/Pau/ImapNotes2/Listactivity.java | 14 +++++++------- .../java/com/Pau/ImapNotes2/Miscs/Imaper.java | 2 +- .../com/Pau/ImapNotes2/Miscs/SyncThread.java | 8 ++++---- .../com/Pau/ImapNotes2/Miscs/UpdateThread.java | 8 ++++---- .../com/Pau/ImapNotes2/NotesListAdapter.java | 6 +++--- .../com/Pau/ImapNotes2/Sync/SyncAdapter.java | 4 ++-- .../java/com/Pau/ImapNotes2/Sync/SyncUtils.java | 16 ++++++++-------- 8 files changed, 32 insertions(+), 32 deletions(-) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java index eeaa1fdb..b12dab9c 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java @@ -36,8 +36,8 @@ import static com.Pau.ImapNotes2.Miscs.Imaper.ResultCodeSuccess; public class AccountConfigurationActivity extends AccountAuthenticatorActivity implements OnItemSelectedListener { - public static final int TO_REFRESH = 999; - public static final String AUTHORITY = "com.Pau.ImapNotes2.provider"; + private static final int TO_REFRESH = 999; + private static final String AUTHORITY = "com.Pau.ImapNotes2.provider"; private static final String TAG = "AccountConfigurationActivity"; private Imaper imapFolder; @@ -215,7 +215,7 @@ private String GetConfigValue(String name) { } // DoLogin method is defined in account_selection.xml (account_selection layout) - public void DoLogin(View v) { + private void DoLogin(View v) { ProgressDialog loadingDialog = ProgressDialog.show(this, "ImapNotes2", "Logging into your account... ", true); imapNotes2Account.SetAccountname(accountnameTextView.getText().toString().trim()); imapNotes2Account.SetUsername(usernameTextView.getText().toString().trim()); diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java index 79c06c66..156433b6 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java @@ -83,7 +83,7 @@ public class Listactivity extends Activity implements OnItemSelectedListener, Fi private static List currentList; private TextView status = null; private static String OldStatus; - public static final String AUTHORITY = "com.Pau.ImapNotes2.provider"; + private static final String AUTHORITY = "com.Pau.ImapNotes2.provider"; private static final String TAG = "IN_Listactivity"; @@ -219,17 +219,17 @@ public void onReceive(Context context, Intent intent) { } }; - public void RefreshList() { + private void RefreshList() { ProgressDialog loadingDialog = ProgressDialog.show(this, "ImapNotes2", "Refreshing notes list... ", true); new SyncThread().execute(this.imapFolder, Listactivity.imapNotes2Account, this.noteList, this.listToView, loadingDialog, storedNotes, this.getApplicationContext()); status.setText("Welcome"); } - public void UpdateList(String suid, - String noteBody, - Colors color, - String action) { + private void UpdateList(String suid, + String noteBody, + Colors color, + String action) { ProgressDialog loadingDialog = ProgressDialog.show(this, "imapnote2", "Updating notes list... ", true); new UpdateThread(this.imapFolder, Listactivity.imapNotes2Account, this.noteList, @@ -507,7 +507,7 @@ public void SendLogcatMail() { startActivity(Intent.createChooser(emailIntent, "Send email...")); } - public static void TriggerSync(TextView statusField) { + private static void TriggerSync(TextView statusField) { OldStatus = statusField.getText().toString(); statusField.setText("Syncing..."); Account mAccount = Listactivity.imapNotes2Account.GetAccount(); diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Imaper.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Imaper.java index 6182c2d5..48ad63b6 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Imaper.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Imaper.java @@ -157,7 +157,7 @@ public ImapNotes2Result ConnectToProvider(String username, } - public boolean IsConnected() { + private boolean IsConnected() { return store != null && store.isConnected(); } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/SyncThread.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/SyncThread.java index 1f644fcf..4485d89e 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/SyncThread.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/SyncThread.java @@ -12,12 +12,12 @@ import android.os.AsyncTask; public class SyncThread extends AsyncTask { - NotesListAdapter adapter; - ArrayList notesList; - NotesDb storedNotes; + private NotesListAdapter adapter; + private ArrayList notesList; + private NotesDb storedNotes; boolean bool_to_return; ImapNotes2Result res = new ImapNotes2Result(); - Context ctx; + private Context ctx; private static final String TAG = "SyncThread"; // TODO: remove unused arguments. diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java index 37d208c4..c69664ec 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java @@ -154,7 +154,7 @@ protected void onPostExecute(Boolean result) { } } - public int getIndexByNumber(String pNumber) { + private int getIndexByNumber(String pNumber) { for (OneNote _item : notesList) { if (_item.GetUid().equals(pNumber)) return notesList.indexOf(_item); @@ -176,9 +176,9 @@ private void MoveMailToDeleted(String suid) { } } - public void WriteMailToNew(OneNote note, - boolean usesticky, - String noteBody) throws MessagingException, IOException { + private void WriteMailToNew(OneNote note, + boolean usesticky, + String noteBody) throws MessagingException, IOException { String body = null; // Here we add the new note to the "new" folder diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java index 4ddf2221..d61a972e 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java @@ -240,7 +240,7 @@ public void setViewBinder(ViewBinder viewBinder) { * @param value the value retrieved from the data set * @see #setViewImage(ImageView, String) */ - public void setViewImage(ImageView v, int value) { + private void setViewImage(ImageView v, int value) { v.setImageResource(value); } @@ -260,7 +260,7 @@ public void setViewImage(ImageView v, int value) { * @param value the value retrieved from the data set * @see #setViewImage(ImageView, int) */ - public void setViewImage(ImageView v, String value) { + private void setViewImage(ImageView v, String value) { try { v.setImageResource(Integer.parseInt(value)); } catch (NumberFormatException nfe) { @@ -276,7 +276,7 @@ public void setViewImage(ImageView v, String value) { * @param v TextView to receive text * @param text the text to be set for the TextView */ - public void setViewText(TextView v, String text) { + private void setViewText(TextView v, String text) { v.setText(text); } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java index 8385427a..47051a94 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java @@ -32,7 +32,7 @@ /// because the sync happens under Android control not under control /// of the application. class SyncAdapter extends AbstractThreadedSyncAdapter { - public static final String TAG = "SyncAdapter"; + private static final String TAG = "SyncAdapter"; private static Context context; private NotesDb storedNotes; private static Account account; @@ -179,7 +179,7 @@ public void onPerformSync(Account account, the caller becomes responsible. This is the correct approach. */ - ImapNotes2Result ConnectToRemote() { + private ImapNotes2Result ConnectToRemote() { AccountManager am = AccountManager.get(context); ImapNotes2Result res = SyncUtils.ConnectToRemote( am.getUserData(account, ConfigurationFieldNames.UserName), diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java index 69f5008a..5e6b249e 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java @@ -48,13 +48,13 @@ public class SyncUtils { - static Store store; - static final String TAG = "IN_SyncUtils"; - static String proto; - static String sfolder = "Notes"; - static Folder notesFolder = null; + private static Store store; + private static final String TAG = "IN_SyncUtils"; + private static String proto; + private static String sfolder = "Notes"; + private static Folder notesFolder = null; private static ImapNotes2Result res = new ImapNotes2Result(); - static Long UIDValidity; + private static Long UIDValidity; private final static int NEW = 1; private final static int DELETED = 2; private final static int ROOT_AND_NEW = 3; @@ -228,7 +228,7 @@ public static Sticky ReadStickynote(String stringres) { return new Sticky(text, position, color); } - public static boolean IsConnected() { + private static boolean IsConnected() { return store != null && store.isConnected(); } @@ -352,7 +352,7 @@ public static void CreateDirs(String accountName, Context ctx) { directory.mkdirs(); } - public static void GetOneNote(File outfile, Message notesMessage, NotesDb storedNotes, String accountName, String suid, boolean updateDb) { + private static void GetOneNote(File outfile, Message notesMessage, NotesDb storedNotes, String accountName, String suid, boolean updateDb) { OutputStream str = null; try { From 1a6006c97e92ab84ddb045a61d3fb09e8593565e Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Tue, 8 Nov 2016 14:35:57 +0100 Subject: [PATCH 022/103] Applied fix Make Final to all suggested lines. --- .../Pau/ImapNotes2/AccountConfigurationActivity.java | 10 +++++----- .../src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java | 4 ++-- .../src/main/java/com/Pau/ImapNotes2/Listactivity.java | 4 ++-- .../Miscs/ImapNotesAuthenticatorService.java | 2 +- .../main/java/com/Pau/ImapNotes2/NotesListAdapter.java | 8 ++++---- .../main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java | 2 +- 6 files changed, 15 insertions(+), 15 deletions(-) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java index b12dab9c..07999f26 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java @@ -60,7 +60,7 @@ public class AccountConfigurationActivity extends AccountAuthenticatorActivity i private static Account myAccount = null; private static AccountManager accountManager; - private OnClickListener clickListenerLogin = new View.OnClickListener() { + private final OnClickListener clickListenerLogin = new View.OnClickListener() { @Override public void onClick(View v) { // Click on Login Button @@ -74,7 +74,7 @@ public void onClick(View v) { } }; - private OnClickListener clickListenerEdit = new View.OnClickListener() { + private final OnClickListener clickListenerEdit = new View.OnClickListener() { @Override public void onClick(View v) { // Click on Edit Button @@ -88,7 +88,7 @@ public void onClick(View v) { } }; - private OnClickListener clickListenerRemove = new View.OnClickListener() { + private final OnClickListener clickListenerRemove = new View.OnClickListener() { @Override public void onClick(View v) { // Clic on Remove Button @@ -242,9 +242,9 @@ class LoginThread extends AsyncTask { private final ProgressDialog progressDialog; private final long SYNC_FREQUENCY; - private AccountConfigurationActivity accountConfigurationActivity; + private final AccountConfigurationActivity accountConfigurationActivity; private ImapNotes2Result res = new ImapNotes2Result(); - private String action; + private final String action; public LoginThread(Imaper mapFolder, ImapNotes2Account imapNotes2Account, diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java index 75545c95..806ad763 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java @@ -18,7 +18,7 @@ public class NotesDb { private static final int NOTES_VERSION = 3; private static final String TAG = "IN_NotesDb"; - private Context ctx; + private final Context ctx; private static final String CREATE_NOTES_DB = "CREATE TABLE IF NOT EXISTS " + "notesTable (" @@ -29,7 +29,7 @@ public class NotesDb { + "accountname text not null);"; private SQLiteDatabase notesDb; - private NotesDbHelper defaultHelper; + private final NotesDbHelper defaultHelper; public NotesDb(Context applicationContext) { this.defaultHelper = new NotesDbHelper(applicationContext, "NotesDb", NOTES_VERSION); diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java index 156433b6..01c1627c 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java @@ -87,7 +87,7 @@ public class Listactivity extends Activity implements OnItemSelectedListener, Fi private static final String TAG = "IN_Listactivity"; - private OnClickListener clickListenerEditAccount = new View.OnClickListener() { + private final OnClickListener clickListenerEditAccount = new View.OnClickListener() { @Override public void onClick(View v) { Intent res = new Intent(); @@ -187,7 +187,7 @@ protected void onPause() { unregisterReceiver(syncFinishedReceiver); } - private BroadcastReceiver syncFinishedReceiver = new BroadcastReceiver() { + private final BroadcastReceiver syncFinishedReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { String accountname = intent.getStringExtra("ACCOUNTNAME"); diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/ImapNotesAuthenticatorService.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/ImapNotesAuthenticatorService.java index 92a3c0ff..118ba8bb 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/ImapNotesAuthenticatorService.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/ImapNotesAuthenticatorService.java @@ -41,7 +41,7 @@ private Authenticator getAuthenticator() { private static class Authenticator extends AbstractAccountAuthenticator { - private Context mContext; + private final Context mContext; public Authenticator(Context context) { super(context); diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java index d61a972e..3ccd2ad9 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java @@ -55,15 +55,15 @@ * If no appropriate binding can be found, an {@link IllegalStateException} is thrown. */ public class NotesListAdapter extends BaseAdapter implements Filterable { - private int[] mTo; - private String[] mFrom; + private final int[] mTo; + private final String[] mFrom; private ViewBinder mViewBinder; private List> mData; - private int mResource; + private final int mResource; private int mDropDownResource; - private LayoutInflater mInflater; + private final LayoutInflater mInflater; private SimpleFilter mFilter; private ArrayList> mUnfilteredData; diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java index 5e6b249e..dc80a032 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java @@ -53,7 +53,7 @@ public class SyncUtils { private static String proto; private static String sfolder = "Notes"; private static Folder notesFolder = null; - private static ImapNotes2Result res = new ImapNotes2Result(); + private static final ImapNotes2Result res = new ImapNotes2Result(); private static Long UIDValidity; private final static int NEW = 1; private final static int DELETED = 2; From 2986e119c90c46ac02fbb2a81d9f5c0dcb48961c Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Tue, 8 Nov 2016 14:36:53 +0100 Subject: [PATCH 023/103] Removed all redundant throws. --- .../src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java index dc80a032..581284b0 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java @@ -166,7 +166,7 @@ static ImapNotes2Result ConnectToRemote(String username, public static void GetNotes(Account account, Folder notesFolder, Context ctx, - NotesDb storedNotes) throws MessagingException, IOException { + NotesDb storedNotes) throws MessagingException { //Long UIDM; //Message notesMessage; File directory = new File(ctx.getFilesDir() + "/" + account.name); @@ -232,7 +232,7 @@ private static boolean IsConnected() { return store != null && store.isConnected(); } - public static void DeleteNote(int numMessage) throws MessagingException, IOException { + public static void DeleteNote(int numMessage) throws MessagingException { Folder notesFolder = store.getFolder(sfolder); if (notesFolder.isOpen()) { if ((notesFolder.getMode() & Folder.READ_WRITE) != 0) { @@ -321,7 +321,7 @@ public static Message ReadMailFromFile(String uid, int where, boolean removeMinu return message; } - public static AppendUID[] sendMessageToRemote(Message[] message) throws MessagingException, IOException { + public static AppendUID[] sendMessageToRemote(Message[] message) throws MessagingException { notesFolder = store.getFolder(sfolder); if (notesFolder.isOpen()) { if ((notesFolder.getMode() & Folder.READ_WRITE) != 0) @@ -428,7 +428,7 @@ private static void GetOneNote(File outfile, Message notesMessage, NotesDb store } public static boolean handleRemoteNotes(Context context, Folder notesFolder, NotesDb storedNotes, String accountName, String usesticky) - throws MessagingException, IOException { + throws MessagingException { Message notesMessage; boolean result = false; From 52eb61fd5254c8174c8829eb428a6222fe27dcb1 Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Tue, 8 Nov 2016 14:40:56 +0100 Subject: [PATCH 024/103] Use <> instead of explicit type arguments. --- .../java/com/Pau/ImapNotes2/Data/ConfigurationFieldNames.java | 2 +- .../main/java/com/Pau/ImapNotes2/Data/ConfigurationFile.java | 2 ++ ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java | 2 +- .../src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java | 4 ++-- ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/Security.java | 4 ++-- .../src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java | 4 ++-- 6 files changed, 10 insertions(+), 8 deletions(-) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFieldNames.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFieldNames.java index 3c9dae59..d95ef609 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFieldNames.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFieldNames.java @@ -1,7 +1,7 @@ package com.Pau.ImapNotes2.Data; /** - * Created by kj on 2016-11-08 14:18. + * Created by kj on 2016-11-08 14:38. */ public final class ConfigurationFieldNames { diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFile.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFile.java index 689ebb0a..572c451f 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFile.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFile.java @@ -121,10 +121,12 @@ public void SetPortnum(String Portnum) { public Security GetSecurity() { return security; } +/* public void SetSecurity(Security security) { security = security; } +*/ public boolean GetUsesticky() { return usesticky; diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java index 01c1627c..f2ba2051 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java @@ -425,7 +425,7 @@ public void onAccountsUpdated(Account[] accounts) { i++; } Listactivity.accounts = imapNotes2Accounts; - newList = new ArrayList(); + newList = new ArrayList<>(); for (Account account : Listactivity.accounts) { newList.add(account.name); } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java index 3ccd2ad9..54661541 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java @@ -329,7 +329,7 @@ protected FilterResults performFiltering(CharSequence prefix) { FilterResults results = new FilterResults(); if (mUnfilteredData == null) { - mUnfilteredData = new ArrayList>(mData); + mUnfilteredData = new ArrayList<>(mData); } if (prefix == null || prefix.length() == 0) { @@ -342,7 +342,7 @@ protected FilterResults performFiltering(CharSequence prefix) { ArrayList> unfilteredValues = mUnfilteredData; int count = unfilteredValues.size(); - ArrayList> newValues = new ArrayList>(count); + ArrayList> newValues = new ArrayList<>(count); for (int i = 0; i < count; i++) { Map h = unfilteredValues.get(i); diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/Security.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/Security.java index 2ca90695..7142b5d8 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/Security.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/Security.java @@ -38,7 +38,7 @@ public enum Security { } public static List Printables() { - List list = new ArrayList(); + List list = new ArrayList<>(); for (Security e : Security.values()) { list.add(e.printable); } @@ -46,7 +46,7 @@ public static List Printables() { } // Mapping from integer. See http://dan.clarke.name/2011/07/enum-in-java-with-int-conversion/ - private static final Map _map = new HashMap(); + private static final Map _map = new HashMap<>(); static { for (Security security : Security.values()) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java index 581284b0..efe64d60 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java @@ -432,8 +432,8 @@ public static boolean handleRemoteNotes(Context context, Folder notesFolder, Not Message notesMessage; boolean result = false; - ArrayList uids = new ArrayList(); - ArrayList localListOfNotes = new ArrayList(); + ArrayList uids = new ArrayList<>(); + ArrayList localListOfNotes = new ArrayList<>(); String remoteInternaldate; String localInternaldate; Flags flags; From 42fe7d4af7ddeee3533f9efbadf37708d3e74503 Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Tue, 8 Nov 2016 17:45:54 +0100 Subject: [PATCH 025/103] Fixed empty XML elements. --- .../java/com/Pau/ImapNotes2/Data/NotesDb.java | 4 ++-- .../java/com/Pau/ImapNotes2/Listactivity.java | 2 +- .../com/Pau/ImapNotes2/NewNoteActivity.java | 2 +- .../com/Pau/ImapNotes2/Sync/SyncUtils.java | 4 ++-- .../src/main/res/layout/account_selection.xml | 24 +++++++++---------- ImapNote2/src/main/res/layout/main.xml | 2 +- ImapNote2/src/main/res/layout/new_note.xml | 2 +- ImapNote2/src/main/res/layout/note_detail.xml | 2 +- .../src/main/res/layout/note_element.xml | 4 ++-- 9 files changed, 23 insertions(+), 23 deletions(-) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java index 806ad763..6b0880ed 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java @@ -108,9 +108,9 @@ public void GetStoredNotes(ArrayList noteList, String accountname) { try { date = sdf.parse(resultPointer.getString(dateIndex)); } catch (ParseException e) { - //Exception handling + // TODO: Exception handling } catch (Exception e) { - //handle exception + // TODO: handle exception } DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(this.ctx); //String sdate = dateFormat.format(date); diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java index f2ba2051..a2ff0384 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java @@ -487,7 +487,7 @@ public void SendLogcatMail() { StringBuilder sb = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { - sb.append(line + "\n"); + sb.append(line).append("\n"); } emailData = sb.toString(); } catch (IOException e) { diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NewNoteActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NewNoteActivity.java index a0ac19ef..6f24a9db 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NewNoteActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NewNoteActivity.java @@ -27,7 +27,7 @@ public void onCreate(Bundle savedInstanceState) { } private void ResetColors() { - ((EditText) findViewById(R.id.editNote)).setBackgroundColor(Color.TRANSPARENT); + findViewById(R.id.editNote).setBackgroundColor(Color.TRANSPARENT); ((EditText) findViewById(R.id.editNote)).setTextColor(Color.BLACK); } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java index efe64d60..3d4e563a 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java @@ -511,8 +511,8 @@ public static void RemoveAccount(Context context, Account account) { // Remove all files and sub directories File filesDir = context.getFilesDir(); File[] files = filesDir.listFiles(); - for (int i = 0; i < files.length; i++) { - files[i].delete(); + for (File file : files) { + file.delete(); } // Delete account name entries in database NotesDb storedNotes = new NotesDb(context); diff --git a/ImapNote2/src/main/res/layout/account_selection.xml b/ImapNote2/src/main/res/layout/account_selection.xml index da4e2e3b..dd161ad2 100644 --- a/ImapNote2/src/main/res/layout/account_selection.xml +++ b/ImapNote2/src/main/res/layout/account_selection.xml @@ -17,7 +17,7 @@ android:layout_marginBottom="10dip" android:text="Add Account" android:textAppearance="?android:attr/textAppearanceLarge" - android:textColor="#000000"> + android:textColor="#000000" /> + android:textColor="#000000" /> - + + android:textColor="#000000" /> + android:inputType="textEmailAddress" /> + android:textColor="#000000" /> + android:inputType="textPassword" /> + android:textColor="#000000" /> + android:inputType="textNoSuggestions|text|textVisiblePassword" /> + android:textColor="#000000" /> + android:layout_height="wrap_content" /> + android:textColor="#000000" /> + android:layout_height="fill_parent" /> diff --git a/ImapNote2/src/main/res/layout/new_note.xml b/ImapNote2/src/main/res/layout/new_note.xml index 3eb189db..92967916 100644 --- a/ImapNote2/src/main/res/layout/new_note.xml +++ b/ImapNote2/src/main/res/layout/new_note.xml @@ -16,7 +16,7 @@ android:ems="10" android:inputType="textMultiLine"> - + diff --git a/ImapNote2/src/main/res/layout/note_detail.xml b/ImapNote2/src/main/res/layout/note_detail.xml index 9bb603ff..6f353155 100644 --- a/ImapNote2/src/main/res/layout/note_detail.xml +++ b/ImapNote2/src/main/res/layout/note_detail.xml @@ -21,7 +21,7 @@ android:inputType="textMultiLine" android:onClick="onClick"> - + diff --git a/ImapNote2/src/main/res/layout/note_element.xml b/ImapNote2/src/main/res/layout/note_element.xml index 86428490..69bf13ff 100644 --- a/ImapNote2/src/main/res/layout/note_element.xml +++ b/ImapNote2/src/main/res/layout/note_element.xml @@ -17,7 +17,7 @@ android:singleLine="true" android:text="Note Title" android:textAppearance="?android:attr/textAppearanceLarge" - android:textColor="#000000"> + android:textColor="#000000" /> + android:textColor="#838383" /> From 20328e7811d240db90d160edafef3892fbbf3db0 Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Tue, 8 Nov 2016 18:59:41 +0100 Subject: [PATCH 026/103] Oops, forgot the progree dialog in doInBackground. Fixed. --- .../java/com/Pau/ImapNotes2/Listactivity.java | 8 +++++++- .../com/Pau/ImapNotes2/Miscs/SyncThread.java | 17 ++++++++--------- .../com/Pau/ImapNotes2/NewNoteActivity.java | 8 ++++++-- .../com/Pau/ImapNotes2/NoteDetailActivity.java | 3 ++- .../com/Pau/ImapNotes2/Sync/SyncAdapter.java | 6 ------ 5 files changed, 23 insertions(+), 19 deletions(-) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java index a2ff0384..92a31f80 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java @@ -222,7 +222,13 @@ public void onReceive(Context context, Intent intent) { private void RefreshList() { ProgressDialog loadingDialog = ProgressDialog.show(this, "ImapNotes2", "Refreshing notes list... ", true); - new SyncThread().execute(this.imapFolder, Listactivity.imapNotes2Account, this.noteList, this.listToView, loadingDialog, storedNotes, this.getApplicationContext()); + new SyncThread(this.imapFolder, + Listactivity.imapNotes2Account, + this.noteList, + this.listToView, + loadingDialog, + storedNotes, + this.getApplicationContext()).execute(); status.setText("Welcome"); } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/SyncThread.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/SyncThread.java index 4485d89e..b49f4acb 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/SyncThread.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/SyncThread.java @@ -12,12 +12,12 @@ import android.os.AsyncTask; public class SyncThread extends AsyncTask { + private final ProgressDialog progressDialog; private NotesListAdapter adapter; private ArrayList notesList; private NotesDb storedNotes; boolean bool_to_return; ImapNotes2Result res = new ImapNotes2Result(); - private Context ctx; private static final String TAG = "SyncThread"; // TODO: remove unused arguments. @@ -32,9 +32,9 @@ public SyncThread(Object imapFolder, //this.imapNotes2Account = imapNotes2Account; this.notesList = noteList; this.adapter = listToView; - //this.loadingDialog = loadingDialog; - this.storedNotes = storedNotes; - this.ctx = applicationContext; + this.progressDialog = loadingDialog; + //this.storedNotes = storedNotes; + this.storedNotes = (storedNotes == null) ? new NotesDb(applicationContext) : storedNotes; } @@ -62,11 +62,10 @@ protected Boolean doInBackground(Object... stuffs) { //usesticky = ((ImapNotes2Account) stuffs[1]).GetUsesticky(); - if (this.storedNotes == null) this.storedNotes = new NotesDb(this.ctx); - this.storedNotes.OpenDb(); - this.storedNotes.GetStoredNotes(this.notesList, Listactivity.imapNotes2Account.GetAccountname()); - this.storedNotes.CloseDb(); - ((ProgressDialog) stuffs[4]).dismiss(); + storedNotes.OpenDb(); + storedNotes.GetStoredNotes(this.notesList, Listactivity.imapNotes2Account.GetAccountname()); + storedNotes.CloseDb(); + progressDialog.dismiss(); return true; } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NewNoteActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NewNoteActivity.java index 6f24a9db..a8b0dea7 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NewNoteActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NewNoteActivity.java @@ -10,12 +10,16 @@ import android.view.MenuItem; import android.widget.EditText; +import static com.Pau.ImapNotes2.NoteDetailActivity.*; +import static com.Pau.ImapNotes2.NoteDetailActivity.Colors.NONE; +import static com.Pau.ImapNotes2.NoteDetailActivity.Colors.YELLOW; + public class NewNoteActivity extends Activity { private static final int SAVE_BUTTON = 5; private static final String TAG = "IN_NewNoteActivity"; private boolean sticky; - private String color = "NONE"; + private Colors color = NONE; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -42,7 +46,7 @@ public boolean onOptionsItemSelected(MenuItem item) { Intent intent = new Intent(); intent.putExtra("SAVE_ITEM", Html.toHtml(((EditText) findViewById(R.id.editNote)).getText())); if (this.sticky) { - this.color = "YELLOW"; + this.color = YELLOW; } intent.putExtra("SAVE_ITEM_COLOR", this.color); setResult(SAVE_BUTTON, intent); diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java index f5fb180a..ea694dfe 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java @@ -33,6 +33,7 @@ import javax.mail.internet.ContentType; import static com.Pau.ImapNotes2.NoteDetailActivity.Colors.BLUE; +import static com.Pau.ImapNotes2.NoteDetailActivity.Colors.NONE; public class NoteDetailActivity extends Activity { @@ -217,7 +218,7 @@ private Sticky GetInfoFromMessage(Message message) { ContentType contentType = null; String stringres = null; InputStream iis = null; - String color = "NONE"; + //Colors color = NONE; String charset; Sticky sticky = null; try { diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java index 47051a94..94054a68 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java @@ -118,9 +118,6 @@ public void onPerformSync(Account account, } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); } SyncUtils.SetUIDValidity(account, res.UIDValidity, context); // Notify Listactivity that it's finished, and that it can refresh display @@ -152,9 +149,6 @@ public void onPerformSync(Account account, } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); } if (remoteNotesManaged) isChanged = true; From 1ed7b17bf42047a18124eeda622e8d741da48a59 Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Wed, 9 Nov 2016 19:27:33 +0100 Subject: [PATCH 027/103] Added intent item names to make it easier to understand and enforce proper comunication between activities. --- .../AccountConfigurationActivity.java | 15 +++- .../java/com/Pau/ImapNotes2/Listactivity.java | 49 +++++++----- .../com/Pau/ImapNotes2/NewNoteActivity.java | 5 +- .../Pau/ImapNotes2/NoteDetailActivity.java | 74 +++++++++++-------- .../com/Pau/ImapNotes2/Sync/SyncAdapter.java | 28 +++---- notes.org | 21 ++++-- 6 files changed, 120 insertions(+), 72 deletions(-) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java index 07999f26..b97537aa 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java @@ -60,6 +60,13 @@ public class AccountConfigurationActivity extends AccountAuthenticatorActivity i private static Account myAccount = null; private static AccountManager accountManager; + //region Intent item names and values. + public static final String ACTION = "ACTION"; + public static final String ACCOUNTNAME = "ACCOUNTNAME"; + public static final String EDIT_ACCOUNT = "EDIT_ACCOUNT"; + public static final String CREATE_ACCOUNT = "CREATE_ACCOUNT"; + //endregion + private final OnClickListener clickListenerLogin = new View.OnClickListener() { @Override public void onClick(View v) { @@ -137,11 +144,11 @@ public void onCreate(Bundle savedInstanceState) { Bundle extras = getIntent().getExtras(); if (extras != null) { - if (extras.containsKey("action")) { - action = extras.getString("action"); + if (extras.containsKey(ACTION)) { + action = extras.getString(ACTION); } - if (extras.containsKey("accountname")) { - accountname = extras.getString("accountname"); + if (extras.containsKey(ACCOUNTNAME)) { + accountname = extras.getString(ACCOUNTNAME); } } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java index 92a31f80..d4569f31 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java @@ -64,11 +64,25 @@ public class Listactivity extends Activity implements OnItemSelectedListener, Filterable { private static final int SEE_DETAIL = 2; - private static final int DELETE_BUTTON = 3; + public static final int DELETE_BUTTON = 3; private static final int NEW_BUTTON = 4; private static final int SAVE_BUTTON = 5; private static final int EDIT_BUTTON = 6; + + //region Intent item names + public static final String EDIT_ITEM_NUM_IMAP = "EDIT_ITEM_NUM_IMAP"; + public static final String EDIT_ITEM_TXT = "EDIT_ITEM_TXT"; + public static final String EDIT_ITEM_COLOR = "EDIT_ITEM_COLOR"; + public static final String SAVE_ITEM_COLOR = "SAVE_ITEM_COLOR"; + public static final String SAVE_ITEM = "SAVE_ITEM"; + public static final String DELETE_ITEM_NUM_IMAP = "DELETE_ITEM_NUM_IMAP"; + public static final String ACCOUNTNAME = "ACCOUNTNAME"; + public static final String SYNCINTERVAL = "SYNCINTERVAL"; + public static final String CHANGED = "CHANGED"; + public static final String SYNCED = "SYNCED"; + //endregion + private ArrayList noteList; private NotesListAdapter listToView; private ArrayAdapter spinnerList; @@ -94,8 +108,8 @@ public void onClick(View v) { String mPackage = "com.Pau.ImapNotes2"; String mClass = ".AccountConfigurationActivity"; res.setComponent(new ComponentName(mPackage, mPackage + mClass)); - res.putExtra("action", "EDIT_ACCOUNT"); - res.putExtra("accountname", Listactivity.imapNotes2Account.GetAccountname()); + res.putExtra(AccountConfigurationActivity.ACTION, AccountConfigurationActivity.EDIT_ACCOUNT); + res.putExtra(AccountConfigurationActivity.ACCOUNTNAME, Listactivity.imapNotes2Account.GetAccountname()); startActivity(res); } }; @@ -149,8 +163,8 @@ public void onCreate(Bundle savedInstanceState) { listview.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView parent, View widget, int selectedNote, long rowId) { Intent toDetail = new Intent(widget.getContext(), NoteDetailActivity.class); - toDetail.putExtra("selectedNote", (OneNote) parent.getItemAtPosition(selectedNote)); - toDetail.putExtra("useSticky", Listactivity.imapNotes2Account.GetUsesticky()); + toDetail.putExtra(NoteDetailActivity.selectedNote, (OneNote) parent.getItemAtPosition(selectedNote)); + toDetail.putExtra(NoteDetailActivity.useSticky, Listactivity.imapNotes2Account.GetUsesticky()); startActivityForResult(toDetail, SEE_DETAIL); } }); @@ -188,12 +202,11 @@ protected void onPause() { } private final BroadcastReceiver syncFinishedReceiver = new BroadcastReceiver() { - public void onReceive(Context context, Intent intent) { - String accountname = intent.getStringExtra("ACCOUNTNAME"); - Boolean isChanged = intent.getBooleanExtra("CHANGED", false); - Boolean isSynced = intent.getBooleanExtra("SYNCED", false); - String syncInterval = intent.getStringExtra("SYNCINTERVAL"); + String accountname = intent.getStringExtra(ACCOUNTNAME); + Boolean isChanged = intent.getBooleanExtra(CHANGED, false); + Boolean isSynced = intent.getBooleanExtra(SYNCED, false); + String syncInterval = intent.getStringExtra(SYNCINTERVAL); if (accountname.equals(Listactivity.imapNotes2Account.GetAccountname())) { if (isSynced) { // Display last sync date @@ -281,7 +294,7 @@ public boolean onOptionsItemSelected(MenuItem item) { String mPackage = "com.Pau.ImapNotes2"; String mClass = ".AccountConfigurationActivity"; res.setComponent(new ComponentName(mPackage, mPackage + mClass)); - res.putExtra("action", "CREATE_ACCOUNT"); + res.putExtra(AccountConfigurationActivity.ACTION, AccountConfigurationActivity.CREATE_ACCOUNT); startActivity(res); return true; case R.id.refresh: @@ -289,7 +302,7 @@ public boolean onOptionsItemSelected(MenuItem item) { return true; case R.id.newnote: Intent toNew = new Intent(this, NewNoteActivity.class); - toNew.putExtra("usesSticky", Listactivity.imapNotes2Account.GetUsesticky()); + toNew.putExtra(NewNoteActivity.usesSticky, Listactivity.imapNotes2Account.GetUsesticky()); startActivityForResult(toNew, Listactivity.NEW_BUTTON); return true; case R.id.about: @@ -324,13 +337,13 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Listactivity.DELETE_BUTTON) { // Delete Message asked for // String suid will contain the Message Imap UID to delete - String suid = data.getStringExtra("DELETE_ITEM_NUM_IMAP"); + String suid = data.getStringExtra(DELETE_ITEM_NUM_IMAP); this.UpdateList(suid, null, null, "delete"); } if (resultCode == Listactivity.EDIT_BUTTON) { - String txt = data.getStringExtra("EDIT_ITEM_TXT"); - String suid = data.getStringExtra("EDIT_ITEM_NUM_IMAP"); - Colors color = (Colors) data.getSerializableExtra("EDIT_ITEM_COLOR"); + String txt = data.getStringExtra(EDIT_ITEM_TXT); + String suid = data.getStringExtra(EDIT_ITEM_NUM_IMAP); + Colors color = (Colors) data.getSerializableExtra(EDIT_ITEM_COLOR); //Log.d(TAG,"Received request to delete message:"+suid); //Log.d(TAG,"Received request to replace message with:"+txt); this.UpdateList(suid, txt, color, "update"); @@ -338,9 +351,9 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) { case Listactivity.NEW_BUTTON: // Returning from NewNoteActivity if (resultCode == Listactivity.SAVE_BUTTON) { - String res = data.getStringExtra("SAVE_ITEM"); + String res = data.getStringExtra(SAVE_ITEM); //Log.d(TAG,"Received request to save message:"+res); - Colors color = (Colors) data.getSerializableExtra("SAVE_ITEM_COLOR"); + Colors color = (Colors) data.getSerializableExtra(SAVE_ITEM_COLOR); this.UpdateList(null, res, color, "insert"); } } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NewNoteActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NewNoteActivity.java index a8b0dea7..d298f7bd 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NewNoteActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NewNoteActivity.java @@ -20,6 +20,9 @@ public class NewNoteActivity extends Activity { private static final String TAG = "IN_NewNoteActivity"; private boolean sticky; private Colors color = NONE; + //region Intent item names + public static final String usesSticky = "usesSticky"; + //endregion public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -27,7 +30,7 @@ public void onCreate(Bundle savedInstanceState) { //noinspection ConstantConditions getActionBar().setDisplayHomeAsUpEnabled(true); this.ResetColors(); - this.sticky = (boolean) getIntent().getExtras().get("usesSticky"); + this.sticky = (boolean) getIntent().getExtras().get(usesSticky); } private void ResetColors() { diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java index ea694dfe..30f26c7b 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java @@ -32,12 +32,14 @@ import javax.mail.Part; import javax.mail.internet.ContentType; -import static com.Pau.ImapNotes2.NoteDetailActivity.Colors.BLUE; -import static com.Pau.ImapNotes2.NoteDetailActivity.Colors.NONE; +import com.Pau.ImapNotes2.Listactivity; +import com.Pau.ImapNotes2.NoteDetailActivity.Colors; + + public class NoteDetailActivity extends Activity { - private static final int DELETE_BUTTON = 3; + //private static final int DELETE_BUTTON = 3; private static final int EDIT_BUTTON = 6; private boolean usesticky; private Colors color; @@ -46,6 +48,12 @@ public class NoteDetailActivity extends Activity { private final static int ROOT_AND_NEW = 3; private static final String TAG = "IN_NoteDetailActivity"; + //region Intent item names + public static final String useSticky = "useSticky"; + public static final String selectedNote = "selectedNote"; + //endregion + + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.note_detail); @@ -57,8 +65,8 @@ public void onCreate(Bundle savedInstanceState) { ); Bundle extras = getIntent().getExtras(); - HashMap hm = (HashMap) extras.get("selectedNote"); - this.usesticky = (boolean) extras.get("useSticky"); + HashMap hm = (HashMap) extras.get(selectedNote); + usesticky = (boolean) extras.get(useSticky); assert hm != null; suid = hm.get("uid").toString(); String rootDir = (ImapNotes2k.getAppContext()).getFilesDir() + "/" + @@ -91,41 +99,47 @@ public void afterTextChanged(Editable s) { } }); - this.ResetColors(); + ResetColors(); //invalidateOptionsMenu(); } + // TODO: delete this? public void onClick(View v) { Boolean isClicked = true; } - // TODO: Find out what this is for. + // realColor is misnamed. It is the ID of the radio button widget that chooses the background + // colour. + // We have three distinct representations for each colour for different purposes, they should + // be collected into properties of the enum. Then we could get rid of the switch. private void ResetColors() { - findViewById(R.id.bodyView).setBackgroundColor(Color.TRANSPARENT); - ((EditText) findViewById(R.id.bodyView)).setTextColor(Color.BLACK); - Colors currentColor = color; - switch (currentColor) { + EditText bodyView = (EditText) findViewById(R.id.bodyView); + bodyView.setBackgroundColor(Color.TRANSPARENT); + bodyView.setTextColor(Color.BLACK); + switch (color) { case BLUE: (findViewById(R.id.scrollView)).setBackgroundColor(0xFFA6CAFD); - this.realColor = R.id.blue; + realColor = R.id.blue; break; case WHITE: (findViewById(R.id.scrollView)).setBackgroundColor(0xFFFFFFFF); - this.realColor = R.id.white; + realColor = R.id.white; break; case YELLOW: (findViewById(R.id.scrollView)).setBackgroundColor(0xFFFFFFCC); - this.realColor = R.id.yellow; + realColor = R.id.yellow; break; case PINK: (findViewById(R.id.scrollView)).setBackgroundColor(0xFFFFCCCC); - this.realColor = R.id.pink; + realColor = R.id.pink; break; case GREEN: (findViewById(R.id.scrollView)).setBackgroundColor(0xFFCCFFCC); - this.realColor = R.id.green; + realColor = R.id.green; break; default: + // Default should not be necessary because we should be able to ensure that it + // never happens. We should instead throw an exception. (findViewById(R.id.scrollView)).setBackgroundColor(Color.TRANSPARENT); } invalidateOptionsMenu(); @@ -142,7 +156,7 @@ public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); //depending on your conditions, either enable/disable item.setVisible(usesticky); - menu.findItem(this.realColor).setChecked(true); + menu.findItem(realColor).setChecked(true); return true; } @@ -150,9 +164,9 @@ public boolean onOptionsItemSelected(MenuItem item) { Intent intent = new Intent(); switch (item.getItemId()) { case R.id.delete: - //Log.d(TAG,"We ask to delete Message #"+this.currentNote.get("number")); - intent.putExtra("DELETE_ITEM_NUM_IMAP", suid); - setResult(NoteDetailActivity.DELETE_BUTTON, intent); + //Log.d(TAG,"We ask to delete Message #"+currentNote.get("number")); + intent.putExtra(Listactivity.DELETE_ITEM_NUM_IMAP, suid); + setResult(Listactivity.DELETE_BUTTON, intent); finish();//finishing activity return true; case R.id.save: @@ -163,27 +177,27 @@ public boolean onOptionsItemSelected(MenuItem item) { return true; case R.id.blue: item.setChecked(true); - this.color = BLUE; + color = Colors.BLUE; (findViewById(R.id.scrollView)).setBackgroundColor(0xFFA6CAFD); return true; case R.id.white: item.setChecked(true); - this.color = Colors.WHITE; + color = Colors.WHITE; (findViewById(R.id.scrollView)).setBackgroundColor(0xFFFFFFFF); return true; case R.id.yellow: item.setChecked(true); - this.color = Colors.YELLOW; + color = Colors.YELLOW; (findViewById(R.id.scrollView)).setBackgroundColor(0xFFFFFFCC); return true; case R.id.pink: item.setChecked(true); - this.color = Colors.PINK; + color = Colors.PINK; (findViewById(R.id.scrollView)).setBackgroundColor(0xFFFFCCCC); return true; case R.id.green: item.setChecked(true); - this.color = Colors.GREEN; + color = Colors.GREEN; (findViewById(R.id.scrollView)).setBackgroundColor(0xFFCCFFCC); return true; default: @@ -194,17 +208,19 @@ public boolean onOptionsItemSelected(MenuItem item) { private void Save() { Log.d(TAG, "Save"); Intent intent = new Intent(); - intent.putExtra("EDIT_ITEM_NUM_IMAP", suid); - intent.putExtra("EDIT_ITEM_TXT", + intent.putExtra(Listactivity.EDIT_ITEM_NUM_IMAP, suid); + intent.putExtra(Listactivity.EDIT_ITEM_TXT, Html.toHtml(((EditText) findViewById(R.id.bodyView)).getText())); if (!usesticky) { - this.color = Colors.NONE; + color = Colors.NONE; } - intent.putExtra("EDIT_ITEM_COLOR", this.color); + intent.putExtra(Listactivity.EDIT_ITEM_COLOR, color); setResult(NoteDetailActivity.EDIT_BUTTON, intent); finish();//finishing activity } + + // TODO: use R.id.blue etc. public enum Colors { BLUE, WHITE, diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java index 94054a68..08ec636c 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java @@ -24,6 +24,8 @@ import com.Pau.ImapNotes2.Miscs.ImapNotes2Result; import com.sun.mail.imap.AppendUID; +import com.Pau.ImapNotes2.Listactivity; + import static com.Pau.ImapNotes2.Miscs.Imaper.ResultCodeSuccess; /// A SyncAdapter provides methods to be called by the Android @@ -90,12 +92,12 @@ public void onPerformSync(Account account, // Notify Listactivity that it's finished, but it can't // refresh display Intent i = new Intent(SyncService.SYNC_FINISHED); - i.putExtra("ACCOUNTNAME", account.name); + i.putExtra(Listactivity.ACCOUNTNAME, account.name); isChanged = false; isSynced = false; - i.putExtra("CHANGED", false); - i.putExtra("SYNCED", false); - i.putExtra("SYNCINTERVAL", syncinterval); + i.putExtra(Listactivity.CHANGED, false); + i.putExtra(Listactivity.SYNCED, false); + i.putExtra(Listactivity.SYNCINTERVAL, syncinterval); context.sendBroadcast(i); return; } @@ -122,12 +124,10 @@ public void onPerformSync(Account account, SyncUtils.SetUIDValidity(account, res.UIDValidity, context); // Notify Listactivity that it's finished, and that it can refresh display Intent i = new Intent(SyncService.SYNC_FINISHED); - i.putExtra("ACCOUNTNAME", account.name); - isChanged = true; - isSynced = true; - i.putExtra("CHANGED", true); - i.putExtra("SYNCED", true); - i.putExtra("SYNCINTERVAL", syncinterval); + i.putExtra(Listactivity.ACCOUNTNAME, account.name); + i.putExtra(Listactivity.CHANGED, true); + i.putExtra(Listactivity.SYNCED, true); + i.putExtra(Listactivity.SYNCINTERVAL, syncinterval); context.sendBroadcast(i); return; } @@ -159,11 +159,11 @@ public void onPerformSync(Account account, //Log.d(TAG, "Network synchronization complete of account: "+account.name); // Notify Listactivity that it's finished, and that it can refresh display Intent i = new Intent(SyncService.SYNC_FINISHED); - i.putExtra("ACCOUNTNAME", account.name); - i.putExtra("CHANGED", isChanged); + i.putExtra(Listactivity.ACCOUNTNAME, account.name); + i.putExtra(Listactivity.CHANGED, isChanged); isSynced = true; - i.putExtra("SYNCED", isSynced); - i.putExtra("SYNCINTERVAL", syncinterval); + i.putExtra(Listactivity.SYNCED, isSynced); + i.putExtra(Listactivity.SYNCINTERVAL, syncinterval); context.sendBroadcast(i); } diff --git a/notes.org b/notes.org index b6029f5a..40ec6436 100644 --- a/notes.org +++ b/notes.org @@ -17,6 +17,7 @@ First question is how is the note saved in the first place. Then can we do it automatically and then can we start the sync early? + * Directory synchronization Use the already implemented accounts. @@ -80,6 +81,7 @@ This is used to store metadata about the notes. The notes themselves are stored as files in a sub-directory named after the account to which they belong. The file names are the IMAP UIDs. + * Code analysis Run Android lint to discover opportunities to get rid of warnings, @@ -90,10 +92,17 @@ convert fields to local variables, etc. Ran whole project default profile to get an overview and then picked one analysis at a time to be fixed, tested and committed. -| Group | Analysis | Synopsis | Notes | -|---------------+----------------------------------+--------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------| -| | Field can be local | | Some of these seem to be work in progress so have been left unfixed. | -| | Parameter can be local | | No suspicious code found. | -| Probable bugs | Constant conditions & exceptions | Method invocation 'setDisplayHomeAsUpEnabled' at line 106 may produce 'java.lang.NullPointerException' | Suppressed because result is not used. | -| | | ConstantConditions | Some possible null pointers remain. | +| Group | Analysis | Synopsis | Notes | +|------------------+----------------------------------+--------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------| +| | Field can be local | | Some of these seem to be work in progress so have been left unfixed. | +| | Parameter can be local | | No suspicious code found. | +| Probable bugs | Constant conditions & exceptions | Method invocation 'setDisplayHomeAsUpEnabled' at line 106 may produce 'java.lang.NullPointerException' | Suppressed because result is not used. | +| | ConstantConditions | | Some possible null pointers remain. | +| Data flow issues | Missing return statement | Not all execution paths return a value | Very odd the, the file in question is build.gradle. What should I do? | +| | | | | + + +* Intents +The names of the intent items should be defined as constants in the +receiving class. From c7fdc348f3588558160b9947b8549db97a7d0e90 Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Wed, 9 Nov 2016 21:09:42 +0100 Subject: [PATCH 028/103] Put all the sticky colour related values together in the Colors enum. --- .../java/com/Pau/ImapNotes2/Miscs/Sticky.java | 5 +- .../com/Pau/ImapNotes2/NewNoteActivity.java | 8 +-- .../Pau/ImapNotes2/NoteDetailActivity.java | 61 ++++++++++--------- .../com/Pau/ImapNotes2/Sync/SyncUtils.java | 23 +++---- 4 files changed, 48 insertions(+), 49 deletions(-) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Sticky.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Sticky.java index 6e2be475..df47e824 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Sticky.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Sticky.java @@ -4,6 +4,7 @@ public class Sticky { + // TODO: Why are these fields static when the class is not? private static String text; private static String position; private static Colors color; @@ -14,7 +15,9 @@ public Sticky() { Sticky.color = Colors.YELLOW; } - public Sticky(String text, String position, + // TODO: why is a constructor allowed to modify static members? + public Sticky(String text, + String position, Colors color) { Sticky.text = text; Sticky.position = position; diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NewNoteActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NewNoteActivity.java index d298f7bd..6374342b 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NewNoteActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NewNoteActivity.java @@ -10,16 +10,14 @@ import android.view.MenuItem; import android.widget.EditText; -import static com.Pau.ImapNotes2.NoteDetailActivity.*; -import static com.Pau.ImapNotes2.NoteDetailActivity.Colors.NONE; -import static com.Pau.ImapNotes2.NoteDetailActivity.Colors.YELLOW; +import static com.Pau.ImapNotes2.NoteDetailActivity.Colors; public class NewNoteActivity extends Activity { private static final int SAVE_BUTTON = 5; private static final String TAG = "IN_NewNoteActivity"; private boolean sticky; - private Colors color = NONE; + private Colors color = Colors.NONE; //region Intent item names public static final String usesSticky = "usesSticky"; //endregion @@ -49,7 +47,7 @@ public boolean onOptionsItemSelected(MenuItem item) { Intent intent = new Intent(); intent.putExtra("SAVE_ITEM", Html.toHtml(((EditText) findViewById(R.id.editNote)).getText())); if (this.sticky) { - this.color = YELLOW; + this.color = Colors.YELLOW; } intent.putExtra("SAVE_ITEM_COLOR", this.color); setResult(SAVE_BUTTON, intent); diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java index 30f26c7b..d42452c7 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java @@ -32,9 +32,6 @@ import javax.mail.Part; import javax.mail.internet.ContentType; -import com.Pau.ImapNotes2.Listactivity; -import com.Pau.ImapNotes2.NoteDetailActivity.Colors; - public class NoteDetailActivity extends Activity { @@ -162,7 +159,8 @@ public boolean onPrepareOptionsMenu(Menu menu) { public boolean onOptionsItemSelected(MenuItem item) { Intent intent = new Intent(); - switch (item.getItemId()) { + int itemId = item.getItemId(); + switch (itemId) { case R.id.delete: //Log.d(TAG,"We ask to delete Message #"+currentNote.get("number")); intent.putExtra(Listactivity.DELETE_ITEM_NUM_IMAP, suid); @@ -176,29 +174,13 @@ public boolean onOptionsItemSelected(MenuItem item) { NavUtils.navigateUpFromSameTask(this); return true; case R.id.blue: - item.setChecked(true); - color = Colors.BLUE; - (findViewById(R.id.scrollView)).setBackgroundColor(0xFFA6CAFD); - return true; case R.id.white: - item.setChecked(true); - color = Colors.WHITE; - (findViewById(R.id.scrollView)).setBackgroundColor(0xFFFFFFFF); - return true; case R.id.yellow: - item.setChecked(true); - color = Colors.YELLOW; - (findViewById(R.id.scrollView)).setBackgroundColor(0xFFFFFFCC); - return true; case R.id.pink: - item.setChecked(true); - color = Colors.PINK; - (findViewById(R.id.scrollView)).setBackgroundColor(0xFFFFCCCC); - return true; case R.id.green: item.setChecked(true); - color = Colors.GREEN; - (findViewById(R.id.scrollView)).setBackgroundColor(0xFFCCFFCC); + color = Colors.fromId(itemId); + (findViewById(R.id.scrollView)).setBackgroundColor(color.colorCode); return true; default: return super.onOptionsItemSelected(item); @@ -220,14 +202,35 @@ private void Save() { } - // TODO: use R.id.blue etc. + // List the colours together with the ids of the option widgets used to select them and the + // RGB values used as the actual colours. Doing this means that we do not need so much code + // in switch statements, etc. public enum Colors { - BLUE, - WHITE, - YELLOW, - PINK, - GREEN, - NONE + BLUE(R.id.blue, 0xFFA6CAFD), + WHITE(R.id.white, 0xFFFFFFFF), + YELLOW(R.id.yellow, 0xFFFFFFCC), + PINK(R.id.pink, 0xFFFFCCCC), + GREEN(R.id.green, 0xFFCCFFCC), + // Is NONE ever used? + NONE(0, 0); + + public final int id; + public final int colorCode; + + private Colors(int id, + int colorCode) { + this.id = id; + this.colorCode = colorCode; + } + + public static Colors fromId(int id) { + + for (Colors color : Colors.values()) { + if (color.id == id) + return color; + } + throw new IllegalArgumentException("id not found in Colors: " + Integer.toString(id)); + } } private Sticky GetInfoFromMessage(Message message) { diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java index 3d4e563a..ad55547f 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java @@ -41,10 +41,7 @@ import javax.mail.UIDFolder; import javax.mail.internet.MimeMessage; -import static com.Pau.ImapNotes2.Miscs.Imaper.ResultCodeException; -import static com.Pau.ImapNotes2.Miscs.Imaper.ResultCodeSuccess; import static com.Pau.ImapNotes2.NoteDetailActivity.Colors; -import static com.Pau.ImapNotes2.NoteDetailActivity.Colors.NONE; public class SyncUtils { @@ -148,13 +145,13 @@ static ImapNotes2Result ConnectToRemote(String username, notesFolder = store.getFolder(sfolder); res.UIDValidity = ((IMAPFolder) notesFolder).getUIDValidity(); res.errorMessage = ""; - res.returnCode = ResultCodeSuccess; + res.returnCode = Imaper.ResultCodeSuccess; res.notesFolder = notesFolder; return res; } catch (Exception e) { Log.d(TAG, e.getMessage()); res.errorMessage = e.getMessage(); - res.returnCode = ResultCodeException; + res.returnCode = Imaper.ResultCodeException; return res; } @@ -196,27 +193,25 @@ public static void GetNotes(Account account, private static final Pattern patternText = Pattern.compile("TEXT:(.*?)(END:|POSITION:)", Pattern.DOTALL); public static Sticky ReadStickynote(String stringres) { - Colors color = NONE; - String position = ""; - String text = ""; - //Pattern p = null; - Matcher matcherColor = patternColor.matcher(stringres); + Colors color = Colors.NONE; if (matcherColor.find()) { String colorName = matcherColor.group(1); - Log.d(TAG, " Color: " + colorName + " " + (colorName == null)); color = ((colorName == null) || colorName.equals("null")) ? Colors.NONE : Colors.valueOf(colorName); + } else { + color = Colors.NONE; } Matcher matcherPosition = patternPosition.matcher(stringres); - if (matcherPosition.find()) { - position = matcherPosition.group(1); - } + String position = matcherPosition.find() ? + matcherPosition.group(1) : + ""; Matcher matcherText = patternText.matcher(stringres); + String text = ""; if (matcherText.find()) { text = matcherText.group(1); // Kerio Connect puts CR+LF+space every 78 characters from line 2 From 3f50effebc017ae34efce131cb3472780f4dcf71 Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Thu, 10 Nov 2016 20:31:44 +0100 Subject: [PATCH 029/103] Removed unused constructor from Sticky. --- .../AccountConfigurationActivity.java | 8 +++-- .../java/com/Pau/ImapNotes2/Miscs/Sticky.java | 24 +++++-------- .../Pau/ImapNotes2/NoteDetailActivity.java | 36 +++---------------- 3 files changed, 18 insertions(+), 50 deletions(-) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java index b97537aa..995199e3 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java @@ -181,7 +181,7 @@ public void onCreate(Bundle savedInstanceState) { this.action = "CREATE_ACCOUNT"; } - if (this.action.equals("EDIT_ACCOUNT")) { + if (this.action.equals(EDIT_ACCOUNT)) { // Here we have to edit an existing account this.accountnameTextView.setText(this.accountname); this.usernameTextView.setText(GetConfigValue(ConfigurationFieldNames.UserName)); @@ -286,7 +286,7 @@ protected Boolean doInBackground(Void... none) { AccountManager am = AccountManager.get(accountConfigurationActivity); accountConfigurationActivity.setResult(AccountConfigurationActivity.TO_REFRESH); Bundle result; - if (this.action.equals("EDIT_ACCOUNT")) { + if (this.action.equals(EDIT_ACCOUNT)) { result = new Bundle(); result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name); result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type); @@ -361,7 +361,9 @@ public void onFinish() { tag.show(); } }.start(); - if (this.action.equals("EDIT_ACCOUNT")) finish(); + if (this.action.equals(EDIT_ACCOUNT)) { + finish(); + } } } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Sticky.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Sticky.java index df47e824..b4c4030d 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Sticky.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Sticky.java @@ -4,26 +4,18 @@ public class Sticky { - // TODO: Why are these fields static when the class is not? - private static String text; - private static String position; - private static Colors color; - - public Sticky() { - Sticky.text = ""; - Sticky.position = "0 0 0 0"; - Sticky.color = Colors.YELLOW; - } + public final String text; + public final String position; + public final Colors color; - // TODO: why is a constructor allowed to modify static members? public Sticky(String text, String position, Colors color) { - Sticky.text = text; - Sticky.position = position; - Sticky.color = color; + this.text = text; + this.position = position; + this.color = color; } - +/* public String GetPosition() { return Sticky.position; } @@ -46,5 +38,5 @@ public void SetPosition(String position) { public void SetColor(Colors color) { Sticky.color = color; - } + }*/ } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java index d42452c7..d36b5e18 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java @@ -70,9 +70,9 @@ public void onCreate(Bundle savedInstanceState) { Listactivity.imapNotes2Account.GetAccountname(); Message message = SyncUtils.ReadMailFromFile(suid, ROOT_AND_NEW, true, rootDir); Sticky sticky = GetInfoFromMessage(message); - String stringres = sticky.GetText(); - String position = sticky.GetPosition(); - color = sticky.GetColor(); + String stringres = sticky.text; + String position = sticky.position; + color = sticky.color; Spanned plainText = Html.fromHtml(stringres); EditText editText = ((EditText) findViewById(R.id.bodyView)); editText.setText(plainText); @@ -107,38 +107,12 @@ public void onClick(View v) { // realColor is misnamed. It is the ID of the radio button widget that chooses the background // colour. - // We have three distinct representations for each colour for different purposes, they should - // be collected into properties of the enum. Then we could get rid of the switch. private void ResetColors() { EditText bodyView = (EditText) findViewById(R.id.bodyView); bodyView.setBackgroundColor(Color.TRANSPARENT); bodyView.setTextColor(Color.BLACK); - switch (color) { - case BLUE: - (findViewById(R.id.scrollView)).setBackgroundColor(0xFFA6CAFD); - realColor = R.id.blue; - break; - case WHITE: - (findViewById(R.id.scrollView)).setBackgroundColor(0xFFFFFFFF); - realColor = R.id.white; - break; - case YELLOW: - (findViewById(R.id.scrollView)).setBackgroundColor(0xFFFFFFCC); - realColor = R.id.yellow; - break; - case PINK: - (findViewById(R.id.scrollView)).setBackgroundColor(0xFFFFCCCC); - realColor = R.id.pink; - break; - case GREEN: - (findViewById(R.id.scrollView)).setBackgroundColor(0xFFCCFFCC); - realColor = R.id.green; - break; - default: - // Default should not be necessary because we should be able to ensure that it - // never happens. We should instead throw an exception. - (findViewById(R.id.scrollView)).setBackgroundColor(Color.TRANSPARENT); - } + (findViewById(R.id.scrollView)).setBackgroundColor(color.colorCode); + realColor = color.id; invalidateOptionsMenu(); } From 8f1de3a37d71e117ef40506ae2a7195edb749c6d Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Fri, 11 Nov 2016 20:04:58 +0100 Subject: [PATCH 030/103] Added comments to manifest to ask why we have met-data elements. --- ImapNote2/src/main/AndroidManifest.xml | 6 + .../AccountConfigurationActivity.java | 141 ++++++++++-------- .../java/com/Pau/ImapNotes2/Listactivity.java | 11 +- 3 files changed, 88 insertions(+), 70 deletions(-) diff --git a/ImapNote2/src/main/AndroidManifest.xml b/ImapNote2/src/main/AndroidManifest.xml index 4b47dad2..0cc70a06 100644 --- a/ImapNote2/src/main/AndroidManifest.xml +++ b/ImapNote2/src/main/AndroidManifest.xml @@ -34,6 +34,7 @@ + @@ -43,6 +44,7 @@ android:name=".AccountConfigurationActivity" android:exported="true" android:parentActivityName="com.Pau.ImapNotes2.Listactivity"> + @@ -51,6 +53,7 @@ + @@ -59,6 +62,7 @@ + @@ -71,6 +75,7 @@ + @@ -87,6 +92,7 @@ + diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java index 995199e3..24340764 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java @@ -33,6 +33,7 @@ import java.util.List; +import static com.Pau.ImapNotes2.AccountConfigurationActivity.Actions.EDIT_ACCOUNT; import static com.Pau.ImapNotes2.Miscs.Imaper.ResultCodeSuccess; public class AccountConfigurationActivity extends AccountAuthenticatorActivity implements OnItemSelectedListener { @@ -54,19 +55,26 @@ public class AccountConfigurationActivity extends AccountAuthenticatorActivity i private ImapNotes2Account imapNotes2Account; private Security security; //private int security_i; - private String action; + private Actions action; private String accountname; - private ConfigurationFile settings; + private ConfigurationFile settings = new ConfigurationFile(); + private static Account myAccount = null; private static AccountManager accountManager; //region Intent item names and values. public static final String ACTION = "ACTION"; public static final String ACCOUNTNAME = "ACCOUNTNAME"; - public static final String EDIT_ACCOUNT = "EDIT_ACCOUNT"; - public static final String CREATE_ACCOUNT = "CREATE_ACCOUNT"; +// public static final String EDIT_ACCOUNT = "EDIT_ACCOUNT"; +// public static final String CREATE_ACCOUNT = "CREATE_ACCOUNT"; //endregion + + enum Actions { + CREATE_ACCOUNT, + EDIT_ACCOUNT + } + private final OnClickListener clickListenerLogin = new View.OnClickListener() { @Override public void onClick(View v) { @@ -112,14 +120,14 @@ public void onCreate(Bundle savedInstanceState) { setContentView(R.layout.account_selection); //noinspection ConstantConditions getActionBar().setDisplayHomeAsUpEnabled(true); - this.accountnameTextView = (TextView) (findViewById(R.id.accountnameEdit)); - this.usernameTextView = (TextView) findViewById(R.id.usernameEdit); - this.passwordTextView = (TextView) findViewById(R.id.passwordEdit); - this.serverTextView = (TextView) findViewById(R.id.serverEdit); - this.portnumTextView = (TextView) findViewById(R.id.portnumEdit); - this.syncintervalTextView = (TextView) findViewById(R.id.syncintervalEdit); - this.folderTextView = (TextView) findViewById(R.id.folderEdit); - this.stickyCheckBox = (CheckBox) findViewById(R.id.stickyCheckBox); + accountnameTextView = (TextView) (findViewById(R.id.accountnameEdit)); + usernameTextView = (TextView) findViewById(R.id.usernameEdit); + passwordTextView = (TextView) findViewById(R.id.passwordEdit); + serverTextView = (TextView) findViewById(R.id.serverEdit); + portnumTextView = (TextView) findViewById(R.id.portnumEdit); + syncintervalTextView = (TextView) findViewById(R.id.syncintervalEdit); + folderTextView = (TextView) findViewById(R.id.folderEdit); + stickyCheckBox = (CheckBox) findViewById(R.id.stickyCheckBox); securitySpinner = (Spinner) findViewById(R.id.securitySpinner); /*List list = new ArrayList(); @@ -139,33 +147,35 @@ public void onCreate(Bundle savedInstanceState) { securitySpinner.setOnItemSelectedListener(this); imapNotes2Account = new ImapNotes2Account(); - this.imapFolder = ((ImapNotes2k) getApplicationContext()).GetImaper(); - this.settings = new ConfigurationFile(); + imapFolder = ((ImapNotes2k) getApplicationContext()).GetImaper(); + //settings = new ConfigurationFile(); Bundle extras = getIntent().getExtras(); + // TODO: find out if extras can be null. if (extras != null) { if (extras.containsKey(ACTION)) { - action = extras.getString(ACTION); + action = (Actions) (extras.getSerializable(ACTION)); } if (extras.containsKey(ACCOUNTNAME)) { accountname = extras.getString(ACCOUNTNAME); } } - if (this.settings != null) { - this.accountnameTextView.setText(this.settings.GetAccountname()); - this.usernameTextView.setText(this.settings.GetUsername()); - this.passwordTextView.setText(this.settings.GetPassword()); - this.serverTextView.setText(this.settings.GetServer()); - this.portnumTextView.setText(this.settings.GetPortnum()); - this.security = this.settings.GetSecurity(); - // Can never be null. if (this.security == null) this.security = "0"; - int security_i = this.security.ordinal(); - this.securitySpinner.setSelection(security_i); - this.stickyCheckBox.setChecked(this.settings.GetUsesticky()); - this.syncintervalTextView.setText("15"); - this.folderTextView.setText(this.settings.GetFoldername()); - } + // Settings can never be null so there is no need to guard it + //if (settings != null) { + accountnameTextView.setText(settings.GetAccountname()); + usernameTextView.setText(settings.GetUsername()); + passwordTextView.setText(settings.GetPassword()); + serverTextView.setText(settings.GetServer()); + portnumTextView.setText(settings.GetPortnum()); + security = settings.GetSecurity(); + // Can never be null. if (security == null) security = "0"; + int security_i = security.ordinal(); + securitySpinner.setSelection(security_i); + stickyCheckBox.setChecked(settings.GetUsesticky()); + syncintervalTextView.setText("15"); + folderTextView.setText(settings.GetFoldername()); + //} LinearLayout layout = (LinearLayout) findViewById(R.id.bttonsLayout); accountManager = AccountManager.get(getApplicationContext()); @@ -177,24 +187,25 @@ public void onCreate(Bundle savedInstanceState) { } } - if ((this.action == null) || (myAccount == null)) { - this.action = "CREATE_ACCOUNT"; + // action can never be null + if (myAccount == null) { + action = Actions.CREATE_ACCOUNT; } - if (this.action.equals(EDIT_ACCOUNT)) { + if (action == EDIT_ACCOUNT) { // Here we have to edit an existing account - this.accountnameTextView.setText(this.accountname); - this.usernameTextView.setText(GetConfigValue(ConfigurationFieldNames.UserName)); - this.passwordTextView.setText(accountManager.getPassword(myAccount)); - this.serverTextView.setText(GetConfigValue(ConfigurationFieldNames.Server)); - this.portnumTextView.setText(GetConfigValue(ConfigurationFieldNames.PortNumber)); - this.security = Security.from(GetConfigValue(ConfigurationFieldNames.Security)); - this.stickyCheckBox.setChecked(Boolean.parseBoolean(GetConfigValue(ConfigurationFieldNames.UseSticky))); - this.syncintervalTextView.setText(GetConfigValue(ConfigurationFieldNames.SyncInterval)); - this.folderTextView.setText(GetConfigValue(ConfigurationFieldNames.ImapFolder)); - //if (this.security == null) this.security = "0"; - int security_i = security.ordinal(); - this.securitySpinner.setSelection(security_i); + accountnameTextView.setText(accountname); + usernameTextView.setText(GetConfigValue(ConfigurationFieldNames.UserName)); + passwordTextView.setText(accountManager.getPassword(myAccount)); + serverTextView.setText(GetConfigValue(ConfigurationFieldNames.Server)); + portnumTextView.setText(GetConfigValue(ConfigurationFieldNames.PortNumber)); + security = Security.from(GetConfigValue(ConfigurationFieldNames.Security)); + stickyCheckBox.setChecked(Boolean.parseBoolean(GetConfigValue(ConfigurationFieldNames.UseSticky))); + syncintervalTextView.setText(GetConfigValue(ConfigurationFieldNames.SyncInterval)); + folderTextView.setText(GetConfigValue(ConfigurationFieldNames.ImapFolder)); + //if (security == null) security = "0"; + security_i = security.ordinal(); + securitySpinner.setSelection(security_i); Button buttonEdit = new Button(this); buttonEdit.setText("Save"); buttonEdit.setOnClickListener(clickListenerEdit); @@ -251,13 +262,13 @@ class LoginThread extends AsyncTask { private final AccountConfigurationActivity accountConfigurationActivity; private ImapNotes2Result res = new ImapNotes2Result(); - private final String action; + private final Actions action; public LoginThread(Imaper mapFolder, ImapNotes2Account imapNotes2Account, ProgressDialog loadingDialog, AccountConfigurationActivity accountConfigurationActivity, - String action, + Actions action, long SYNC_FREQUENCY) { this.imapNotes2Account = imapNotes2Account; this.progressDialog = loadingDialog; @@ -268,10 +279,10 @@ public LoginThread(Imaper mapFolder, } protected Boolean doInBackground(Void... none) { - //this.action = (String) stuffs[ParamAction]; + //action = (String) stuffs[ParamAction]; try { //ImapNotes2Account imapNotes2Account= ((ImapNotes2Account) stuffs[ParamImapNotes2Account]); - this.res = imapFolder.ConnectToProvider( + res = imapFolder.ConnectToProvider( imapNotes2Account.GetUsername(), imapNotes2Account.GetPassword(), imapNotes2Account.GetServer(), @@ -280,13 +291,13 @@ protected Boolean doInBackground(Void... none) { imapNotes2Account.GetUsesticky(), imapNotes2Account.GetFoldername()); //accountConfigurationActivity = acountConfigurationActivity; - if (this.res.returnCode == ResultCodeSuccess) { + if (res.returnCode == ResultCodeSuccess) { Account account = new Account(imapNotes2Account.GetAccountname(), "com.Pau.ImapNotes2"); //long SYNC_FREQUENCY = (long) stuffs[ParamSyncPeriod]; AccountManager am = AccountManager.get(accountConfigurationActivity); accountConfigurationActivity.setResult(AccountConfigurationActivity.TO_REFRESH); Bundle result; - if (this.action.equals(EDIT_ACCOUNT)) { + if (action == EDIT_ACCOUNT) { result = new Bundle(); result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name); result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type); @@ -302,7 +313,7 @@ protected Boolean doInBackground(Void... none) { ContentResolver.setIsSyncable(account, AUTHORITY, 1); ContentResolver.setSyncAutomatically(account, AUTHORITY, true); ContentResolver.addPeriodicSync(account, AUTHORITY, new Bundle(), SYNC_FREQUENCY); - this.res.errorMessage = "Account has been modified"; + res.errorMessage = "Account has been modified"; return true; } else { if (am.addAccountExplicitly(account, imapNotes2Account.GetPassword(), null)) { @@ -321,10 +332,10 @@ protected Boolean doInBackground(Void... none) { ContentResolver.setIsSyncable(account, AUTHORITY, 1); ContentResolver.setSyncAutomatically(account, AUTHORITY, true); ContentResolver.addPeriodicSync(account, AUTHORITY, new Bundle(), SYNC_FREQUENCY); - this.res.errorMessage = "Account has been added"; + res.errorMessage = "Account has been added"; return true; } else { - this.res.errorMessage = "Account already exists or is null"; + res.errorMessage = "Account already exists or is null"; return false; } } @@ -340,17 +351,17 @@ protected Boolean doInBackground(Void... none) { protected void onPostExecute(Boolean result) { if (result) { accountConfigurationActivity.settings.Clear(); - this.accountConfigurationActivity.accountnameTextView.setText(""); - this.accountConfigurationActivity.usernameTextView.setText(""); - this.accountConfigurationActivity.passwordTextView.setText(""); - this.accountConfigurationActivity.serverTextView.setText(""); - this.accountConfigurationActivity.portnumTextView.setText(""); - this.accountConfigurationActivity.syncintervalTextView.setText("15"); - this.accountConfigurationActivity.securitySpinner.setSelection(0); - this.accountConfigurationActivity.folderTextView.setText(""); - this.accountConfigurationActivity.stickyCheckBox.setChecked(false); + accountConfigurationActivity.accountnameTextView.setText(""); + accountConfigurationActivity.usernameTextView.setText(""); + accountConfigurationActivity.passwordTextView.setText(""); + accountConfigurationActivity.serverTextView.setText(""); + accountConfigurationActivity.portnumTextView.setText(""); + accountConfigurationActivity.syncintervalTextView.setText("15"); + accountConfigurationActivity.securitySpinner.setSelection(0); + accountConfigurationActivity.folderTextView.setText(""); + accountConfigurationActivity.stickyCheckBox.setChecked(false); } - final Toast tag = Toast.makeText(getApplicationContext(), this.res.errorMessage, Toast.LENGTH_LONG); + final Toast tag = Toast.makeText(getApplicationContext(), res.errorMessage, Toast.LENGTH_LONG); tag.show(); new CountDownTimer(5000, 1000) { public void onTick(long millisUntilFinished) { @@ -361,7 +372,7 @@ public void onFinish() { tag.show(); } }.start(); - if (this.action.equals(EDIT_ACCOUNT)) { + if (action == EDIT_ACCOUNT) { finish(); } } @@ -384,7 +395,7 @@ public boolean onOptionsItemSelected(MenuItem item) { @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { security = Security.from(position); - this.portnumTextView.setText(security.defaultPort); + portnumTextView.setText(security.defaultPort); } @Override diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java index d4569f31..0a680a52 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java @@ -59,6 +59,7 @@ import android.widget.TextView; import android.widget.Toast; +import static com.Pau.ImapNotes2.AccountConfigurationActivity.*; import static com.Pau.ImapNotes2.NoteDetailActivity.*; @@ -108,7 +109,7 @@ public void onClick(View v) { String mPackage = "com.Pau.ImapNotes2"; String mClass = ".AccountConfigurationActivity"; res.setComponent(new ComponentName(mPackage, mPackage + mClass)); - res.putExtra(AccountConfigurationActivity.ACTION, AccountConfigurationActivity.EDIT_ACCOUNT); + res.putExtra(ACTION, Actions.EDIT_ACCOUNT); res.putExtra(AccountConfigurationActivity.ACCOUNTNAME, Listactivity.imapNotes2Account.GetAccountname()); startActivity(res); } @@ -210,8 +211,8 @@ public void onReceive(Context context, Intent intent) { if (accountname.equals(Listactivity.imapNotes2Account.GetAccountname())) { if (isSynced) { // Display last sync date - DateFormat dateFormat = - android.text.format.DateFormat.getDateFormat(getApplicationContext()); + //DateFormat dateFormat = + // android.text.format.DateFormat.getDateFormat(getApplicationContext()); Date date = new Date(); String sdate = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(date); String sinterval = " (interval:" + String.valueOf(syncInterval) + " min)"; @@ -294,7 +295,7 @@ public boolean onOptionsItemSelected(MenuItem item) { String mPackage = "com.Pau.ImapNotes2"; String mClass = ".AccountConfigurationActivity"; res.setComponent(new ComponentName(mPackage, mPackage + mClass)); - res.putExtra(AccountConfigurationActivity.ACTION, AccountConfigurationActivity.CREATE_ACCOUNT); + res.putExtra(ACTION, Actions.CREATE_ACCOUNT); startActivity(res); return true; case R.id.refresh: @@ -428,7 +429,7 @@ private class AccountsUpdateListener implements OnAccountsUpdateListener { @Override public void onAccountsUpdated(Account[] accounts) { List newList; - Integer newListSize = 0; + //Integer newListSize = 0; //invoked when the AccountManager starts up and whenever the account set changes this.newAccounts = new ArrayList<>(); for (final Account account : accounts) { From 2cbfb7159a65ac86ce1f1805b67bb6c65cd53aaa Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Fri, 11 Nov 2016 21:25:50 +0100 Subject: [PATCH 031/103] Use strings resource instead of literal strings to enable translation. --- .../AccountConfigurationActivity.java | 53 +++++++++---------- ImapNote2/src/main/res/values/strings.xml | 8 +++ 2 files changed, 33 insertions(+), 28 deletions(-) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java index 24340764..188695db 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java @@ -33,9 +33,6 @@ import java.util.List; -import static com.Pau.ImapNotes2.AccountConfigurationActivity.Actions.EDIT_ACCOUNT; -import static com.Pau.ImapNotes2.Miscs.Imaper.ResultCodeSuccess; - public class AccountConfigurationActivity extends AccountAuthenticatorActivity implements OnItemSelectedListener { private static final int TO_REFRESH = 999; private static final String AUTHORITY = "com.Pau.ImapNotes2.provider"; @@ -79,13 +76,7 @@ enum Actions { @Override public void onClick(View v) { // Click on Login Button - if (accountnameTextView.getText().toString().contains("'")) { - // Single quotation marks are not allowed in accountname - Toast.makeText(getApplicationContext(), "Quotation marks are not allowed in accountname", - Toast.LENGTH_LONG).show(); - } else { - DoLogin(v); - } + CheckNameAndLogIn(v); } }; @@ -93,22 +84,26 @@ public void onClick(View v) { @Override public void onClick(View v) { // Click on Edit Button - if (accountnameTextView.getText().toString().contains("'")) { - // Single quotation marks are not allowed in accountname - Toast.makeText(getApplicationContext(), "Quotation marks are not allowed in accountname", - Toast.LENGTH_LONG).show(); - } else { - DoLogin(v); - } + CheckNameAndLogIn(v); } }; + private void CheckNameAndLogIn(View v) { + if (accountnameTextView.getText().toString().contains("'")) { + // Single quotation marks are not allowed in accountname + Toast.makeText(getApplicationContext(), R.string.quotation_marks_not_allowed, + Toast.LENGTH_LONG).show(); + } else { + DoLogin(v); + } + } + private final OnClickListener clickListenerRemove = new View.OnClickListener() { @Override public void onClick(View v) { // Clic on Remove Button accountManager.removeAccount(myAccount, null, null); - Toast.makeText(getApplicationContext(), "Account has been removed", + Toast.makeText(getApplicationContext(), R.string.account_removed, Toast.LENGTH_LONG).show(); finish();//finishing activity } @@ -192,7 +187,7 @@ public void onCreate(Bundle savedInstanceState) { action = Actions.CREATE_ACCOUNT; } - if (action == EDIT_ACCOUNT) { + if (action == Actions.EDIT_ACCOUNT) { // Here we have to edit an existing account accountnameTextView.setText(accountname); usernameTextView.setText(GetConfigValue(ConfigurationFieldNames.UserName)); @@ -207,17 +202,17 @@ public void onCreate(Bundle savedInstanceState) { security_i = security.ordinal(); securitySpinner.setSelection(security_i); Button buttonEdit = new Button(this); - buttonEdit.setText("Save"); + buttonEdit.setText(R.string.save); buttonEdit.setOnClickListener(clickListenerEdit); layout.addView(buttonEdit); Button buttonRemove = new Button(this); - buttonRemove.setText("Remove"); + buttonRemove.setText(R.string.remove); buttonRemove.setOnClickListener(clickListenerRemove); layout.addView(buttonRemove); } else { // Here we have to create a new account Button buttonView = new Button(this); - buttonView.setText("Check & Create Account"); + buttonView.setText(R.string.check_and_create_account); buttonView.setOnClickListener(clickListenerLogin); layout.addView(buttonView); } @@ -234,7 +229,8 @@ private String GetConfigValue(String name) { // DoLogin method is defined in account_selection.xml (account_selection layout) private void DoLogin(View v) { - ProgressDialog loadingDialog = ProgressDialog.show(this, "ImapNotes2", "Logging into your account... ", true); + ProgressDialog loadingDialog = ProgressDialog.show(this, getString(R.string.app_name), + getString(R.string.logging_in), true); imapNotes2Account.SetAccountname(accountnameTextView.getText().toString().trim()); imapNotes2Account.SetUsername(usernameTextView.getText().toString().trim()); imapNotes2Account.SetPassword(passwordTextView.getText().toString().trim()); @@ -291,13 +287,14 @@ protected Boolean doInBackground(Void... none) { imapNotes2Account.GetUsesticky(), imapNotes2Account.GetFoldername()); //accountConfigurationActivity = acountConfigurationActivity; - if (res.returnCode == ResultCodeSuccess) { + if (res.returnCode == Imaper.ResultCodeSuccess) { + // TODO: Find out if "com.Pau.ImapNotes2" is the same as getApplicationContext().getPackageName(). Account account = new Account(imapNotes2Account.GetAccountname(), "com.Pau.ImapNotes2"); //long SYNC_FREQUENCY = (long) stuffs[ParamSyncPeriod]; AccountManager am = AccountManager.get(accountConfigurationActivity); accountConfigurationActivity.setResult(AccountConfigurationActivity.TO_REFRESH); Bundle result; - if (action == EDIT_ACCOUNT) { + if (action == Actions.EDIT_ACCOUNT) { result = new Bundle(); result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name); result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type); @@ -332,10 +329,10 @@ protected Boolean doInBackground(Void... none) { ContentResolver.setIsSyncable(account, AUTHORITY, 1); ContentResolver.setSyncAutomatically(account, AUTHORITY, true); ContentResolver.addPeriodicSync(account, AUTHORITY, new Bundle(), SYNC_FREQUENCY); - res.errorMessage = "Account has been added"; + res.errorMessage = getString(R.string.account_added); return true; } else { - res.errorMessage = "Account already exists or is null"; + res.errorMessage = getString(R.string.account_already_exists_or_is_null); return false; } } @@ -372,7 +369,7 @@ public void onFinish() { tag.show(); } }.start(); - if (action == EDIT_ACCOUNT) { + if (action == Actions.EDIT_ACCOUNT) { finish(); } } diff --git a/ImapNote2/src/main/res/values/strings.xml b/ImapNote2/src/main/res/values/strings.xml index 1910f6ff..15ea870d 100644 --- a/ImapNote2/src/main/res/values/strings.xml +++ b/ImapNote2/src/main/res/values/strings.xml @@ -6,4 +6,12 @@ Refresh About search + Account has been removed + Quotation marks are not allowed in accountname + Remove + Save + + "Logging into your account... " + Account already exists or is null + Account has been added From 4b0b96dc2865446228537a13c549d0500f622db8 Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Sat, 12 Nov 2016 12:54:02 +0100 Subject: [PATCH 032/103] Ran the Infer nullity analyser to annotate the code with @Nullable to provide hints for possible improvements to the code to reduce the risk of null reference errors. --- .../AccountConfigurationActivity.java | 50 +++++++++++++------ .../ImapNotes2/Data/ConfigurationFile.java | 22 ++++++-- .../ImapNotes2/Data/ImapNotes2Account.java | 20 ++++++++ .../java/com/Pau/ImapNotes2/Data/NotesDb.java | 10 ++-- .../java/com/Pau/ImapNotes2/ImapNotes2k.java | 2 + .../java/com/Pau/ImapNotes2/Listactivity.java | 21 +++++--- .../ImapNotes2/Miscs/ImapNotes2Result.java | 3 ++ .../Miscs/ImapNotesAuthenticatorService.java | 18 ++++++- .../java/com/Pau/ImapNotes2/Miscs/Imaper.java | 7 ++- .../com/Pau/ImapNotes2/Miscs/OneNote.java | 3 ++ .../com/Pau/ImapNotes2/Miscs/SyncThread.java | 8 ++- .../Pau/ImapNotes2/Miscs/UpdateThread.java | 5 +- .../com/Pau/ImapNotes2/NewNoteActivity.java | 4 +- .../Pau/ImapNotes2/NoteDetailActivity.java | 16 ++++-- .../com/Pau/ImapNotes2/NotesListAdapter.java | 25 +++++++--- .../com/Pau/ImapNotes2/Sync/Security.java | 3 ++ .../com/Pau/ImapNotes2/Sync/SyncAdapter.java | 9 ++-- .../com/Pau/ImapNotes2/Sync/SyncService.java | 2 + .../com/Pau/ImapNotes2/Sync/SyncUtils.java | 40 +++++++++------ 19 files changed, 198 insertions(+), 70 deletions(-) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java index 188695db..ac4ae858 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java @@ -8,6 +8,8 @@ import android.os.AsyncTask; import android.os.Bundle; import android.os.CountDownTimer; +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; import android.support.v4.app.NavUtils; import android.view.Menu; import android.view.MenuItem; @@ -50,12 +52,18 @@ public class AccountConfigurationActivity extends AccountAuthenticatorActivity i private CheckBox stickyCheckBox; private Spinner securitySpinner; private ImapNotes2Account imapNotes2Account; + // TODO: This should probably be initialized to None so that it need not be nullable. + @Nullable private Security security; //private int security_i; + @Nullable private Actions action; + @Nullable private String accountname; + @NonNull private ConfigurationFile settings = new ConfigurationFile(); + @Nullable private static Account myAccount = null; private static AccountManager accountManager; @@ -165,8 +173,8 @@ public void onCreate(Bundle savedInstanceState) { portnumTextView.setText(settings.GetPortnum()); security = settings.GetSecurity(); // Can never be null. if (security == null) security = "0"; - int security_i = security.ordinal(); - securitySpinner.setSelection(security_i); + //int security_i = security.ordinal(); + securitySpinner.setSelection(security.ordinal()); stickyCheckBox.setChecked(settings.GetUsesticky()); syncintervalTextView.setText("15"); folderTextView.setText(settings.GetFoldername()); @@ -199,8 +207,8 @@ public void onCreate(Bundle savedInstanceState) { syncintervalTextView.setText(GetConfigValue(ConfigurationFieldNames.SyncInterval)); folderTextView.setText(GetConfigValue(ConfigurationFieldNames.ImapFolder)); //if (security == null) security = "0"; - security_i = security.ordinal(); - securitySpinner.setSelection(security_i); + //security_i = security.ordinal(); + securitySpinner.setSelection(security.ordinal()); Button buttonEdit = new Button(this); buttonEdit.setText(R.string.save); buttonEdit.setOnClickListener(clickListenerEdit); @@ -227,20 +235,28 @@ private String GetConfigValue(String name) { return accountManager.getUserData(myAccount, name); } + private String GetTextViewText(@NonNull TextView textView) { + return textView.getText().toString().trim(); + } + // DoLogin method is defined in account_selection.xml (account_selection layout) private void DoLogin(View v) { ProgressDialog loadingDialog = ProgressDialog.show(this, getString(R.string.app_name), getString(R.string.logging_in), true); - imapNotes2Account.SetAccountname(accountnameTextView.getText().toString().trim()); - imapNotes2Account.SetUsername(usernameTextView.getText().toString().trim()); - imapNotes2Account.SetPassword(passwordTextView.getText().toString().trim()); - imapNotes2Account.SetServer(serverTextView.getText().toString().trim()); - imapNotes2Account.SetPortnum(portnumTextView.getText().toString()); + imapNotes2Account.SetAccountname(GetTextViewText(accountnameTextView)); + imapNotes2Account.SetUsername(GetTextViewText(usernameTextView)); + imapNotes2Account.SetPassword(GetTextViewText(passwordTextView)); + imapNotes2Account.SetServer(GetTextViewText(serverTextView)); + imapNotes2Account.SetPortnum(GetTextViewText(portnumTextView)); imapNotes2Account.SetSecurity(security); imapNotes2Account.SetUsesticky(stickyCheckBox.isChecked()); - imapNotes2Account.SetSyncinterval(syncintervalTextView.getText().toString()); - imapNotes2Account.SetFoldername(folderTextView.getText().toString()); - long SYNC_FREQUENCY = Long.parseLong(syncintervalTextView.getText().toString(), 10) * 60; + imapNotes2Account.SetSyncinterval(GetTextViewText(syncintervalTextView)); + imapNotes2Account.SetFoldername(GetTextViewText(folderTextView)); + // No need to check for valid numbers because the field only allows digits. But it is + // possible to remove all characters which causes the program to crash. The easiest fix is + // to add a zero at the beginning so that we are guaranteed to be able to parse it but that + // leaves us with a zero sync. interval. + long SYNC_FREQUENCY = Long.parseLong(GetTextViewText(syncintervalTextView), 10) * 60; new LoginThread( imapFolder, imapNotes2Account, @@ -257,6 +273,7 @@ class LoginThread extends AsyncTask { private final long SYNC_FREQUENCY; private final AccountConfigurationActivity accountConfigurationActivity; + @NonNull private ImapNotes2Result res = new ImapNotes2Result(); private final Actions action; @@ -274,6 +291,7 @@ public LoginThread(Imaper mapFolder, } + @NonNull protected Boolean doInBackground(Void... none) { //action = (String) stuffs[ParamAction]; try { @@ -293,9 +311,9 @@ protected Boolean doInBackground(Void... none) { //long SYNC_FREQUENCY = (long) stuffs[ParamSyncPeriod]; AccountManager am = AccountManager.get(accountConfigurationActivity); accountConfigurationActivity.setResult(AccountConfigurationActivity.TO_REFRESH); - Bundle result; + //Bundle result; if (action == Actions.EDIT_ACCOUNT) { - result = new Bundle(); + Bundle result = new Bundle(); result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name); result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type); setAccountAuthenticatorResult(result); @@ -314,7 +332,7 @@ protected Boolean doInBackground(Void... none) { return true; } else { if (am.addAccountExplicitly(account, imapNotes2Account.GetPassword(), null)) { - result = new Bundle(); + Bundle result = new Bundle(); result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name); result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type); setAccountAuthenticatorResult(result); @@ -379,7 +397,7 @@ public boolean onCreateOptionsMenu(Menu menu) { return true; } - public boolean onOptionsItemSelected(MenuItem item) { + public boolean onOptionsItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case android.R.id.home: NavUtils.navigateUpFromSameTask(this); diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFile.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFile.java index 572c451f..0fc36ac9 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFile.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFile.java @@ -12,6 +12,8 @@ import android.content.Context; //import android.util.Log; +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; import android.util.Xml; import com.Pau.ImapNotes2.ImapNotes2k; @@ -24,19 +26,26 @@ public class ConfigurationFile { // TODO: make all fields final. // The account name is the concatenation of the username and server. + @Nullable private String accountname; // User name on the IMAP server. + @Nullable private String username; + @Nullable private String password; // Address of the IMAP server + @Nullable private String server; // Port number. + @Nullable private String portnum; // TLS, etc. + @Nullable private Security security = Security.None; // ? private boolean usesticky; // The name of the IMAP folder to be used. + @Nullable private String imapfolder; @@ -82,10 +91,12 @@ public ConfigurationFile() { } } + @Nullable public String GetAccountname() { return accountname; } + @Nullable public String GetUsername() { return username; } @@ -94,6 +105,7 @@ public void SetUsername(String Username) { username = Username; } + @Nullable public String GetPassword() { return password; } @@ -102,6 +114,7 @@ public void SetPassword(String Password) { password = Password; } + @Nullable public String GetServer() { return server; } @@ -110,6 +123,7 @@ public void SetServer(String Server) { server = Server; } + @Nullable public String GetPortnum() { return portnum; } @@ -118,6 +132,7 @@ public void SetPortnum(String Portnum) { portnum = Portnum; } + @Nullable public Security GetSecurity() { return security; } @@ -138,6 +153,7 @@ public void SetUsesticky(boolean usesticky) { } */ + @Nullable public String GetFoldername() { return imapfolder; } @@ -181,7 +197,7 @@ public void SaveConfigurationToXML() } // Avoid repeated literal tag names. - private void SerializeText(XmlSerializer serializer, + private void SerializeText(@NonNull XmlSerializer serializer, String tag, String text) throws IOException { @@ -190,13 +206,13 @@ private void SerializeText(XmlSerializer serializer, serializer.endTag(null, tag); } - private NodeList LoadItemFromXML(Document fileLoaded, + private NodeList LoadItemFromXML(@NonNull Document fileLoaded, String tag) { return fileLoaded.getElementsByTagName(tag); } // Reduce clutter and improve maintainability. - private String NodeValueFromXML(Document fileLoaded, + private String NodeValueFromXML(@NonNull Document fileLoaded, String tag) { return LoadItemFromXML(fileLoaded, tag).item(0).getChildNodes().item(0).getNodeValue(); } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ImapNotes2Account.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ImapNotes2Account.java index 6a92e1a0..146474d0 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ImapNotes2Account.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ImapNotes2Account.java @@ -1,27 +1,39 @@ package com.Pau.ImapNotes2.Data; import android.accounts.Account; +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; import com.Pau.ImapNotes2.Sync.Security; public class ImapNotes2Account { private String accountname = ""; + // TODO: Why are the username, password, etc. nullable? + @Nullable private String username = ""; + @Nullable private String password = ""; + @Nullable private String server = ""; + @Nullable private String portnum = ""; + @Nullable private Security security = null; private boolean usesticky = false; private String syncinterval = "15"; + @Nullable private String imapfolder = ""; + @NonNull private Boolean accountHasChanged = false; + @Nullable private Account account = null; public ImapNotes2Account() { } + @NonNull public String toString() { return this.accountname + ":" + this.username + ":" + this.password + ":" + this.server + ":" + this.portnum + ":" + this.security + ":" @@ -36,6 +48,7 @@ public void SetAccount(Account account) { this.account = account; } + @Nullable public Account GetAccount() { return this.account; } @@ -45,6 +58,7 @@ public void SetAccountname(String Accountname) { this.accountname = Accountname; } + @Nullable public String GetUsername() { return this.username; } @@ -53,6 +67,7 @@ public void SetUsername(String Username) { this.username = Username; } + @Nullable public String GetPassword() { return this.password; } @@ -61,6 +76,7 @@ public void SetPassword(String Password) { this.password = Password; } + @Nullable public String GetServer() { return this.server; } @@ -69,6 +85,7 @@ public void SetServer(String Server) { this.server = Server; } + @Nullable public String GetPortnum() { return this.portnum; } @@ -77,6 +94,7 @@ public void SetPortnum(String Portnum) { this.portnum = Portnum; } + @Nullable public Security GetSecurity() { return security; } @@ -113,10 +131,12 @@ public void SetaccountHasNotChanged() { this.accountHasChanged = false; } + @NonNull public Boolean GetaccountHasChanged() { return this.accountHasChanged; } + @Nullable public String GetFoldername() { return this.imapfolder; } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java index 6b0880ed..2034f471 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java @@ -13,6 +13,7 @@ import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; +import android.support.annotation.NonNull; public class NotesDb { @@ -29,6 +30,7 @@ public class NotesDb { + "accountname text not null);"; private SQLiteDatabase notesDb; + @NonNull private final NotesDbHelper defaultHelper; public NotesDb(Context applicationContext) { @@ -47,7 +49,7 @@ public void CloseDb() { } - public void InsertANoteInDb(OneNote noteElement, String accountname) { + public void InsertANoteInDb(@NonNull OneNote noteElement, String accountname) { ContentValues tableRow = new ContentValues(); tableRow.put("title", (noteElement.GetTitle() != null) ? noteElement.GetTitle() : ""); tableRow.put("date", noteElement.GetDate()); @@ -90,7 +92,7 @@ public String GetTempNumber(String accountname) { return "-1"; } - public void GetStoredNotes(ArrayList noteList, String accountname) { + public void GetStoredNotes(@NonNull ArrayList noteList, String accountname) { noteList.clear(); Date date = null; Cursor resultPointer = this.notesDb.query("notesTable", null, "accountname = ?", new String[]{accountname}, null, null, "date DESC"); @@ -140,7 +142,7 @@ public NotesDbHelper(Context currentApplicationContext, String dbName, int dbVer } @Override - public void onCreate(SQLiteDatabase _db) { + public void onCreate(@NonNull SQLiteDatabase _db) { _db.execSQL(NotesDb.CREATE_NOTES_DB); } @@ -159,7 +161,7 @@ public void apply(SQLiteDatabase _db) { private static final Patch[] PATCHES = new Patch[]{ new Patch() { - public void apply(SQLiteDatabase _db) { + public void apply(@NonNull SQLiteDatabase _db) { //Log.d(TAG,"upgrade: v2 to v3"); _db.execSQL("Drop table notesTable;"); _db.execSQL(NotesDb.CREATE_NOTES_DB); diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/ImapNotes2k.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/ImapNotes2k.java index 3c0431ad..2b2c8009 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/ImapNotes2k.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/ImapNotes2k.java @@ -9,6 +9,7 @@ import android.app.Application; import android.content.Context; +import android.support.annotation.NonNull; /* @@ -37,6 +38,7 @@ public static Context getAppContext() { return ImapNotes2k.context; } + @NonNull public static String ConfigurationFilePath() { return ConfigurationDirPath() + "/" + configurationFileName; } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java index 0a680a52..6537b10d 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java @@ -40,6 +40,8 @@ import android.content.PeriodicSync; import android.content.pm.PackageInfo; import android.os.Bundle; +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; import android.util.Log; import android.view.Menu; import android.view.MenuItem; @@ -89,13 +91,16 @@ public class Listactivity extends Activity implements OnItemSelectedListener, Fi private ArrayAdapter spinnerList; private Imaper imapFolder; + @Nullable private static NotesDb storedNotes = null; private Spinner accountSpinner; public static ImapNotes2Account imapNotes2Account; private static AccountManager accountManager; // Ensure that we never have to check for null by initializing reference. + @NonNull private static Account[] accounts = new Account[0]; private static List currentList; + @Nullable private TextView status = null; private static String OldStatus; private static final String AUTHORITY = "com.Pau.ImapNotes2.provider"; @@ -162,7 +167,7 @@ public void onCreate(Bundle savedInstanceState) { // When item is clicked, we go to NoteDetailActivity listview.setOnItemClickListener(new OnItemClickListener() { - public void onItemClick(AdapterView parent, View widget, int selectedNote, long rowId) { + public void onItemClick(@NonNull AdapterView parent, @NonNull View widget, int selectedNote, long rowId) { Intent toDetail = new Intent(widget.getContext(), NoteDetailActivity.class); toDetail.putExtra(NoteDetailActivity.selectedNote, (OneNote) parent.getItemAtPosition(selectedNote)); toDetail.putExtra(NoteDetailActivity.useSticky, Listactivity.imapNotes2Account.GetUsesticky()); @@ -202,8 +207,9 @@ protected void onPause() { unregisterReceiver(syncFinishedReceiver); } + @Nullable private final BroadcastReceiver syncFinishedReceiver = new BroadcastReceiver() { - public void onReceive(Context context, Intent intent) { + public void onReceive(Context context, @NonNull Intent intent) { String accountname = intent.getStringExtra(ACCOUNTNAME); Boolean isChanged = intent.getBooleanExtra(CHANGED, false); Boolean isSynced = intent.getBooleanExtra(SYNCED, false); @@ -258,7 +264,7 @@ private void UpdateList(String suid, } - public boolean onCreateOptionsMenu(Menu menu) { + public boolean onCreateOptionsMenu(@NonNull Menu menu) { getMenuInflater().inflate(R.menu.list, menu); // Associate searchable configuration with the SearchView @@ -288,7 +294,7 @@ public boolean onQueryTextSubmit(String query) { return true; } - public boolean onOptionsItemSelected(MenuItem item) { + public boolean onOptionsItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.login: Intent res = new Intent(); @@ -331,7 +337,7 @@ public void onClick(DialogInterface dialog, int which) { } } - protected void onActivityResult(int requestCode, int resultCode, Intent data) { + protected void onActivityResult(int requestCode, int resultCode, @NonNull Intent data) { switch (requestCode) { case Listactivity.SEE_DETAIL: // Returning from NoteDetailActivity @@ -427,7 +433,7 @@ private class AccountsUpdateListener implements OnAccountsUpdateListener { private ArrayList newAccounts; @Override - public void onAccountsUpdated(Account[] accounts) { + public void onAccountsUpdated(@NonNull Account[] accounts) { List newList; //Integer newListSize = 0; //invoked when the AccountManager starts up and whenever the account set changes @@ -527,7 +533,7 @@ public void SendLogcatMail() { startActivity(Intent.createChooser(emailIntent, "Send email...")); } - private static void TriggerSync(TextView statusField) { + private static void TriggerSync(@NonNull TextView statusField) { OldStatus = statusField.getText().toString(); statusField.setText("Syncing..."); Account mAccount = Listactivity.imapNotes2Account.GetAccount(); @@ -540,6 +546,7 @@ private static void TriggerSync(TextView statusField) { ContentResolver.requestSync(mAccount, AUTHORITY, settingsBundle); } + @Nullable @Override public Filter getFilter() { return null; diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/ImapNotes2Result.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/ImapNotes2Result.java index 1c363599..0e9c6ade 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/ImapNotes2Result.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/ImapNotes2Result.java @@ -1,5 +1,7 @@ package com.Pau.ImapNotes2.Miscs; +import android.support.annotation.Nullable; + import javax.mail.Folder; public class ImapNotes2Result { @@ -8,6 +10,7 @@ public class ImapNotes2Result { public String errorMessage; public Long UIDValidity; public boolean hasUIDPLUS; + @Nullable public Folder notesFolder; public ImapNotes2Result() { diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/ImapNotesAuthenticatorService.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/ImapNotesAuthenticatorService.java index 118ba8bb..c68d6332 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/ImapNotesAuthenticatorService.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/ImapNotesAuthenticatorService.java @@ -13,6 +13,8 @@ import android.content.Intent; import android.os.Bundle; import android.os.IBinder; +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; public class ImapNotesAuthenticatorService extends Service { @@ -24,7 +26,7 @@ public void onCreate() { this.imapNotesAuthenticator = new Authenticator(this); } - public IBinder onBind(Intent intent) { + public IBinder onBind(@NonNull Intent intent) { IBinder ret = null; if (intent.getAction().equals(android.accounts.AccountManager.ACTION_AUTHENTICATOR_INTENT)) ret = getAuthenticator().getIBinder(); @@ -50,7 +52,7 @@ public Authenticator(Context context) { @Override public Bundle getAccountRemovalAllowed( - AccountAuthenticatorResponse response, Account account) + AccountAuthenticatorResponse response, @NonNull Account account) throws NetworkErrorException { Bundle ret = super.getAccountRemovalAllowed(response, account); if (ret.getBoolean(AccountManager.KEY_BOOLEAN_RESULT)) @@ -62,6 +64,7 @@ public Bundle getAccountRemovalAllowed( return ret; } + @NonNull @Override public Bundle addAccount(AccountAuthenticatorResponse response, String accountType, String authTokenType, String[] requiredFeatures, Bundle options) throws NetworkErrorException { @@ -73,36 +76,47 @@ public Bundle addAccount(AccountAuthenticatorResponse response, String accountTy return bundle; } + @Nullable @Override public Bundle confirmCredentials(AccountAuthenticatorResponse response, Account account, Bundle options) throws NetworkErrorException { return null; } + // TODO: Describe the purpose of this method. + @Nullable @Override public Bundle editProperties(AccountAuthenticatorResponse response, String accountType) { return null; } + // TODO: Describe the purpose of this method. + @Nullable @Override public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException { return null; } + // TODO: Describe the purpose of this method. + @Nullable @Override public String getAuthTokenLabel(String authTokenType) { return null; } + // TODO: Describe the purpose of this method. + @Nullable @Override public Bundle hasFeatures(AccountAuthenticatorResponse response, Account account, String[] features) throws NetworkErrorException { return null; } + // TODO: Describe the purpose of this method. + @Nullable @Override public Bundle updateCredentials(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException { diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Imaper.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Imaper.java index 48ad63b6..25bed7e2 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Imaper.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Imaper.java @@ -5,6 +5,7 @@ import android.content.Context; import android.content.SharedPreferences; +import android.support.annotation.NonNull; import android.util.Log; import javax.mail.Folder; @@ -23,6 +24,7 @@ public class Imaper { private Store store; private static final String TAG = "IN_Imaper"; + @NonNull private static String sfolder = "Notes"; private Long UIDValidity; public static final String PREFS_NAME = "PrefsFile"; @@ -31,13 +33,14 @@ public class Imaper { public static final int ResultCodeException = -2; public static final int ResultCodeCantConnect = -1; + @NonNull public ImapNotes2Result ConnectToProvider(String username, String password, String server, String portnum, - Security security, + @NonNull Security security, boolean usesticky, - String folderoverride) throws MessagingException { + @NonNull String folderoverride) throws MessagingException { if (IsConnected()) { store.close(); } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/OneNote.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/OneNote.java index dd13f78b..47b5b021 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/OneNote.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/OneNote.java @@ -1,5 +1,7 @@ package com.Pau.ImapNotes2.Miscs; +import android.support.annotation.NonNull; + import java.util.HashMap; /* Represents metadata aboit a note. */ @@ -51,6 +53,7 @@ public void SetUid(String uid) { this.put("uid", uid); } + @NonNull @Override public String toString() { return ("Title:" + this.GetTitle() + diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/SyncThread.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/SyncThread.java index b49f4acb..3ffbeeb4 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/SyncThread.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/SyncThread.java @@ -10,13 +10,18 @@ import android.app.ProgressDialog; import android.content.Context; import android.os.AsyncTask; +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; public class SyncThread extends AsyncTask { private final ProgressDialog progressDialog; private NotesListAdapter adapter; private ArrayList notesList; + // TODO: NoteDb should probably never be null. + @Nullable private NotesDb storedNotes; boolean bool_to_return; + @NonNull ImapNotes2Result res = new ImapNotes2Result(); private static final String TAG = "SyncThread"; @@ -26,7 +31,7 @@ public SyncThread(Object imapFolder, ArrayList noteList, NotesListAdapter listToView, ProgressDialog loadingDialog, - NotesDb storedNotes, + @Nullable NotesDb storedNotes, Context applicationContext) { //this.imapFolder = imapFolder; //this.imapNotes2Account = imapNotes2Account; @@ -40,6 +45,7 @@ public SyncThread(Object imapFolder, // Do not pass arguments via execute; the object is never reused so it is quite safe to pass // the arguments in the constructor. + @NonNull @Override protected Boolean doInBackground(Object... stuffs) { /*String username = null; diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java index c69664ec..4ed6b4c0 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java @@ -26,6 +26,7 @@ import android.app.ProgressDialog; import android.content.Context; import android.os.AsyncTask; +import android.support.annotation.NonNull; import android.text.Html; import static com.Pau.ImapNotes2.NoteDetailActivity.*; @@ -162,7 +163,7 @@ private int getIndexByNumber(String pNumber) { return -1; } - private void MoveMailToDeleted(String suid) { + private void MoveMailToDeleted(@NonNull String suid) { String directory = (ImapNotes2k.getAppContext()).getFilesDir() + "/" + Listactivity.imapNotes2Account.GetAccountname(); String positiveUid = suid.substring(1); @@ -176,7 +177,7 @@ private void MoveMailToDeleted(String suid) { } } - private void WriteMailToNew(OneNote note, + private void WriteMailToNew(@NonNull OneNote note, boolean usesticky, String noteBody) throws MessagingException, IOException { String body = null; diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NewNoteActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NewNoteActivity.java index 6374342b..6f45d4d7 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NewNoteActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NewNoteActivity.java @@ -4,6 +4,7 @@ import android.content.Intent; import android.graphics.Color; import android.os.Bundle; +import android.support.annotation.NonNull; import android.support.v4.app.NavUtils; import android.text.Html; import android.view.Menu; @@ -17,6 +18,7 @@ public class NewNoteActivity extends Activity { private static final int SAVE_BUTTON = 5; private static final String TAG = "IN_NewNoteActivity"; private boolean sticky; + @NonNull private Colors color = Colors.NONE; //region Intent item names public static final String usesSticky = "usesSticky"; @@ -41,7 +43,7 @@ public boolean onCreateOptionsMenu(Menu menu) { return true; } - public boolean onOptionsItemSelected(MenuItem item) { + public boolean onOptionsItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.save: Intent intent = new Intent(); diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java index d36b5e18..ca7a326c 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java @@ -4,6 +4,8 @@ import android.content.Intent; import android.graphics.Color; import android.os.Bundle; +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; import android.support.v4.app.NavUtils; import android.text.Editable; import android.text.Html; @@ -122,7 +124,7 @@ public boolean onCreateOptionsMenu(Menu menu) { } @Override - public boolean onPrepareOptionsMenu(Menu menu) { + public boolean onPrepareOptionsMenu(@NonNull Menu menu) { MenuItem item = menu.findItem(R.id.color); super.onPrepareOptionsMenu(menu); //depending on your conditions, either enable/disable @@ -131,7 +133,7 @@ public boolean onPrepareOptionsMenu(Menu menu) { return true; } - public boolean onOptionsItemSelected(MenuItem item) { + public boolean onOptionsItemSelected(@NonNull MenuItem item) { Intent intent = new Intent(); int itemId = item.getItemId(); switch (itemId) { @@ -197,6 +199,7 @@ private Colors(int id, this.colorCode = colorCode; } + @NonNull public static Colors fromId(int id) { for (Colors color : Colors.values()) { @@ -207,7 +210,8 @@ public static Colors fromId(int id) { } } - private Sticky GetInfoFromMessage(Message message) { + @Nullable + private Sticky GetInfoFromMessage(@NonNull Message message) { ContentType contentType = null; String stringres = null; InputStream iis = null; @@ -246,7 +250,7 @@ private Sticky GetInfoFromMessage(Message message) { return sticky; } - private void GetPart(Part message) throws Exception { + private void GetPart(@NonNull Part message) throws Exception { if (message.isMimeType("text/plain")) { Log.d(TAG, "+++ isMimeType text/plain (contentType):" + message.getContentType()); } else if (message.isMimeType("multipart/*")) { @@ -272,6 +276,7 @@ private void GetPart(Part message) throws Exception { } } + @NonNull private Sticky ReadHtmlnote(String stringres) { // Log.d(TAG,"From server (html):"+stringres); Spanned spanres = Html.fromHtml(stringres); @@ -285,6 +290,7 @@ private Sticky ReadHtmlnote(String stringres) { return new Sticky(stringres, "", Colors.NONE); } + @NonNull private Sticky ReadPlainnote(String stringres) { // Log.d(TAG,"From server (plain):"+stringres); stringres = stringres.replaceAll("\n", "
"); @@ -292,7 +298,7 @@ private Sticky ReadPlainnote(String stringres) { return new Sticky(stringres, "", Colors.NONE); } - private void WriteMailToFile(String suid, Message message) { + private void WriteMailToFile(@NonNull String suid, @NonNull Message message) { String directory = (ImapNotes2k.getAppContext()).getFilesDir() + "/" + Listactivity.imapNotes2Account.GetAccountname(); try { diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java index 54661541..e15d96bf 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java @@ -17,6 +17,8 @@ */ import android.content.Context; +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; @@ -63,6 +65,7 @@ public class NotesListAdapter extends BaseAdapter implements Filterable { private final int mResource; private int mDropDownResource; + @NonNull private final LayoutInflater mInflater; private SimpleFilter mFilter; @@ -83,7 +86,7 @@ public class NotesListAdapter extends BaseAdapter implements Filterable { * TextViews. The first N views in this list are given the values of the first N columns * in the from parameter. */ - public NotesListAdapter(Context context, List> data, + public NotesListAdapter(@NonNull Context context, List> data, int resource, String[] from, int[] to) { mData = data; mResource = mDropDownResource = resource; @@ -117,11 +120,14 @@ public long getItemId(int position) { /** * @see android.widget.Adapter#getView(int, View, ViewGroup) */ + @Nullable public View getView(int position, View convertView, ViewGroup parent) { return createViewFromResource(position, convertView, parent, mResource); } - private View createViewFromResource(int position, View convertView, + // TODO: this should never return null and the convertView argument should never be null. + @Nullable + private View createViewFromResource(int position, @Nullable View convertView, ViewGroup parent, int resource) { View v; if (convertView == null) { @@ -145,12 +151,14 @@ public void setDropDownViewResource(int resource) { this.mDropDownResource = resource; } + // TODO: Should never return null. + @Nullable @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { return createViewFromResource(position, convertView, parent, mDropDownResource); } - private void bindView(int position, View view) { + private void bindView(int position, @NonNull View view) { final Map dataSet = mData.get(position); if (dataSet == null) { return; @@ -240,7 +248,7 @@ public void setViewBinder(ViewBinder viewBinder) { * @param value the value retrieved from the data set * @see #setViewImage(ImageView, String) */ - private void setViewImage(ImageView v, int value) { + private void setViewImage(@NonNull ImageView v, int value) { v.setImageResource(value); } @@ -260,7 +268,7 @@ private void setViewImage(ImageView v, int value) { * @param value the value retrieved from the data set * @see #setViewImage(ImageView, int) */ - private void setViewImage(ImageView v, String value) { + private void setViewImage(@NonNull ImageView v, String value) { try { v.setImageResource(Integer.parseInt(value)); } catch (NumberFormatException nfe) { @@ -276,7 +284,7 @@ private void setViewImage(ImageView v, String value) { * @param v TextView to receive text * @param text the text to be set for the TextView */ - private void setViewText(TextView v, String text) { + private void setViewText(@NonNull TextView v, String text) { v.setText(text); } @@ -324,8 +332,9 @@ public interface ViewBinder { */ private class SimpleFilter extends Filter { + @NonNull @Override - protected FilterResults performFiltering(CharSequence prefix) { + protected FilterResults performFiltering(@Nullable CharSequence prefix) { FilterResults results = new FilterResults(); if (mUnfilteredData == null) { @@ -369,7 +378,7 @@ protected FilterResults performFiltering(CharSequence prefix) { } @Override - protected void publishResults(CharSequence constraint, FilterResults results) { + protected void publishResults(CharSequence constraint, @NonNull FilterResults results) { //noinspection unchecked mData = (List>) results.values; if (results.count > 0) { diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/Security.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/Security.java index 7142b5d8..400ce1c2 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/Security.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/Security.java @@ -1,5 +1,7 @@ package com.Pau.ImapNotes2.Sync; +import android.support.annotation.NonNull; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -37,6 +39,7 @@ public enum Security { this.acceptcrt = acceptcrt; } + @NonNull public static List Printables() { List list = new ArrayList<>(); for (Security e : Security.values()) { diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java index 08ec636c..551cadc1 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java @@ -9,6 +9,7 @@ import android.content.Intent; import android.content.SyncResult; import android.os.Bundle; +import android.support.annotation.NonNull; import android.util.Log; import java.io.File; @@ -39,13 +40,14 @@ class SyncAdapter extends AbstractThreadedSyncAdapter { private NotesDb storedNotes; private static Account account; /// See RFC 3501: http://www.faqs.org/rfcs/rfc3501.html + @NonNull private Long UIDValidity = (long) -1; private final static int NEW = 1; private final static int DELETED = 2; private final ContentResolver mContentResolver; - public SyncAdapter(Context context, + public SyncAdapter(@NonNull Context context, boolean autoInitialize) { super(context, autoInitialize); mContentResolver = context.getContentResolver(); @@ -53,7 +55,7 @@ public SyncAdapter(Context context, SyncAdapter.context = context; } - public SyncAdapter(Context context, + public SyncAdapter(@NonNull Context context, boolean autoInitialize, // ? boolean allowParallelSyncs // always false, set in syncadapter.xml ) { @@ -63,7 +65,7 @@ public SyncAdapter(Context context, } @Override - public void onPerformSync(Account account, + public void onPerformSync(@NonNull Account account, Bundle extras, String authority, ContentProviderClient provider, @@ -173,6 +175,7 @@ public void onPerformSync(Account account, the caller becomes responsible. This is the correct approach. */ + @NonNull private ImapNotes2Result ConnectToRemote() { AccountManager am = AccountManager.get(context); ImapNotes2Result res = SyncUtils.ConnectToRemote( diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncService.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncService.java index 4537d6e1..9d0795b8 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncService.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncService.java @@ -3,6 +3,7 @@ import android.app.Service; import android.content.Intent; import android.os.IBinder; +import android.support.annotation.Nullable; import android.util.Log; public class SyncService extends Service { @@ -10,6 +11,7 @@ public class SyncService extends Service { private static final String TAG = "SyncService"; private static final Object sSyncAdapterLock = new Object(); + @Nullable private static SyncAdapter sSyncAdapter = null; @Override diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java index ad55547f..9ff0aa9f 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java @@ -3,6 +3,8 @@ import android.accounts.Account; import android.content.Context; import android.content.SharedPreferences; +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; import android.util.Log; import com.Pau.ImapNotes2.Data.NotesDb; @@ -48,7 +50,10 @@ public class SyncUtils { private static Store store; private static final String TAG = "IN_SyncUtils"; private static String proto; + // TODO: Why do we have two folder fields and why are they both nullable? + @Nullable private static String sfolder = "Notes"; + @Nullable private static Folder notesFolder = null; private static final ImapNotes2Result res = new ImapNotes2Result(); private static Long UIDValidity; @@ -59,13 +64,14 @@ public class SyncUtils { /* This function cannot return null. Can we mark it so that the analysers can use this information? */ + @NonNull static ImapNotes2Result ConnectToRemote(String username, String password, String server, String portnum, - Security security, + @NonNull Security security, String usesticky, - String override) { + @Nullable String override) { if (IsConnected()) { try { store.close(); @@ -160,10 +166,10 @@ static ImapNotes2Result ConnectToRemote(String username, /* Copy all notes from the IMAP server to the local directory using the UID as the file name. */ - public static void GetNotes(Account account, - Folder notesFolder, - Context ctx, - NotesDb storedNotes) throws MessagingException { + public static void GetNotes(@NonNull Account account, + @NonNull Folder notesFolder, + @NonNull Context ctx, + @NonNull NotesDb storedNotes) throws MessagingException { //Long UIDM; //Message notesMessage; File directory = new File(ctx.getFilesDir() + "/" + account.name); @@ -192,7 +198,8 @@ public static void GetNotes(Account account, private static final Pattern patternPosition = Pattern.compile("^POSITION:(.*?)$", Pattern.MULTILINE); private static final Pattern patternText = Pattern.compile("TEXT:(.*?)(END:|POSITION:)", Pattern.DOTALL); - public static Sticky ReadStickynote(String stringres) { + @NonNull + public static Sticky ReadStickynote(@NonNull String stringres) { Matcher matcherColor = patternColor.matcher(stringres); Colors color = Colors.NONE; @@ -244,7 +251,7 @@ public static void DeleteNote(int numMessage) throws MessagingException { } // Put values in shared preferences - public static void SetUIDValidity(Account account, Long UIDValidity, Context ctx) { + public static void SetUIDValidity(@NonNull Account account, Long UIDValidity, @NonNull Context ctx) { SharedPreferences preferences = ctx.getSharedPreferences(account.name, Context.MODE_MULTI_PROCESS); SharedPreferences.Editor editor = preferences.edit(); editor.putString("Name", "valid_data"); @@ -254,7 +261,7 @@ public static void SetUIDValidity(Account account, Long UIDValidity, Context ctx } // Retrieve values from shared preferences: - public static Long GetUIDValidity(Account account, Context ctx) { + public static Long GetUIDValidity(@NonNull Account account, @NonNull Context ctx) { UIDValidity = (long) -1; SharedPreferences preferences = ctx.getSharedPreferences(account.name, Context.MODE_MULTI_PROCESS); String name = preferences.getString("Name", ""); @@ -274,7 +281,8 @@ public static void DisconnectFromRemote() { } } - public static Message ReadMailFromFile(String uid, int where, boolean removeMinus, String nameDir) { + @Nullable + public static Message ReadMailFromFile(@NonNull String uid, int where, boolean removeMinus, String nameDir) { File mailFile; Message message = null; mailFile = new File(nameDir, uid); @@ -316,7 +324,7 @@ public static Message ReadMailFromFile(String uid, int where, boolean removeMinu return message; } - public static AppendUID[] sendMessageToRemote(Message[] message) throws MessagingException { + public static AppendUID[] sendMessageToRemote(@NonNull Message[] message) throws MessagingException { notesFolder = store.getFolder(sfolder); if (notesFolder.isOpen()) { if ((notesFolder.getMode() & Folder.READ_WRITE) != 0) @@ -327,7 +335,7 @@ public static AppendUID[] sendMessageToRemote(Message[] message) throws Messagin return ((IMAPFolder) notesFolder).appendUIDMessages(message); } - public static void ClearHomeDir(Account account, Context ctx) { + public static void ClearHomeDir(@NonNull Account account, @NonNull Context ctx) { File directory = new File(ctx.getFilesDir() + "/" + account.name); try { FileUtils.deleteDirectory(directory); @@ -337,7 +345,7 @@ public static void ClearHomeDir(Account account, Context ctx) { } } - public static void CreateDirs(String accountName, Context ctx) { + public static void CreateDirs(String accountName, @NonNull Context ctx) { String stringDir = ctx.getFilesDir() + "/" + accountName; File directory = new File(stringDir); directory.mkdirs(); @@ -347,7 +355,7 @@ public static void CreateDirs(String accountName, Context ctx) { directory.mkdirs(); } - private static void GetOneNote(File outfile, Message notesMessage, NotesDb storedNotes, String accountName, String suid, boolean updateDb) { + private static void GetOneNote(@NonNull File outfile, @NonNull Message notesMessage, @NonNull NotesDb storedNotes, String accountName, String suid, boolean updateDb) { OutputStream str = null; try { @@ -422,7 +430,7 @@ private static void GetOneNote(File outfile, Message notesMessage, NotesDb store storedNotes.InsertANoteInDb(aNote, accountName); } - public static boolean handleRemoteNotes(Context context, Folder notesFolder, NotesDb storedNotes, String accountName, String usesticky) + public static boolean handleRemoteNotes(@NonNull Context context, @NonNull Folder notesFolder, @NonNull NotesDb storedNotes, String accountName, @NonNull String usesticky) throws MessagingException { Message notesMessage; @@ -496,7 +504,7 @@ public static boolean handleRemoteNotes(Context context, Folder notesFolder, Not return result; } - public static void RemoveAccount(Context context, Account account) { + public static void RemoveAccount(@NonNull Context context, @NonNull Account account) { // remove Shared Preference file String rootString = context.getFilesDir().getParent() + File.separator + "shared_prefs"; From 215af82c993d1189b6804a410fb2186cf7678ffa Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Sat, 12 Nov 2016 14:34:48 +0100 Subject: [PATCH 033/103] Removed Imaper.sfolder because it was only assigned but never read. --- ImapNote2/src/main/AndroidManifest.xml | 1 + .../java/com/Pau/ImapNotes2/Miscs/Imaper.java | 6 ++--- .../com/Pau/ImapNotes2/Sync/StubProvider.java | 11 ++++---- .../com/Pau/ImapNotes2/Sync/SyncAdapter.java | 5 ++-- .../com/Pau/ImapNotes2/Sync/SyncService.java | 6 +++++ .../com/Pau/ImapNotes2/Sync/SyncUtils.java | 25 ++++++++----------- 6 files changed, 28 insertions(+), 26 deletions(-) diff --git a/ImapNote2/src/main/AndroidManifest.xml b/ImapNote2/src/main/AndroidManifest.xml index 0cc70a06..59057e82 100644 --- a/ImapNote2/src/main/AndroidManifest.xml +++ b/ImapNote2/src/main/AndroidManifest.xml @@ -81,6 +81,7 @@ android:resource="@xml/authenticator" /> + Date: Sat, 12 Nov 2016 16:11:44 +0100 Subject: [PATCH 034/103] Fixed bug associated with background colour. None should have White not zero. --- .../java/com/Pau/ImapNotes2/Miscs/Sticky.java | 6 +++- .../Pau/ImapNotes2/NoteDetailActivity.java | 35 ++++++++++++------- 2 files changed, 28 insertions(+), 13 deletions(-) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Sticky.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Sticky.java index b4c4030d..16321617 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Sticky.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Sticky.java @@ -1,16 +1,20 @@ package com.Pau.ImapNotes2.Miscs; +import android.support.annotation.NonNull; + import static com.Pau.ImapNotes2.NoteDetailActivity.Colors; public class Sticky { public final String text; public final String position; + @NonNull public final Colors color; public Sticky(String text, String position, - Colors color) { + @NonNull Colors color) { + assert (color != null); this.text = text; this.position = position; this.color = color; diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java index ca7a326c..7e1f4c55 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java @@ -6,6 +6,8 @@ import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; +import android.support.v4.*; +import android.support.v4.BuildConfig; import android.support.v4.app.NavUtils; import android.text.Editable; import android.text.Html; @@ -41,8 +43,9 @@ public class NoteDetailActivity extends Activity { //private static final int DELETE_BUTTON = 3; private static final int EDIT_BUTTON = 6; private boolean usesticky; - private Colors color; - private int realColor = R.id.yellow; + @NonNull + private Colors color = Colors.YELLOW; + //private int realColor = R.id.yellow; private String suid; // uid as string private final static int ROOT_AND_NEW = 3; private static final String TAG = "IN_NoteDetailActivity"; @@ -75,6 +78,7 @@ public void onCreate(Bundle savedInstanceState) { String stringres = sticky.text; String position = sticky.position; color = sticky.color; + assert (color != null); Spanned plainText = Html.fromHtml(stringres); EditText editText = ((EditText) findViewById(R.id.bodyView)); editText.setText(plainText); @@ -114,7 +118,7 @@ private void ResetColors() { bodyView.setBackgroundColor(Color.TRANSPARENT); bodyView.setTextColor(Color.BLACK); (findViewById(R.id.scrollView)).setBackgroundColor(color.colorCode); - realColor = color.id; + //realColor = color.id; invalidateOptionsMenu(); } @@ -129,7 +133,13 @@ public boolean onPrepareOptionsMenu(@NonNull Menu menu) { super.onPrepareOptionsMenu(menu); //depending on your conditions, either enable/disable item.setVisible(usesticky); - menu.findItem(realColor).setChecked(true); + Log.d(TAG, "color.id: " + Integer.toString(color.id)); + Log.d(TAG, "mfi: " + (menu.findItem(color.id) == null)); + if (BuildConfig.DEBUG && (color == null)) { + throw new AssertionError("color is null"); + } + ; + menu.findItem(color.id).setChecked(true); return true; } @@ -156,6 +166,7 @@ public boolean onOptionsItemSelected(@NonNull MenuItem item) { case R.id.green: item.setChecked(true); color = Colors.fromId(itemId); + assert (color != null); (findViewById(R.id.scrollView)).setBackgroundColor(color.colorCode); return true; default: @@ -170,6 +181,7 @@ private void Save() { intent.putExtra(Listactivity.EDIT_ITEM_TXT, Html.toHtml(((EditText) findViewById(R.id.bodyView)).getText())); if (!usesticky) { + Log.d(TAG, "not sticky so set color to none"); color = Colors.NONE; } intent.putExtra(Listactivity.EDIT_ITEM_COLOR, color); @@ -187,14 +199,13 @@ public enum Colors { YELLOW(R.id.yellow, 0xFFFFFFCC), PINK(R.id.pink, 0xFFFFCCCC), GREEN(R.id.green, 0xFFCCFFCC), - // Is NONE ever used? - NONE(0, 0); + NONE(R.id.white, 0xFFFFFFFF); public final int id; public final int colorCode; - private Colors(int id, - int colorCode) { + Colors(int id, + int colorCode) { this.id = id; this.colorCode = colorCode; } @@ -214,15 +225,15 @@ public static Colors fromId(int id) { private Sticky GetInfoFromMessage(@NonNull Message message) { ContentType contentType = null; String stringres = null; - InputStream iis = null; + //InputStream iis = null; //Colors color = NONE; - String charset; + //String charset; Sticky sticky = null; try { //Log.d(TAG, "Contenttype as string:"+message.getContentType()); contentType = new ContentType(message.getContentType()); - charset = contentType.getParameter("charset"); - iis = (InputStream) message.getContent(); + String charset = contentType.getParameter("charset"); + InputStream iis = (InputStream) message.getContent(); stringres = IOUtils.toString(iis, charset); } catch (Exception e) { // TODO Auto-generated catch block From e7050a24fb784f32de294e70168e6d8aa96f6d5c Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Sat, 12 Nov 2016 17:53:34 +0100 Subject: [PATCH 035/103] Added Utilities class. Only members so far are to define the internal date format. --- .../java/com/Pau/ImapNotes2/Data/NotesDb.java | 8 ++++---- .../java/com/Pau/ImapNotes2/Miscs/Sticky.java | 1 - .../Pau/ImapNotes2/Miscs/UpdateThread.java | 3 ++- .../com/Pau/ImapNotes2/Miscs/Utilities.java | 19 +++++++++++++++++++ .../Pau/ImapNotes2/NoteDetailActivity.java | 2 -- .../com/Pau/ImapNotes2/NotesListAdapter.java | 2 +- .../com/Pau/ImapNotes2/Sync/SyncUtils.java | 10 +++++----- ImapNote2/src/main/res/layout/new_note.xml | 4 +++- ImapNote2/src/main/res/layout/note_detail.xml | 4 +++- 9 files changed, 37 insertions(+), 16 deletions(-) create mode 100644 ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Utilities.java diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java index 2034f471..2ae50ed7 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java @@ -2,11 +2,11 @@ import java.text.DateFormat; import java.text.ParseException; -import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import com.Pau.ImapNotes2.Miscs.OneNote; +import com.Pau.ImapNotes2.Miscs.Utilities; import android.content.ContentValues; import android.content.Context; @@ -105,10 +105,10 @@ public void GetStoredNotes(@NonNull ArrayList noteList, String accountn int positionIndex = resultPointer.getColumnIndex("position"); int colorIndex = resultPointer.getColumnIndex("color"); do { - String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; - SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); + //String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; + //SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT, Locale.ROOT); try { - date = sdf.parse(resultPointer.getString(dateIndex)); + date = Utilities.internalDateFormat.parse(resultPointer.getString(dateIndex)); } catch (ParseException e) { // TODO: Exception handling } catch (Exception e) { diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Sticky.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Sticky.java index 16321617..2508a489 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Sticky.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Sticky.java @@ -14,7 +14,6 @@ public class Sticky { public Sticky(String text, String position, @NonNull Colors color) { - assert (color != null); this.text = text; this.position = position; this.color = color; diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java index 4ed6b4c0..62b8d119 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java @@ -8,6 +8,7 @@ import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; +import java.util.Locale; import java.util.Properties; import java.util.UUID; @@ -117,7 +118,7 @@ protected Boolean doInBackground(Object... stuffs) { String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; Date date = new Date(); - SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); + SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT, Locale.ROOT); String stringDate = sdf.format(date); OneNote currentNote = new OneNote(title, stringDate, ""); // Add note to database diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Utilities.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Utilities.java new file mode 100644 index 00000000..903b0565 --- /dev/null +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Utilities.java @@ -0,0 +1,19 @@ +package com.Pau.ImapNotes2.Miscs; + +import java.text.SimpleDateFormat; +import java.util.Locale; + +/** + * Created by kj on 2016-11-12 17:21. + *

+ * Reduce repetition by providing static fields and methods for common operations. + */ +public class Utilities { + + /** + * The notes have a time stamp associated with thme and this is stored as a string on the + * server so we must define a fixed format for it. + */ + public static String internalDateFormatString = "yyyy-MM-dd HH:mm:ss"; + public static SimpleDateFormat internalDateFormat = new SimpleDateFormat(internalDateFormatString, Locale.ROOT); +} diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java index 7e1f4c55..d0d78bcb 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java @@ -78,7 +78,6 @@ public void onCreate(Bundle savedInstanceState) { String stringres = sticky.text; String position = sticky.position; color = sticky.color; - assert (color != null); Spanned plainText = Html.fromHtml(stringres); EditText editText = ((EditText) findViewById(R.id.bodyView)); editText.setText(plainText); @@ -166,7 +165,6 @@ public boolean onOptionsItemSelected(@NonNull MenuItem item) { case R.id.green: item.setChecked(true); color = Colors.fromId(itemId); - assert (color != null); (findViewById(R.id.scrollView)).setBackgroundColor(color.colorCode); return true; default: diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java index e15d96bf..e2d7409c 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java @@ -219,7 +219,7 @@ private void bindView(int position, @NonNull View view) { * Returns the {@link ViewBinder} used to bind data to views. * * @return a ViewBinder or null if the binder does not exist - * @see #getViewBinder(android.widget.SimpleAdapter.ViewBinder) + * @see #getViewBinder() */ public ViewBinder getViewBinder() { return mViewBinder; diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java index 5d611017..22d8292b 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java @@ -12,6 +12,7 @@ import com.Pau.ImapNotes2.Miscs.Imaper; import com.Pau.ImapNotes2.Miscs.OneNote; import com.Pau.ImapNotes2.Miscs.Sticky; +import com.Pau.ImapNotes2.Miscs.Utilities; import com.sun.mail.imap.AppendUID; import com.sun.mail.imap.IMAPFolder; import com.sun.mail.imap.IMAPStore; @@ -27,7 +28,6 @@ import java.io.InputStream; import java.io.OutputStream; import java.security.GeneralSecurityException; -import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Properties; @@ -407,7 +407,7 @@ private static void GetOneNote(@NonNull File outfile, @NonNull Message notesMess } // Get INTERNALDATE - String internaldate = null; + //String internaldate = null; Date MessageInternaldate = null; try { MessageInternaldate = notesMessage.getReceivedDate(); @@ -415,9 +415,9 @@ private static void GetOneNote(@NonNull File outfile, @NonNull Message notesMess // TODO Auto-generated catch block e.printStackTrace(); } - String DATE_FORMAT = "yyyy-MM-dd HH:MM:ss"; - SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); - internaldate = sdf.format(MessageInternaldate); + //String DATE_FORMAT = "yyyy-MM-dd HH:MM:ss"; + //SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT, Locale.ROOT); + String internaldate = Utilities.internalDateFormat.format(MessageInternaldate); OneNote aNote = new OneNote( title, diff --git a/ImapNote2/src/main/res/layout/new_note.xml b/ImapNote2/src/main/res/layout/new_note.xml index 92967916..6efe8100 100644 --- a/ImapNote2/src/main/res/layout/new_note.xml +++ b/ImapNote2/src/main/res/layout/new_note.xml @@ -1,5 +1,6 @@ @@ -14,7 +15,8 @@ android:layout_width="fill_parent" android:layout_height="fill_parent" android:ems="10" - android:inputType="textMultiLine"> + android:inputType="textMultiLine" + tools:ignore="LabelFor"> diff --git a/ImapNote2/src/main/res/layout/note_detail.xml b/ImapNote2/src/main/res/layout/note_detail.xml index 6f353155..c661e93b 100644 --- a/ImapNote2/src/main/res/layout/note_detail.xml +++ b/ImapNote2/src/main/res/layout/note_detail.xml @@ -2,6 +2,7 @@ + android:onClick="onClick" + tools:ignore="LabelFor"> From 1078b434f9b2b64213b34283ce66e03133817fad Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Sat, 12 Nov 2016 19:42:15 +0100 Subject: [PATCH 036/103] Use try with resource to ensure that cursors are closed after use. --- .../java/com/Pau/ImapNotes2/Data/NotesDb.java | 70 ++++++++++--------- .../com/Pau/ImapNotes2/Miscs/Utilities.java | 2 +- 2 files changed, 38 insertions(+), 34 deletions(-) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java index 2ae50ed7..2caf3bdb 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java @@ -76,18 +76,20 @@ public String GetDate(String uid, String accountname) { TODO: use date class. */ String selectQuery = "select date from notesTable where number = '" + uid + "' and accountname='" + accountname + "'"; - Cursor c = this.notesDb.rawQuery(selectQuery, null); - if (c.moveToFirst()) { - return c.getString(0); + try (Cursor c = this.notesDb.rawQuery(selectQuery, null)) { + if (c.moveToFirst()) { + return c.getString(0); + } } return ""; } public String GetTempNumber(String accountname) { String selectQuery = "select case when cast(max(abs(number)+1) as int) > 0 then cast(max(abs(number)+1) as int)*-1 else '-1' end from notesTable where number < '0' and accountname='" + accountname + "'"; - Cursor c = this.notesDb.rawQuery(selectQuery, null); - if (c.moveToFirst()) { - return c.getString(0); + try (Cursor c = this.notesDb.rawQuery(selectQuery, null)) { + if (c.moveToFirst()) { + return c.getString(0); + } } return "-1"; } @@ -95,33 +97,35 @@ public String GetTempNumber(String accountname) { public void GetStoredNotes(@NonNull ArrayList noteList, String accountname) { noteList.clear(); Date date = null; - Cursor resultPointer = this.notesDb.query("notesTable", null, "accountname = ?", new String[]{accountname}, null, null, "date DESC"); - - if (resultPointer.moveToFirst()) { - int titleIndex = resultPointer.getColumnIndex("title"); - int bodyIndex = resultPointer.getColumnIndex("body"); - int dateIndex = resultPointer.getColumnIndex("date"); - int numberIndex = resultPointer.getColumnIndex("number"); - int positionIndex = resultPointer.getColumnIndex("position"); - int colorIndex = resultPointer.getColumnIndex("color"); - do { - //String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; - //SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT, Locale.ROOT); - try { - date = Utilities.internalDateFormat.parse(resultPointer.getString(dateIndex)); - } catch (ParseException e) { - // TODO: Exception handling - } catch (Exception e) { - // TODO: handle exception - } - DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(this.ctx); - //String sdate = dateFormat.format(date); - String sdate = DateFormat.getDateTimeInstance().format(date); - - noteList.add(new OneNote(resultPointer.getString(titleIndex), - sdate, - resultPointer.getString(numberIndex))); - } while (resultPointer.moveToNext()); + try (Cursor resultPointer = this.notesDb.query("notesTable", null, "accountname = ?", + new String[]{accountname}, null, null, "date DESC")) { + + if (resultPointer.moveToFirst()) { + int titleIndex = resultPointer.getColumnIndex("title"); + int bodyIndex = resultPointer.getColumnIndex("body"); + int dateIndex = resultPointer.getColumnIndex("date"); + int numberIndex = resultPointer.getColumnIndex("number"); + int positionIndex = resultPointer.getColumnIndex("position"); + int colorIndex = resultPointer.getColumnIndex("color"); + do { + //String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; + //SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT, Locale.ROOT); + try { + date = Utilities.internalDateFormat.parse(resultPointer.getString(dateIndex)); + } catch (ParseException e) { + // TODO: Exception handling + } catch (Exception e) { + // TODO: handle exception + } + DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(this.ctx); + //String sdate = dateFormat.format(date); + String sdate = DateFormat.getDateTimeInstance().format(date); + + noteList.add(new OneNote(resultPointer.getString(titleIndex), + sdate, + resultPointer.getString(numberIndex))); + } while (resultPointer.moveToNext()); + } } } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Utilities.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Utilities.java index 903b0565..72239205 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Utilities.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Utilities.java @@ -14,6 +14,6 @@ public class Utilities { * The notes have a time stamp associated with thme and this is stored as a string on the * server so we must define a fixed format for it. */ - public static String internalDateFormatString = "yyyy-MM-dd HH:mm:ss"; + private static String internalDateFormatString = "yyyy-MM-dd HH:mm:ss"; public static SimpleDateFormat internalDateFormat = new SimpleDateFormat(internalDateFormatString, Locale.ROOT); } From 0c3c427da7a558d4f0dcf9aece4ec2928daca4e4 Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Sat, 12 Nov 2016 20:02:47 +0100 Subject: [PATCH 037/103] No more warnings in NotesDb! --- .../java/com/Pau/ImapNotes2/Data/NotesDb.java | 22 +++++++++---------- 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java index 2caf3bdb..7d35a47b 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java @@ -14,12 +14,12 @@ import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.support.annotation.NonNull; +import android.util.Log; public class NotesDb { private static final int NOTES_VERSION = 3; private static final String TAG = "IN_NotesDb"; - private final Context ctx; private static final String CREATE_NOTES_DB = "CREATE TABLE IF NOT EXISTS " + "notesTable (" @@ -35,7 +35,6 @@ public class NotesDb { public NotesDb(Context applicationContext) { this.defaultHelper = new NotesDbHelper(applicationContext, "NotesDb", NOTES_VERSION); - this.ctx = applicationContext; } @@ -94,30 +93,29 @@ public String GetTempNumber(String accountname) { return "-1"; } - public void GetStoredNotes(@NonNull ArrayList noteList, String accountname) { + public void GetStoredNotes(@NonNull ArrayList noteList, + @NonNull String accountName) { noteList.clear(); Date date = null; try (Cursor resultPointer = this.notesDb.query("notesTable", null, "accountname = ?", - new String[]{accountname}, null, null, "date DESC")) { + new String[]{accountName}, null, null, "date DESC")) { if (resultPointer.moveToFirst()) { int titleIndex = resultPointer.getColumnIndex("title"); - int bodyIndex = resultPointer.getColumnIndex("body"); + //int bodyIndex = resultPointer.getColumnIndex("body"); int dateIndex = resultPointer.getColumnIndex("date"); int numberIndex = resultPointer.getColumnIndex("number"); - int positionIndex = resultPointer.getColumnIndex("position"); - int colorIndex = resultPointer.getColumnIndex("color"); + //int positionIndex = resultPointer.getColumnIndex("position"); + //int colorIndex = resultPointer.getColumnIndex("color"); do { //String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; //SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT, Locale.ROOT); try { date = Utilities.internalDateFormat.parse(resultPointer.getString(dateIndex)); } catch (ParseException e) { - // TODO: Exception handling - } catch (Exception e) { - // TODO: handle exception + Log.d(TAG, "Parsing data from database failed: " + e.getMessage()); } - DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(this.ctx); + //DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(this.ctx); //String sdate = dateFormat.format(date); String sdate = DateFormat.getDateTimeInstance().format(date); @@ -141,7 +139,7 @@ public void ClearDb(String accountname) { private static class NotesDbHelper extends SQLiteOpenHelper { - public NotesDbHelper(Context currentApplicationContext, String dbName, int dbVersion) { + NotesDbHelper(Context currentApplicationContext, String dbName, int dbVersion) { super(currentApplicationContext, dbName, null, dbVersion); } From c791e3477dfdb390123596727f9d5d76d3c9d838 Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Sat, 12 Nov 2016 20:07:19 +0100 Subject: [PATCH 038/103] Only unused method warnings left in NotesListAdapter. --- .../main/java/com/Pau/ImapNotes2/NotesListAdapter.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java index e2d7409c..96c6b089 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java @@ -86,8 +86,8 @@ public class NotesListAdapter extends BaseAdapter implements Filterable { * TextViews. The first N views in this list are given the values of the first N columns * in the from parameter. */ - public NotesListAdapter(@NonNull Context context, List> data, - int resource, String[] from, int[] to) { + NotesListAdapter(@NonNull Context context, List> data, + int resource, String[] from, int[] to) { mData = data; mResource = mDropDownResource = resource; mFrom = from; @@ -221,7 +221,7 @@ private void bindView(int position, @NonNull View view) { * @return a ViewBinder or null if the binder does not exist * @see #getViewBinder() */ - public ViewBinder getViewBinder() { + private ViewBinder getViewBinder() { return mViewBinder; } @@ -307,7 +307,7 @@ public Filter getFilter() { * @see SimpleAdapter#setViewImage(ImageView, String) * @see SimpleAdapter#setViewText(TextView, String) */ - public interface ViewBinder { + interface ViewBinder { /** * Binds the specified data to the specified view. *

From d36fec2f1b17055292f6abe7d85fdeaf9af87165 Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Sat, 12 Nov 2016 20:30:28 +0100 Subject: [PATCH 039/103] Almost all warning fixed in UpdateThread. --- .../java/com/Pau/ImapNotes2/Listactivity.java | 2 +- .../Pau/ImapNotes2/Miscs/UpdateThread.java | 23 +++++++++++-------- 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java index 6537b10d..0558207a 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java @@ -258,7 +258,7 @@ private void UpdateList(String suid, String action) { ProgressDialog loadingDialog = ProgressDialog.show(this, "imapnote2", "Updating notes list... ", true); - new UpdateThread(this.imapFolder, Listactivity.imapNotes2Account, this.noteList, + new UpdateThread(Listactivity.imapNotes2Account, this.noteList, this.listToView, loadingDialog, suid, noteBody, color, this.getApplicationContext(), action, storedNotes).execute(); diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java index 62b8d119..cdd30d73 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java @@ -51,8 +51,7 @@ public class UpdateThread extends AsyncTask { Assign all fields in the constructor because we never reuse this object. This makes the code typesafe. Make them final to preven accidental reuse. */ - public UpdateThread(Imaper imapFolder, - ImapNotes2Account imapNotes2Account, + public UpdateThread(ImapNotes2Account imapNotes2Account, ArrayList noteList, NotesListAdapter listToView, ProgressDialog loadingDialog, @@ -111,7 +110,7 @@ protected Boolean doInBackground(Object... stuffs) { String noteTxt = Html.fromHtml(noteBody).toString(); String[] tok = noteTxt.split("\n", 2); String title = tok[0]; - String position = "0 0 0 0"; + //String position = "0 0 0 0"; String body = (imapNotes2Account.GetUsesticky()) ? noteTxt.replaceAll("\n", "\\\\n") : "" + noteBody + ""; @@ -133,7 +132,7 @@ protected Boolean doInBackground(Object... stuffs) { storedNotes.InsertANoteInDb(currentNote, Listactivity.imapNotes2Account.GetAccountname()); storedNotes.CloseDb(); // Add note to noteList but chage date format before - DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(ctx); + //DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(ctx); String sdate = DateFormat.getDateTimeInstance().format(date); currentNote.SetDate(sdate); notesList.add(0, currentNote); @@ -165,15 +164,19 @@ private int getIndexByNumber(String pNumber) { } private void MoveMailToDeleted(@NonNull String suid) { - String directory = (ImapNotes2k.getAppContext()).getFilesDir() + "/" + + String directory = ImapNotes2k.getAppContext().getFilesDir() + "/" + Listactivity.imapNotes2Account.GetAccountname(); - String positiveUid = suid.substring(1); + // TODO: Explain why we need to omit the first character of the UID File from = new File(directory, suid); - File to = new File(directory + "/deleted/" + suid); if (!from.exists()) { + String positiveUid = suid.substring(1); from = new File(directory + "/new", positiveUid); + // TODO: Explain why it is safe to ignore the result of delete. from.delete(); } else { + File to = new File(directory + "/deleted/" + suid); + // TODO: Explain why it is safe to ignore the result of rename. + //noinspection ResultOfMethodCallIgnored from.renameTo(to); } } @@ -181,7 +184,7 @@ private void MoveMailToDeleted(@NonNull String suid) { private void WriteMailToNew(@NonNull OneNote note, boolean usesticky, String noteBody) throws MessagingException, IOException { - String body = null; + //String body = null; // Here we add the new note to the "new" folder //Log.d(TAG,"Add new note"); @@ -189,7 +192,7 @@ private void WriteMailToNew(@NonNull OneNote note, Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); if (usesticky) { - body = "BEGIN:STICKYNOTE\nCOLOR:" + color.name() + "\nTEXT:" + noteBody + + String body = "BEGIN:STICKYNOTE\nCOLOR:" + color.name() + "\nTEXT:" + noteBody + "\nPOSITION:0 0 0 0\nEND:STICKYNOTE"; message.setText(body); message.setHeader("Content-Transfer-Encoding", "8bit"); @@ -198,7 +201,7 @@ private void WriteMailToNew(@NonNull OneNote note, message.setHeader("X-Uniform-Type-Identifier", "com.apple.mail-note"); UUID uuid = UUID.randomUUID(); message.setHeader("X-Universally-Unique-Identifier", uuid.toString()); - body = noteBody; + String body = noteBody; body = body.replaceFirst("

", "

"); body = body.replaceFirst("

", "

"); body = body.replaceAll("

", "


"); From 57abe43dc378b8b2e89c91afdd479c1f41667a5a Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Sun, 13 Nov 2016 12:49:37 +0100 Subject: [PATCH 040/103] Made StubProvider package local. Added TODO reminder to find out what it is for. Marked methods as @Nullable because they return null. --- .../java/com/Pau/ImapNotes2/NoteDetailActivity.java | 7 +++---- .../java/com/Pau/ImapNotes2/Sync/StubProvider.java | 10 ++++++++-- .../main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java | 5 ++++- 3 files changed, 15 insertions(+), 7 deletions(-) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java index d0d78bcb..5bb60d4e 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java @@ -6,7 +6,6 @@ import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; -import android.support.v4.*; import android.support.v4.BuildConfig; import android.support.v4.app.NavUtils; import android.text.Editable; @@ -76,7 +75,7 @@ public void onCreate(Bundle savedInstanceState) { Message message = SyncUtils.ReadMailFromFile(suid, ROOT_AND_NEW, true, rootDir); Sticky sticky = GetInfoFromMessage(message); String stringres = sticky.text; - String position = sticky.position; + //String position = sticky.position; color = sticky.color; Spanned plainText = Html.fromHtml(stringres); EditText editText = ((EditText) findViewById(R.id.bodyView)); @@ -92,12 +91,12 @@ public void onTextChanged(CharSequence s, int start, int before, int count) { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { - // TODO Auto-generated method stub + // TODO Work in progess } @Override public void afterTextChanged(Editable s) { - // TODO Auto-generated method stub + // TODO Work in progess } }); diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/StubProvider.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/StubProvider.java index 0725eb41..71830c0f 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/StubProvider.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/StubProvider.java @@ -5,12 +5,15 @@ import android.database.Cursor; import android.net.Uri; import android.support.annotation.NonNull; +import android.support.annotation.Nullable; /* * Define an implementation of ContentProvider that stubs out - * all methods + * all methods. + * + * TODO: Find out what this is for and explain it in the comments. */ -public class StubProvider extends ContentProvider { +class StubProvider extends ContentProvider { /* * Always return true, indicating that the * provider loaded correctly. @@ -22,6 +25,7 @@ public boolean onCreate() { /* * Return no type for MIME type */ + @Nullable @Override public String getType(@NonNull Uri uri) { return null; @@ -30,6 +34,7 @@ public String getType(@NonNull Uri uri) { * query() always returns no results * */ + @Nullable @Override public Cursor query( @NonNull Uri uri, @@ -42,6 +47,7 @@ public Cursor query( /* * insert() always returns null (no URI) */ + @Nullable @Override public Uri insert(@NonNull Uri uri, ContentValues values) { return null; diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java index 22d8292b..4a8303e7 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java @@ -278,7 +278,10 @@ public static void DisconnectFromRemote() { } @Nullable - public static Message ReadMailFromFile(@NonNull String uid, int where, boolean removeMinus, String nameDir) { + public static Message ReadMailFromFile(@NonNull String uid, + int where, + boolean removeMinus, + String nameDir) { File mailFile; Message message = null; mailFile = new File(nameDir, uid); From b21a81100018132652272205aa679770b2b83815 Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Sun, 13 Nov 2016 19:49:17 +0100 Subject: [PATCH 041/103] AndroidDomInspection suppressed, --- ImapNote2/src/main/AndroidManifest.xml | 10 +++++++--- .../Pau/ImapNotes2/Data/ConfigurationFieldNames.java | 2 +- .../java/com/Pau/ImapNotes2/Sync/StubProvider.java | 4 ++-- ImapNote2/src/main/res/layout/note_element.xml | 4 ++-- 4 files changed, 12 insertions(+), 8 deletions(-) diff --git a/ImapNote2/src/main/AndroidManifest.xml b/ImapNote2/src/main/AndroidManifest.xml index 59057e82..dc7aa809 100644 --- a/ImapNote2/src/main/AndroidManifest.xml +++ b/ImapNote2/src/main/AndroidManifest.xml @@ -4,8 +4,9 @@ android:versionCode="40" android:versionName="4.9"> - - + @@ -81,7 +82,10 @@ android:resource="@xml/authenticator" /> - + + + android:textColor="#000000" + android:maxLines="1" /> Date: Sun, 13 Nov 2016 20:20:32 +0100 Subject: [PATCH 042/103] Most literal strings have now been replaced with string resources. --- .../java/com/Pau/ImapNotes2/Listactivity.java | 2 +- .../src/main/res/layout/account_selection.xml | 30 +++++++++---------- ImapNote2/src/main/res/layout/main.xml | 4 +-- .../src/main/res/layout/note_element.xml | 2 +- ImapNote2/src/main/res/menu/detail.xml | 14 ++++----- ImapNote2/src/main/res/values/strings.xml | 26 ++++++++++++++++ 6 files changed, 52 insertions(+), 26 deletions(-) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java index 0558207a..38869264 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java @@ -535,7 +535,7 @@ public void SendLogcatMail() { private static void TriggerSync(@NonNull TextView statusField) { OldStatus = statusField.getText().toString(); - statusField.setText("Syncing..."); + statusField.setText(R.string.syncing); Account mAccount = Listactivity.imapNotes2Account.GetAccount(); Bundle settingsBundle = new Bundle(); settingsBundle.putBoolean( diff --git a/ImapNote2/src/main/res/layout/account_selection.xml b/ImapNote2/src/main/res/layout/account_selection.xml index dd161ad2..996d7221 100644 --- a/ImapNote2/src/main/res/layout/account_selection.xml +++ b/ImapNote2/src/main/res/layout/account_selection.xml @@ -15,7 +15,7 @@ android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="10dip" - android:text="Add Account" + android:text="@string/add_account" android:textAppearance="?android:attr/textAppearanceLarge" android:textColor="#000000" /> @@ -23,7 +23,7 @@ android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" - android:text="Accountname" + android:text="@string/account_name" android:textAppearance="?android:attr/textAppearanceMedium" android:textColor="#000000" /> @@ -32,7 +32,7 @@ android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginBottom="5dip" - android:hint="Choose a name for this account" + android:hint="@string/choose_a_name_for_this_account" android:inputType="textEmailAddress"> @@ -42,7 +42,7 @@ android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" - android:text="Username" + android:text="@string/username" android:textAppearance="?android:attr/textAppearanceMedium" android:textColor="#000000" /> @@ -51,14 +51,14 @@ android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginBottom="5dip" - android:hint="your login" + android:hint="@string/your_login_name" android:inputType="textEmailAddress" /> @@ -66,14 +66,14 @@ android:id="@+id/passwordEdit" android:layout_width="fill_parent" android:layout_height="wrap_content" - android:hint="your password" + android:hint="@string/your_password" android:inputType="textPassword" /> @@ -82,7 +82,7 @@ android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginBottom="5dip" - android:hint="imap notes server" + android:hint="@string/imap_notes_server" android:inputType="textNoSuggestions|text|textVisiblePassword" /> @@ -120,7 +120,7 @@ android:id="@+id/textView7" android:layout_width="wrap_content" android:layout_height="wrap_content" - android:text="Sync Interval (minutes)" + android:text="@string/sync_interval_minutes" android:textAppearance="?android:attr/textAppearanceMedium" android:textColor="#000000" /> @@ -130,7 +130,7 @@ android:layout_height="wrap_content" android:layout_marginBottom="5dip" android:ems="10" - android:hint="sync interval for this account (in minutes)" + android:hint="@string/sync_interval_for_this_account_in_minutes" android:inputType="number" android:text="15" android:textColor="#000000"> @@ -141,7 +141,7 @@ android:id="@+id/folderText" android:layout_width="wrap_content" android:layout_height="wrap_content" - android:text="Notes Folder (optional)" + android:text="@string/notes_folder_optional" android:textAppearance="?android:attr/textAppearanceMedium" android:textColor="#000000" /> @@ -150,14 +150,14 @@ android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="5dip" - android:hint="manually set full imap path to notes folder" + android:hint="@string/manually_set_full_imap_path_to_notes_folder" android:textColor="#000000" /> + android:text="@string/use_sticky_notes" /> + - - - - - diff --git a/ImapNote2/src/main/res/layout/note_detail.xml b/ImapNote2/src/main/res/layout/note_detail.xml index ad826d0d..6839c967 100644 --- a/ImapNote2/src/main/res/layout/note_detail.xml +++ b/ImapNote2/src/main/res/layout/note_detail.xml @@ -19,6 +19,7 @@ android:layout_height="fill_parent" android:clickable="true" android:gravity="top" + android:inputType="textMultiLine" tools:ignore="LabelFor"> From 8a42b03942e6c9a59d195d2c41353b2270f70127 Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Mon, 19 Dec 2016 10:57:02 +0100 Subject: [PATCH 080/103] Implemented Chris Graham's heading change for edit account but added string resource. --- .../com/Pau/ImapNotes2/AccountConfigurationActivity.java | 7 +++++-- ImapNote2/src/main/res/layout/account_selection.xml | 4 ++-- ImapNote2/src/main/res/values/strings.xml | 1 + 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java index 12e9181f..119b3625 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java @@ -43,6 +43,7 @@ public class AccountConfigurationActivity extends AccountAuthenticatorActivity i private Imaper imapFolder; + private TextView headingTextView; private TextView accountnameTextView; private TextView usernameTextView; private TextView passwordTextView; @@ -114,7 +115,7 @@ private void CheckNameAndLogIn() { private final OnClickListener clickListenerRemove = new View.OnClickListener() { @Override public void onClick(View v) { - // Clic on Remove Button + // Click on Remove Button accountManager.removeAccount(myAccount, null, null); Toast.makeText(getApplicationContext(), R.string.account_removed, Toast.LENGTH_LONG).show(); @@ -128,6 +129,7 @@ public void onCreate(Bundle savedInstanceState) { setContentView(R.layout.account_selection); //noinspection ConstantConditions getActionBar().setDisplayHomeAsUpEnabled(true); + headingTextView = (TextView) (findViewById(R.id.heading)); accountnameTextView = (TextView) (findViewById(R.id.accountnameEdit)); usernameTextView = (TextView) findViewById(R.id.usernameEdit); passwordTextView = (TextView) findViewById(R.id.passwordEdit); @@ -185,7 +187,7 @@ public void onCreate(Bundle savedInstanceState) { folderTextView.setText(settings.GetFoldername()); //} - LinearLayout layout = (LinearLayout) findViewById(R.id.bttonsLayout); + LinearLayout layout = (LinearLayout) findViewById(R.id.buttonsLayout); accountManager = AccountManager.get(getApplicationContext()); Account[] accounts = accountManager.getAccountsByType("com.Pau.ImapNotes2"); for (Account account : accounts) { @@ -202,6 +204,7 @@ public void onCreate(Bundle savedInstanceState) { if (action == Actions.EDIT_ACCOUNT) { // Here we have to edit an existing account + headingTextView.setText(R.string.editAccount); accountnameTextView.setText(accountname); usernameTextView.setText(GetConfigValue(ConfigurationFieldNames.UserName)); passwordTextView.setText(accountManager.getPassword(myAccount)); diff --git a/ImapNote2/src/main/res/layout/account_selection.xml b/ImapNote2/src/main/res/layout/account_selection.xml index 996d7221..a6ff3d2d 100644 --- a/ImapNote2/src/main/res/layout/account_selection.xml +++ b/ImapNote2/src/main/res/layout/account_selection.xml @@ -11,7 +11,7 @@ android:orientation="vertical"> --> diff --git a/ImapNote2/src/main/res/values/strings.xml b/ImapNote2/src/main/res/values/strings.xml index 74f0549c..f8130d0e 100644 --- a/ImapNote2/src/main/res/values/strings.xml +++ b/ImapNote2/src/main/res/values/strings.xml @@ -43,4 +43,5 @@ "Refreshing notes list... " "Updating notes list... " 15 + Edit Account From 56e0e1a36a4f8dca80a81f564df65e1cc916f768 Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Mon, 19 Dec 2016 11:07:50 +0100 Subject: [PATCH 081/103] Implemented Chris Graham's confirmation dialog for deletion. Once we have the vector clocks and history we can remove this an allow the user to retrieve old versions instead. --- .../Pau/ImapNotes2/NoteDetailActivity.java | 21 ++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java index 58060185..87d651fe 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java @@ -1,6 +1,8 @@ package com.Pau.ImapNotes2; import android.app.Activity; +import android.app.AlertDialog; +import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; @@ -144,14 +146,23 @@ public boolean onPrepareOptionsMenu(@NonNull Menu menu) { } public boolean onOptionsItemSelected(@NonNull MenuItem item) { - Intent intent = new Intent(); + final Intent intent = new Intent(); int itemId = item.getItemId(); switch (itemId) { case R.id.delete: - //Log.d(TAG,"We ask to delete Message #"+currentNote.get("number")); - intent.putExtra(Listactivity.DELETE_ITEM_NUM_IMAP, suid); - setResult(Listactivity.DELETE_BUTTON, intent); - finish();//finishing activity + new AlertDialog.Builder(this) + .setTitle("Delete note") + .setMessage("Are you sure you wish to delete the note?") + .setIcon(android.R.drawable.ic_dialog_alert) + .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int whichButton) { + //Log.d(TAG,"We ask to delete Message #"+this.currentNote.get("number")); + intent.putExtra("DELETE_ITEM_NUM_IMAP", suid); + setResult(Listactivity.DELETE_BUTTON, intent); + finish();//finishing activity + } + }) + .setNegativeButton(android.R.string.no, null).show(); return true; case R.id.save: Save(); From 3aee097dcc6db51a04f636c1b007e76992ba9899 Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Mon, 19 Dec 2016 11:13:35 +0100 Subject: [PATCH 082/103] Implemented Chris Graham's clarification "Select account" -> "Select account to view or edit" --- ImapNote2/src/main/res/values-nb/strings.xml | 2 +- ImapNote2/src/main/res/values/strings.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/ImapNote2/src/main/res/values-nb/strings.xml b/ImapNote2/src/main/res/values-nb/strings.xml index a7fa8b72..66e32256 100644 --- a/ImapNote2/src/main/res/values-nb/strings.xml +++ b/ImapNote2/src/main/res/values-nb/strings.xml @@ -8,7 +8,7 @@ Fjerne Lagre søḳ - Velg konto + Velg konto til aa se eller rediger Ny Synkronisering.. Brukernavn diff --git a/ImapNote2/src/main/res/values/strings.xml b/ImapNote2/src/main/res/values/strings.xml index f8130d0e..c6cd774b 100644 --- a/ImapNote2/src/main/res/values/strings.xml +++ b/ImapNote2/src/main/res/values/strings.xml @@ -30,7 +30,7 @@ Manually set full IMAP path to notes folder Use Sticky Notes Welcome - Select account + Select account to view or edit Note Title Delete Color From 7db8d0b9cdaf2e491fa5015852ac806566987ca4 Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Mon, 19 Dec 2016 11:26:13 +0100 Subject: [PATCH 083/103] Implemented Chris Graham's clarification autosync on save. --- .../src/main/java/com/Pau/ImapNotes2/Listactivity.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java index c8820628..8abfa793 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java @@ -137,7 +137,7 @@ public void onCreate(Bundle savedInstanceState) { Listactivity.accountManager.addOnAccountsUpdatedListener( new AccountsUpdateListener(), null, true); - //TextView status = (TextView) findViewById(R.id.status); + final TextView status = (TextView) findViewById(R.id.status); this.spinnerList = new ArrayAdapter<> (this, android.R.layout.simple_spinner_item, Listactivity.currentList); @@ -170,6 +170,8 @@ public void onItemClick(@NonNull AdapterView parent, @NonNull View widget, in toDetail.putExtra(NoteDetailActivity.selectedNote, (OneNote) parent.getItemAtPosition(selectedNote)); toDetail.putExtra(NoteDetailActivity.useSticky, Listactivity.imapNotes2Account.GetUsesticky()); startActivityForResult(toDetail, SEE_DETAIL); + + TriggerSync(status); } }); @@ -362,9 +364,11 @@ protected void onActivityResult(int requestCode, int resultCode, @NonNull Intent String txt = data.getStringExtra(EDIT_ITEM_TXT); String suid = data.getStringExtra(EDIT_ITEM_NUM_IMAP); Colors color = (Colors) data.getSerializableExtra(EDIT_ITEM_COLOR); - //Log.d(TAG,"Received request to delete message:"+suid); + //Log.d(TAG,"Received request to edit message:"+suid); //Log.d(TAG,"Received request to replace message with:"+txt); this.UpdateList(suid, txt, color, UpdateThread.Action.Update); + TextView status = (TextView) findViewById(R.id.status); + TriggerSync(status); } case Listactivity.NEW_BUTTON: // Returning from NewNoteActivity From 189af9e0d47fde027327e7c06564c1820b0aad78 Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Mon, 19 Dec 2016 11:33:11 +0100 Subject: [PATCH 084/103] Implemented Chris Graham's corection for height. --- ImapNote2/src/main/res/layout/note_element.xml | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/ImapNote2/src/main/res/layout/note_element.xml b/ImapNote2/src/main/res/layout/note_element.xml index 4f141066..38c06e9c 100644 --- a/ImapNote2/src/main/res/layout/note_element.xml +++ b/ImapNote2/src/main/res/layout/note_element.xml @@ -10,23 +10,24 @@ + android:scrollHorizontally="false"> + + /> From 13b688bd0f1f8c1e4fa13bdca78436a0cee34f14 Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Mon, 19 Dec 2016 11:34:11 +0100 Subject: [PATCH 085/103] Use maxLines=1 instead of singleLine. --- ImapNote2/src/main/res/layout/note_element.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ImapNote2/src/main/res/layout/note_element.xml b/ImapNote2/src/main/res/layout/note_element.xml index 38c06e9c..dea1fa4a 100644 --- a/ImapNote2/src/main/res/layout/note_element.xml +++ b/ImapNote2/src/main/res/layout/note_element.xml @@ -14,9 +14,9 @@ android:textAppearance="?android:attr/textAppearanceLarge" android:layout_width="wrap_content" android:layout_height="wrap_content" - android:singleLine="true" android:layout_marginRight="40dp" - android:scrollHorizontally="false"> + android:scrollHorizontally="false" + android:maxLines="1"> From b3e8797ceda7c4867f9dc5598db17f3b404c7756 Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Thu, 29 Dec 2016 10:49:03 +0100 Subject: [PATCH 086/103] Fixed null reference error caused by over enthusiastic refactoring. --- .../AccountConfigurationActivity.java | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java index 119b3625..bd648cef 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java @@ -36,6 +36,10 @@ import java.util.List; + + + + public class AccountConfigurationActivity extends AccountAuthenticatorActivity implements OnItemSelectedListener { private static final int TO_REFRESH = 999; private static final String AUTHORITY = "com.Pau.ImapNotes2.provider"; @@ -43,7 +47,6 @@ public class AccountConfigurationActivity extends AccountAuthenticatorActivity i private Imaper imapFolder; - private TextView headingTextView; private TextView accountnameTextView; private TextView usernameTextView; private TextView passwordTextView; @@ -62,13 +65,17 @@ public class AccountConfigurationActivity extends AccountAuthenticatorActivity i private Actions action; @Nullable private String accountname; - @NonNull - private final ConfigurationFile settings = new ConfigurationFile(getApplicationContext()); - @Nullable private static Account myAccount = null; + private static AccountManager accountManager; + /** + * Cannot be final or NonNull because it needs the application context which is not available + * until onCreate. + */ + private ConfigurationFile settings; + //region Intent item names and values. public static final String ACTION = "ACTION"; public static final String ACCOUNTNAME = "ACCOUNTNAME"; @@ -126,10 +133,11 @@ public void onClick(View v) { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); + settings = new ConfigurationFile(getApplicationContext()); setContentView(R.layout.account_selection); //noinspection ConstantConditions getActionBar().setDisplayHomeAsUpEnabled(true); - headingTextView = (TextView) (findViewById(R.id.heading)); + TextView headingTextView = (TextView) (findViewById(R.id.heading)); accountnameTextView = (TextView) (findViewById(R.id.accountnameEdit)); usernameTextView = (TextView) findViewById(R.id.usernameEdit); passwordTextView = (TextView) findViewById(R.id.passwordEdit); From 854d9f121ecc16ff89a6cf579e4496cf5f458926 Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Thu, 29 Dec 2016 20:20:04 +0100 Subject: [PATCH 087/103] Now using wasabeef rich editor in a branch, --- ImapNote2/build.gradle | 3 +++ .../Pau/ImapNotes2/Data/MergeMessages.java | 21 ++++++++++++++++++ .../java/com/Pau/ImapNotes2/Listactivity.java | 14 +++++++----- .../Pau/ImapNotes2/NoteDetailActivity.java | 22 ++++++++++++------- .../com/Pau/ImapNotes2/Sync/SyncUtils.java | 3 ++- ImapNote2/src/main/res/layout/note_detail.xml | 13 +++++++++-- notes.org | 4 +++- 7 files changed, 62 insertions(+), 18 deletions(-) create mode 100644 ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/MergeMessages.java diff --git a/ImapNote2/build.gradle b/ImapNote2/build.gradle index 507999d3..9bb66417 100644 --- a/ImapNote2/build.gradle +++ b/ImapNote2/build.gradle @@ -29,4 +29,7 @@ dependencies { compile files('libs/commons-io-2.4.jar') compile files('libs/javamaildir-0.6.jar') compile files('libs/mail.jar') + compile 'jdiff:jdiff:1.0.9' + compile 'jp.wasabeef:richeditor-android:1.2.1' + } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/MergeMessages.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/MergeMessages.java new file mode 100644 index 00000000..ca658949 --- /dev/null +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/MergeMessages.java @@ -0,0 +1,21 @@ +package com.Pau.ImapNotes2.Data; + +/** + * Created by kj on 12/25/16. + + + This class contains methods to fetch ancestors, current versions, etc., and do a three way merge using jdiff. + + */ +public class MergeMessages { + + + /** + * Figure out if there is a conflict, if so fetch the current and ancestor and merge with the local file. Replace + * the local file with the merged version. + * @param id This is the subject line of the message. + */ + MergeMessages(String id) { + + } +} diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java index 8abfa793..a11504a8 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java @@ -99,7 +99,7 @@ public class Listactivity extends Activity implements OnItemSelectedListener, Fi private static Account[] accounts = new Account[0]; private static List currentList; //@Nullable - //private TextView status; + private TextView status; private static String OldStatus; private static final String AUTHORITY = "com.Pau.ImapNotes2.provider"; private static final String TAG = "IN_Listactivity"; @@ -137,7 +137,7 @@ public void onCreate(Bundle savedInstanceState) { Listactivity.accountManager.addOnAccountsUpdatedListener( new AccountsUpdateListener(), null, true); - final TextView status = (TextView) findViewById(R.id.status); + status = (TextView) findViewById(R.id.status); this.spinnerList = new ArrayAdapter<> (this, android.R.layout.simple_spinner_item, Listactivity.currentList); @@ -211,10 +211,12 @@ protected void onPause() { @NonNull private final BroadcastReceiver syncFinishedReceiver = new BroadcastReceiver() { public void onReceive(Context context, @NonNull Intent intent) { + Log.d(TAG, "BroadcastReceiver.onReceive"); String accountName = intent.getStringExtra(ACCOUNTNAME); Boolean isChanged = intent.getBooleanExtra(CHANGED, false); Boolean isSynced = intent.getBooleanExtra(SYNCED, false); String syncInterval = intent.getStringExtra(SYNCINTERVAL); + Log.d(TAG, "if " + accountName + " " + Listactivity.imapNotes2Account.GetAccountName()); if (accountName.equals(Listactivity.imapNotes2Account.GetAccountName())) { String statusText; if (isSynced) { @@ -228,7 +230,7 @@ public void onReceive(Context context, @NonNull Intent intent) { } else { statusText = OldStatus; } - TextView status = (TextView) findViewById(R.id.status); + //TextView status = (TextView) findViewById(R.id.status); status.setText(statusText); if (isChanged) { @@ -251,7 +253,7 @@ private void RefreshList() { ShowProgress(R.string.refreshing_notes_list), storedNotes, this.getApplicationContext()).execute(); - TextView status = (TextView) findViewById(R.id.status); + //TextView status = (TextView) findViewById(R.id.status); status.setText(R.string.welcome); } @@ -317,7 +319,7 @@ public boolean onOptionsItemSelected(@NonNull MenuItem item) { startActivity(res); return true; case R.id.refresh: - TextView status = (TextView) findViewById(R.id.status); + //TextView status = (TextView) findViewById(R.id.status); TriggerSync(status); return true; case R.id.newnote: @@ -367,7 +369,7 @@ protected void onActivityResult(int requestCode, int resultCode, @NonNull Intent //Log.d(TAG,"Received request to edit message:"+suid); //Log.d(TAG,"Received request to replace message with:"+txt); this.UpdateList(suid, txt, color, UpdateThread.Action.Update); - TextView status = (TextView) findViewById(R.id.status); + //TextView status = (TextView) findViewById(R.id.status); TriggerSync(status); } case Listactivity.NEW_BUTTON: diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java index 87d651fe..0aef8e13 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java @@ -4,21 +4,17 @@ import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; -import android.graphics.Color; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.BuildConfig; import android.support.v4.app.NavUtils; -import android.text.Editable; import android.text.Html; import android.text.Spanned; -import android.text.TextWatcher; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.WindowManager; -import android.widget.EditText; import com.Pau.ImapNotes2.Miscs.Sticky; import com.Pau.ImapNotes2.Sync.SyncUtils; @@ -32,6 +28,7 @@ import javax.mail.Message; import javax.mail.internet.ContentType; +import jp.wasabeef.richeditor.RichEditor; public class NoteDetailActivity extends Activity { @@ -77,9 +74,12 @@ public void onCreate(Bundle savedInstanceState) { //String position = sticky.position; color = sticky.color; Spanned plainText = Html.fromHtml(stringres); - EditText editText = ((EditText) findViewById(R.id.bodyView)); - editText.setText(plainText); - // TODO: Watch for changes to that we can auto save. + //EditText editText = ((EditText) findViewById(R.id.bodyView)); + RichEditor editText = (RichEditor) findViewById(R.id.bodyView); + //editText.setText(plainText); + editText.setHtml(stringres); + +/* // TODO: Watch for changes to that we can auto save. // See http://stackoverflow.com/questions/7117209/how-to-know-key-presses-in-edittext#14251047 editText.addTextChangedListener(new TextWatcher() { @Override @@ -99,6 +99,7 @@ public void afterTextChanged(Editable s) { } }); + */ ResetColors(); //invalidateOptionsMenu(); } @@ -116,9 +117,11 @@ public void onClick(View view) { // realColor is misnamed. It is the ID of the radio button widget that chooses the background // colour. private void ResetColors() { +/* EditText bodyView = (EditText) findViewById(R.id.bodyView); bodyView.setBackgroundColor(Color.TRANSPARENT); bodyView.setTextColor(Color.BLACK); +*/ (findViewById(R.id.scrollView)).setBackgroundColor(color.colorCode); //realColor = color.id; invalidateOptionsMenu(); @@ -188,8 +191,11 @@ private void Save() { Log.d(TAG, "Save"); Intent intent = new Intent(); intent.putExtra(Listactivity.EDIT_ITEM_NUM_IMAP, suid); - intent.putExtra(Listactivity.EDIT_ITEM_TXT, + /*intent.putExtra(Listactivity.EDIT_ITEM_TXT, Html.toHtml(((EditText) findViewById(R.id.bodyView)).getText())); + */ + intent.putExtra(Listactivity.EDIT_ITEM_TXT, + ((RichEditor) findViewById(R.id.bodyView)).getHtml()); if (!usesticky) { Log.d(TAG, "not sticky so set color to none"); color = Colors.NONE; diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java index 5cfdf91e..b2d18003 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java @@ -26,6 +26,7 @@ import java.io.InputStream; import java.io.OutputStream; import java.security.GeneralSecurityException; +import java.text.DateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Properties; @@ -640,7 +641,7 @@ static boolean handleRemoteNotes(@NonNull Context context, result = true; } else if (usesticky.equals("true")) { //Log.d (TAG,"MANAGE STICKY"); - remoteInternaldate = notesMessage.getSentDate().toLocaleString(); + remoteInternaldate = DateFormat.getDateInstance().format(notesMessage.getSentDate()); localInternaldate = storedNotes.GetDate(suid, accountName); if (!(remoteInternaldate.equals(localInternaldate))) { File outfile = new File(rootDir, suid); diff --git a/ImapNote2/src/main/res/layout/note_detail.xml b/ImapNote2/src/main/res/layout/note_detail.xml index 6839c967..1fbfdcf8 100644 --- a/ImapNote2/src/main/res/layout/note_detail.xml +++ b/ImapNote2/src/main/res/layout/note_detail.xml @@ -2,7 +2,6 @@ + + + + diff --git a/notes.org b/notes.org index 84ae5460..52445038 100644 --- a/notes.org +++ b/notes.org @@ -102,10 +102,12 @@ server. We can avoid worrying about race conditions by recognizing that this is essentially a single user system so simultaneous access will be -unlikely (not impossible though) +unlikely (not impossible though). https://gist.github.com/stepchowfun/4713315 +See: http://www.qarks.com/web/en/downloads.html + * Sync adapters From 0497694173d7fc317135ec7bc55bd0479559c436 Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Wed, 4 Jan 2017 20:38:37 +0100 Subject: [PATCH 088/103] Now using wasabeef rich editor in master. Seems to work so far. Need to get rid of the Sticky note stuff as it no longer makes sense. --- .../com/Pau/ImapNotes2/Data/Security.java | 2 +- .../java/com/Pau/ImapNotes2/Listactivity.java | 11 +- .../Pau/ImapNotes2/Miscs/UpdateThread.java | 11 +- .../Pau/ImapNotes2/NoteDetailActivity.java | 202 +++++++++++++- .../com/Pau/ImapNotes2/Sync/SyncAdapter.java | 11 +- .../com/Pau/ImapNotes2/Sync/SyncUtils.java | 16 ++ ImapNote2/src/main/res/layout/note_detail.xml | 261 ++++++++++++++++++ ImapNote2/src/main/res/layout/rich_editor.xml | 244 ++++++++++++++++ 8 files changed, 747 insertions(+), 11 deletions(-) create mode 100644 ImapNote2/src/main/res/layout/rich_editor.xml diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/Security.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/Security.java index 4575a812..2b6d06dd 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/Security.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/Security.java @@ -31,7 +31,7 @@ public enum Security { STARTTLS_accept_all_certificates("STARTTLS (accept all certificates)", "143", "imaps", true); @NonNull - static final String TAG = "In_Security"; + static final String TAG = "IN_Security"; public final String proto; public final boolean acceptcrt; diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java index a11504a8..29c314e5 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java @@ -125,6 +125,7 @@ public void onClick(View v) { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); + Log.d(TAG, "onCreate"); setContentView(R.layout.main); this.accountSpinner = (Spinner) findViewById(R.id.accountSpinner); @@ -165,13 +166,18 @@ public void onCreate(Bundle savedInstanceState) { // When item is clicked, we go to NoteDetailActivity listview.setOnItemClickListener(new OnItemClickListener() { - public void onItemClick(@NonNull AdapterView parent, @NonNull View widget, int selectedNote, long rowId) { + public void onItemClick(@NonNull AdapterView parent, + @NonNull View widget, + int selectedNote, + long rowId) { + Log.d(TAG, "onItemClick"); Intent toDetail = new Intent(widget.getContext(), NoteDetailActivity.class); toDetail.putExtra(NoteDetailActivity.selectedNote, (OneNote) parent.getItemAtPosition(selectedNote)); toDetail.putExtra(NoteDetailActivity.useSticky, Listactivity.imapNotes2Account.GetUsesticky()); startActivityForResult(toDetail, SEE_DETAIL); + Log.d(TAG, "onItemClick, back from detail."); - TriggerSync(status); + //TriggerSync(status); } }); @@ -353,6 +359,7 @@ public void onClick(DialogInterface dialog, int which) { } protected void onActivityResult(int requestCode, int resultCode, @NonNull Intent data) { + Log.d(TAG, "onActivityResult: " + requestCode + " " + resultCode); switch (requestCode) { case Listactivity.SEE_DETAIL: // Returning from NoteDetailActivity diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java index cbd43652..8b8f8605 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java @@ -4,7 +4,6 @@ import android.content.Context; import android.os.AsyncTask; import android.support.annotation.NonNull; -import android.text.Html; import android.util.Log; import com.Pau.ImapNotes2.Data.ImapNotes2Account; @@ -68,7 +67,7 @@ public UpdateThread(ImapNotes2Account imapNotes2Account, Context applicationContext, Action action, NotesDb storedNotes) { - + Log.d(TAG, "UpdateThread: " + noteBody); this.imapNotes2Account = imapNotes2Account; this.notesList = noteList; this.adapter = listToView; @@ -102,8 +101,10 @@ protected Boolean doInBackground(Object... stuffs) { if ((action == Action.Insert) || (action == Action.Update)) { //Log.d(TAG,"Sticky ? "+((ImapNotes2Account)stuffs[1]).GetUsesticky()); //Log.d(TAG,"Color:"+color); - //Log.d(TAG,"Received request to add new message"+noteBody+"==="); - String noteTxt = Html.fromHtml(noteBody).toString(); + Log.d(TAG,"Received request to add new message: " + noteBody + "==="); + //String noteTxt = Html.fromHtml(noteBody).toString(); + String noteTxt = noteBody; + Log.d(TAG,"noteTxt: " + noteTxt + "==="); String[] tok = noteTxt.split("\n", 2); String title = tok[0]; //String position = "0 0 0 0"; @@ -123,6 +124,7 @@ protected Boolean doInBackground(Object... stuffs) { currentNote.SetUid(suid); // Here we ask to add the new note to the new note folder // Must be done AFTER uid has been set in currenteNote + Log.d(TAG, "doInBackground body: " + body); WriteMailToNew(currentNote, imapNotes2Account.GetUsesticky(), body); storedNotes.InsertANoteInDb(currentNote, Listactivity.imapNotes2Account.GetAccountName()); @@ -185,6 +187,7 @@ private void MoveMailToDeleted(@NonNull String suid) { private void WriteMailToNew(@NonNull OneNote note, boolean usesticky, String noteBody) throws MessagingException, IOException { + Log.d(TAG, "WriteMailToNew: " + noteBody); //String body = null; // Here we add the new note to the new note folder diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java index 0aef8e13..fbb52ad3 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java @@ -4,6 +4,7 @@ import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; +import android.graphics.Color; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; @@ -14,6 +15,7 @@ import android.util.Log; import android.view.Menu; import android.view.MenuItem; +import android.view.View; import android.view.WindowManager; import com.Pau.ImapNotes2.Miscs.Sticky; @@ -43,6 +45,9 @@ public class NoteDetailActivity extends Activity { // --Commented out by Inspection (11/26/16 11:52 PM):private final static int ROOT_AND_NEW = 3; private static final String TAG = "IN_NoteDetailActivity"; + + private RichEditor editText; + //region Intent item names public static final String useSticky = "useSticky"; public static final String selectedNote = "selectedNote"; @@ -75,11 +80,12 @@ public void onCreate(Bundle savedInstanceState) { color = sticky.color; Spanned plainText = Html.fromHtml(stringres); //EditText editText = ((EditText) findViewById(R.id.bodyView)); - RichEditor editText = (RichEditor) findViewById(R.id.bodyView); + editText = (RichEditor) findViewById(R.id.bodyView); //editText.setText(plainText); + SetupRichEditor(editText); editText.setHtml(stringres); -/* // TODO: Watch for changes to that we can auto save. +/* // TODO: Watch for changes so that we can auto save. // See http://stackoverflow.com/questions/7117209/how-to-know-key-presses-in-edittext#14251047 editText.addTextChangedListener(new TextWatcher() { @Override @@ -105,6 +111,197 @@ public void afterTextChanged(Editable s) { } + + void SetupRichEditor(final RichEditor mEditor) { + //mEditor = (RichEditor) findViewById(R.id.editor); + //mEditor.setEditorHeight(200); + //mEditor.setEditorFontSize(22); + mEditor.setEditorFontColor(Color.RED); + //mEditor.setEditorBackgroundColor(Color.BLUE); + //mEditor.setBackgroundColor(Color.BLUE); + //mEditor.setBackgroundResource(R.drawable.bg); + mEditor.setPadding(10, 10, 10, 10); + // mEditor.setBackground("https://raw.githubusercontent.com/wasabeef/art/master/chip.jpg"); + mEditor.setPlaceholder("Insert text here..."); + +/* + mPreview = (TextView) findViewById(R.id.preview); + mEditor.setOnTextChangeListener(new RichEditor.OnTextChangeListener() { + @Override public void onTextChange(String text) { + mPreview.setText(text); + } + }); + +*/ + findViewById(R.id.action_undo).setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + mEditor.undo(); + } + }); + + findViewById(R.id.action_redo).setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + mEditor.redo(); + } + }); + + findViewById(R.id.action_bold).setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + mEditor.setBold(); + } + }); + + findViewById(R.id.action_italic).setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + mEditor.setItalic(); + } + }); + + findViewById(R.id.action_subscript).setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + mEditor.setSubscript(); + } + }); + + findViewById(R.id.action_superscript).setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + mEditor.setSuperscript(); + } + }); + + findViewById(R.id.action_strikethrough).setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + mEditor.setStrikeThrough(); + } + }); + + findViewById(R.id.action_underline).setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + mEditor.setUnderline(); + } + }); + + findViewById(R.id.action_heading1).setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + mEditor.setHeading(1); + } + }); + + findViewById(R.id.action_heading2).setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + mEditor.setHeading(2); + } + }); + + findViewById(R.id.action_heading3).setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + mEditor.setHeading(3); + } + }); + + findViewById(R.id.action_heading4).setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + mEditor.setHeading(4); + } + }); + + findViewById(R.id.action_heading5).setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + mEditor.setHeading(5); + } + }); + + findViewById(R.id.action_heading6).setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + mEditor.setHeading(6); + } + }); + + findViewById(R.id.action_txt_color).setOnClickListener(new View.OnClickListener() { + private boolean isChanged; + + @Override public void onClick(View v) { + mEditor.setTextColor(isChanged ? Color.BLACK : Color.RED); + isChanged = !isChanged; + } + }); + + findViewById(R.id.action_bg_color).setOnClickListener(new View.OnClickListener() { + private boolean isChanged; + + @Override public void onClick(View v) { + mEditor.setTextBackgroundColor(isChanged ? Color.TRANSPARENT : Color.YELLOW); + isChanged = !isChanged; + } + }); + + findViewById(R.id.action_indent).setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + mEditor.setIndent(); + } + }); + + findViewById(R.id.action_outdent).setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + mEditor.setOutdent(); + } + }); + + findViewById(R.id.action_align_left).setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + mEditor.setAlignLeft(); + } + }); + + findViewById(R.id.action_align_center).setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + mEditor.setAlignCenter(); + } + }); + + findViewById(R.id.action_align_right).setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + mEditor.setAlignRight(); + } + }); + + findViewById(R.id.action_blockquote).setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + mEditor.setBlockquote(); + } + }); + + findViewById(R.id.action_insert_bullets).setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + mEditor.setBullets(); + } + }); + + findViewById(R.id.action_insert_numbers).setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + mEditor.setNumbers(); + } + }); + + findViewById(R.id.action_insert_image).setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + mEditor.insertImage("http://www.1honeywan.com/dachshund/image/7.21/7.21_3_thumb.JPG", + "dachshund"); + } + }); + + findViewById(R.id.action_insert_link).setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + mEditor.insertLink("https://github.com/wasabeef", "wasabeef"); + } + }); + findViewById(R.id.action_insert_checkbox).setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + mEditor.insertTodo(); + } + }); + } + /* // TODO: delete this? public void onClick(View view) { @@ -194,6 +391,7 @@ private void Save() { /*intent.putExtra(Listactivity.EDIT_ITEM_TXT, Html.toHtml(((EditText) findViewById(R.id.bodyView)).getText())); */ + Log.d(TAG, "Save html: " + ((RichEditor) findViewById(R.id.bodyView)).getHtml()); intent.putExtra(Listactivity.EDIT_ITEM_TXT, ((RichEditor) findViewById(R.id.bodyView)).getHtml()); if (!usesticky) { diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java index d46ec1f3..5380d9a2 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java @@ -54,6 +54,8 @@ class SyncAdapter extends AbstractThreadedSyncAdapter { SyncAdapter(@NonNull Context applicationContext) { super(applicationContext, true); + Log.d(TAG, "SyncAdapter"); + //mContentResolver = applicationContext.getContentResolver(); // TODO: do we really need a copy of the applicationContext reference? this.applicationContext = applicationContext; @@ -85,7 +87,7 @@ public void onPerformSync(@NonNull Account accountArg, String authority, ContentProviderClient provider, SyncResult syncResult) { - //Log.d(TAG, "Beginning network synchronization of account: "+account.name); + Log.d(TAG, "Beginning network synchronization of account: " + accountArg.name); // TODO: should the account be static? Should it be local? If static then why do we not // provide it in the constructor? What happens if we allow parallel syncs? account = new ImapNotes2Account(accountArg, applicationContext); @@ -174,6 +176,7 @@ public void onPerformSync(@NonNull Account accountArg, private void NotifySyncFinished(boolean isChanged, boolean isSynced) { + Log.d(TAG, "NotifySyncFinished: " + isChanged + " " + isSynced); Intent i = new Intent(SyncService.SYNC_FINISHED); i.putExtra(Listactivity.ACCOUNTNAME, account.GetAccountName()); i.putExtra(Listactivity.CHANGED, isChanged); @@ -190,6 +193,7 @@ private void NotifySyncFinished(boolean isChanged, */ @NonNull private ImapNotes2Result ConnectToRemote() { + Log.d(TAG, "ConnectToRemote"); AccountManager am = AccountManager.get(applicationContext); ImapNotes2Result res = SyncUtils.ConnectToRemote( account.GetUsername(), @@ -207,6 +211,7 @@ private ImapNotes2Result ConnectToRemote() { } private boolean handleNewNotes() { + Log.d(TAG, "handleNewNotes"); //Message message = null; boolean newNotesManaged = false; //AppendUID[] uids = null; @@ -218,10 +223,11 @@ private boolean handleNewNotes() { Log.d(TAG, "dn exists: " + Boolean.toString(dirNew.exists())); String[] listOfNew = dirNew.list(); for (String fileNew : listOfNew) { - //Log.d(TAG,"New Note to process:"+fileNew); + Log.d(TAG,"New Note to process:"+fileNew); newNotesManaged = true; // Read local new message from file Message message = SyncUtils.ReadMailFromFileNew(fileNew, dirNew); + Log.d(TAG,"handleNewNotes message: " + message.toString()); try { message.setFlag(Flags.Flag.SEEN, true); // set message as seen } catch (MessagingException e) { @@ -251,6 +257,7 @@ private boolean handleNewNotes() { private boolean handleDeletedNotes() { //Message message = null; + Log.d(TAG, "handleDeletedNotes"); boolean deletedNotesManaged = false; String rootString = applicationContext.getFilesDir() + "/" + account.GetAccountName(); File rootDir = new File(rootString); diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java index b2d18003..fdeb3c38 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java @@ -66,6 +66,7 @@ static ImapNotes2Result ConnectToRemote(@NonNull String username, String portnum, @NonNull Security security, @NonNull String folderOverride) { + Log.d(TAG,"ConnectToRemote: " + username); if (IsConnected()) { try { store.close(); @@ -162,6 +163,7 @@ static void GetNotes(@NonNull Account account, @NonNull Folder imapNotesFolder, @NonNull Context applicationContext, @NonNull NotesDb storedNotes) throws MessagingException, IOException { + Log.d(TAG,"GetNotes: " + account.name); //Long UIDM; //Message notesMessage; File directory = new File(applicationContext.getFilesDir(), account.name); @@ -197,6 +199,7 @@ static void GetNotes(@NonNull Account account, @NonNull public static Sticky ReadStickyNote(@NonNull String stringres) { + Log.d(TAG,"ReadStickyNote"); /* Matcher matcherColor = patternColor.matcher(stringres); Colors color = Colors.NONE; @@ -272,6 +275,7 @@ private static boolean IsConnected() { } static void DeleteNote(int numMessage) throws MessagingException { + Log.d(TAG,"DeleteNote: " + numMessage); Folder notesFolder = store.getFolder(sfolder); if (notesFolder.isOpen()) { if ((notesFolder.getMode() & Folder.READ_WRITE) != 0) { @@ -291,6 +295,7 @@ static void DeleteNote(int numMessage) throws MessagingException { static void SetUIDValidity(@NonNull Account account, Long UIDValidity, @NonNull Context ctx) { + Log.d(TAG,"SetUIDValidity: " + account.name); SharedPreferences preferences = ctx.getSharedPreferences(account.name, Context.MODE_MULTI_PROCESS); SharedPreferences.Editor editor = preferences.edit(); editor.putString("Name", "valid_data"); @@ -302,6 +307,7 @@ static void SetUIDValidity(@NonNull Account account, // Retrieve values from shared preferences: static Long GetUIDValidity(@NonNull Account account, @NonNull Context ctx) { + Log.d(TAG,"GetUIDValidity: " + account.name); UIDValidity = (long) -1; SharedPreferences preferences = ctx.getSharedPreferences(account.name, Context.MODE_MULTI_PROCESS); String name = preferences.getString("Name", ""); @@ -313,6 +319,7 @@ static Long GetUIDValidity(@NonNull Account account, } static void DisconnectFromRemote() { + Log.d(TAG,"DisconnectFromRemote"); try { store.close(); } catch (MessagingException e) { @@ -387,6 +394,7 @@ public static Message ReadMailFromFile(@NonNull String uid, @Nullable static Message ReadMailFromFileNew(@NonNull String uid, @NonNull File newFilesDir) { + Log.d(TAG,"ReadMailFromFileNew"); //File mailFile; //Message message = null; //mailFile = new File(nameDir, uid); @@ -403,6 +411,7 @@ static Message ReadMailFromFileNew(@NonNull String uid, @Nullable public static Message ReadMailFromFileRootAndNew(@NonNull String uid, @NonNull File fileDir) { + Log.d(TAG,"ReadMailFromFileRootAndNew: " + fileDir.getPath() + " " + uid); //File mailFile; //Message message = null; File mailFile = new File(fileDir, uid); @@ -439,12 +448,14 @@ public static Message ReadMailFromFileRootAndNew(@NonNull String uid, @Nullable private static Message ReadMailFromFile(@NonNull File nameDir, @NonNull String uid) { + Log.d(TAG,"ReadMailFromFile: " + nameDir.getPath() + " " + uid); File mailFile = new File(nameDir, uid); try (InputStream mailFileInputStream = new FileInputStream(mailFile)) { try { Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); + Log.d(TAG, "ReadMailFromFile return new MimeMessage."); return new MimeMessage(session, mailFileInputStream); } catch (MessagingException e) { // TODO Auto-generated catch block @@ -460,6 +471,7 @@ private static Message ReadMailFromFile(@NonNull File nameDir, Log.d(TAG, "IO exception opening mailFile: " + mailFile.getAbsolutePath()); exIO.printStackTrace(); } + Log.d(TAG,"ReadMailFromFile return null."); return null; } @@ -510,6 +522,7 @@ public static void CreateLocalDirectories(@NonNull String accountName, @NonNull private static void SaveNote(@NonNull File outfile, @NonNull Message notesMessage) throws IOException, MessagingException { + Log.d(TAG,"SaveNote: " + outfile.getCanonicalPath()); try (OutputStream str = new FileOutputStream(outfile)) { notesMessage.writeTo(str); /* @@ -532,6 +545,7 @@ private static void SaveNoteAndUpdatDatabase(@NonNull File outfile, @NonNull NotesDb storedNotes, @NonNull String accountName, @NonNull String suid) throws IOException, MessagingException { + Log.d(TAG,"SaveNoteAndUpdatDatabase: " + outfile.getCanonicalPath() + " " + accountName); SaveNote(outfile, notesMessage); @@ -596,6 +610,7 @@ static boolean handleRemoteNotes(@NonNull Context context, @NonNull String accountName, @NonNull String usesticky) throws MessagingException, IOException { + Log.d(TAG,"handleRemoteNotes: " + notesFolder.getFullName() + " " + accountName + " " + usesticky); Message notesMessage; boolean result = false; @@ -669,6 +684,7 @@ static boolean handleRemoteNotes(@NonNull Context context, } static void RemoveAccount(@NonNull Context context, @NonNull Account account) { + Log.d(TAG,"RemoveAccount: " + account.name); // remove Shared Preference file String rootString = context.getFilesDir().getParent() + File.separator + "shared_prefs"; diff --git a/ImapNote2/src/main/res/layout/note_detail.xml b/ImapNote2/src/main/res/layout/note_detail.xml index 1fbfdcf8..7309d3e1 100644 --- a/ImapNote2/src/main/res/layout/note_detail.xml +++ b/ImapNote2/src/main/res/layout/note_detail.xml @@ -27,11 +27,272 @@ --> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ImapNote2/src/main/res/layout/rich_editor.xml b/ImapNote2/src/main/res/layout/rich_editor.xml new file mode 100644 index 00000000..7b5a8ee7 --- /dev/null +++ b/ImapNote2/src/main/res/layout/rich_editor.xml @@ -0,0 +1,244 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From f958582d9696aebf4ff7fc5f4bb1a791ce8c25b0 Mon Sep 17 00:00:00 2001 From: kwhitefoot Date: Wed, 18 Jan 2017 18:48:47 +0100 Subject: [PATCH 089/103] Now using wasabeef rich editor in master. Seems to work so far. Need to get rid of the Sticky note stuff as it no longer makes sense. Added flag for AutomaticMerge. This should probably be an enum together with the stickynotes because they are mutually exclusive. Added Db and associated classes as a container for the various classes representing tables because we now have two more tables to deal with to support the vector clocks. Moved NotesDbHelper to the new Db class. Added MakeMessageWithAttachment function to begin storing messages in attachments instead of inline this should simplify the business of handling composite documents. Added @NonNull to some argument lists. --- ImapNote2/build.gradle | 2 + .../AccountConfigurationActivity.java | 19 ++- .../Data/ConfigurationFieldNames.java | 1 + .../ImapNotes2/Data/ConfigurationFile.java | 16 +- .../main/java/com/Pau/ImapNotes2/Data/Db.java | 113 ++++++++++++++ .../ImapNotes2/Data/ImapNotes2Account.java | 15 +- .../com/Pau/ImapNotes2/Data/NoteVector.java | 76 ++++++++++ .../java/com/Pau/ImapNotes2/Data/NotesDb.java | 104 +++---------- .../com/Pau/ImapNotes2/Data/VectorDb.java | 141 ++++++++++++++++++ .../com/Pau/ImapNotes2/Data/VectorNote.java | 50 +++++++ .../java/com/Pau/ImapNotes2/ImapNotes2k.java | 6 +- .../java/com/Pau/ImapNotes2/Listactivity.java | 50 ++++--- .../com/Pau/ImapNotes2/Miscs/SyncThread.java | 12 +- .../Pau/ImapNotes2/Miscs/UpdateThread.java | 74 +++++++-- .../Pau/ImapNotes2/NoteDetailActivity.java | 9 +- .../com/Pau/ImapNotes2/Sync/SyncAdapter.java | 15 +- .../com/Pau/ImapNotes2/Sync/SyncUtils.java | 25 ++-- .../src/main/res/layout/account_selection.xml | 7 + ImapNote2/src/main/res/values-nb/strings.xml | 1 + synchronization.org | 93 ++++++++++++ 20 files changed, 679 insertions(+), 150 deletions(-) create mode 100644 ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/Db.java create mode 100644 ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NoteVector.java create mode 100644 ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/VectorDb.java create mode 100644 ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/VectorNote.java create mode 100644 synchronization.org diff --git a/ImapNote2/build.gradle b/ImapNote2/build.gradle index 9bb66417..d5110a81 100644 --- a/ImapNote2/build.gradle +++ b/ImapNote2/build.gradle @@ -4,6 +4,7 @@ android { compileSdkVersion 21 buildToolsVersion "23.0.3" + //noinspection GroovyMissingReturnStatement defaultConfig { applicationId "com.Pau.ImapNotes2" minSdkVersion 19 @@ -17,6 +18,7 @@ android { } } + //noinspection GroovyMissingReturnStatement packagingOptions { exclude 'META-INF/LICENSE.txt' } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java index bd648cef..ebd8a431 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java @@ -28,7 +28,6 @@ import android.widget.Toast; import com.Pau.ImapNotes2.Data.ConfigurationFieldNames; -import com.Pau.ImapNotes2.Data.ConfigurationFile; import com.Pau.ImapNotes2.Data.ImapNotes2Account; import com.Pau.ImapNotes2.Data.Security; import com.Pau.ImapNotes2.Miscs.ImapNotes2Result; @@ -55,6 +54,7 @@ public class AccountConfigurationActivity extends AccountAuthenticatorActivity i private TextView syncintervalTextView; private TextView folderTextView; private CheckBox stickyCheckBox; + private CheckBox automaticMergeCheckBox; private Spinner securitySpinner; // TODO: move this to dologin becauae it is the only use. private ImapNotes2Account imapNotes2Account; @@ -74,7 +74,7 @@ public class AccountConfigurationActivity extends AccountAuthenticatorActivity i * Cannot be final or NonNull because it needs the application context which is not available * until onCreate. */ - private ConfigurationFile settings; + //private ConfigurationFile settings; //region Intent item names and values. public static final String ACTION = "ACTION"; @@ -133,7 +133,7 @@ public void onClick(View v) { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - settings = new ConfigurationFile(getApplicationContext()); + //settings = new ConfigurationFile(getApplicationContext()); setContentView(R.layout.account_selection); //noinspection ConstantConditions getActionBar().setDisplayHomeAsUpEnabled(true); @@ -146,6 +146,7 @@ public void onCreate(Bundle savedInstanceState) { syncintervalTextView = (TextView) findViewById(R.id.syncintervalEdit); folderTextView = (TextView) findViewById(R.id.folderEdit); stickyCheckBox = (CheckBox) findViewById(R.id.stickyCheckBox); + automaticMergeCheckBox = (CheckBox) findViewById(R.id.automaticMergeCheckBox); securitySpinner = (Spinner) findViewById(R.id.securitySpinner); /*List list = new ArrayList(); @@ -181,6 +182,7 @@ public void onCreate(Bundle savedInstanceState) { // Settings can never be null so there is no need to guard it //if (settings != null) { +/* accountnameTextView.setText(settings.GetAccountname()); usernameTextView.setText(settings.GetUsername()); passwordTextView.setText(settings.GetPassword()); @@ -191,8 +193,10 @@ public void onCreate(Bundle savedInstanceState) { //int security_i = security.ordinal(); securitySpinner.setSelection(security.ordinal()); stickyCheckBox.setChecked(settings.GetUsesticky()); - syncintervalTextView.setText(R.string.default_sync_interval); + automaticMergeCheckBox.setChecked(settings.GetUseAutomaticMerge()); folderTextView.setText(settings.GetFoldername()); +*/ + syncintervalTextView.setText(R.string.default_sync_interval); //} LinearLayout layout = (LinearLayout) findViewById(R.id.buttonsLayout); @@ -221,6 +225,7 @@ public void onCreate(Bundle savedInstanceState) { Log.d(TAG, "Security: " + GetConfigValue(ConfigurationFieldNames.Security)); security = Security.from(GetConfigValue(ConfigurationFieldNames.Security)); stickyCheckBox.setChecked(Boolean.parseBoolean(GetConfigValue(ConfigurationFieldNames.UseSticky))); + automaticMergeCheckBox.setChecked(Boolean.parseBoolean(GetConfigValue(ConfigurationFieldNames.UseAutomaticMerge))); syncintervalTextView.setText(GetConfigValue(ConfigurationFieldNames.SyncInterval)); folderTextView.setText(GetConfigValue(ConfigurationFieldNames.ImapFolder)); //if (security == null) security = "0"; @@ -267,6 +272,7 @@ private void DoLogin() { imapNotes2Account.SetPortnum(GetTextViewText(portnumTextView)); imapNotes2Account.SetSecurity(security); imapNotes2Account.SetUsesticky(stickyCheckBox.isChecked()); + imapNotes2Account.SetUsesAutomaticMerge(automaticMergeCheckBox.isChecked()); imapNotes2Account.SetSyncinterval(GetTextViewText(syncintervalTextView)); imapNotes2Account.SetFoldername(GetTextViewText(folderTextView)); // No need to check for valid numbers because the field only allows digits. But it is @@ -291,6 +297,7 @@ class LoginThread extends AsyncTask { private final AccountConfigurationActivity accountConfigurationActivity; //@NonNull //private ImapNotes2Result res = new ImapNotes2Result(); + @NonNull private String statusMessage = ""; private final Actions action; @@ -383,7 +390,7 @@ protected Boolean doInBackground(Void... none) { return false; } - private void setUserData(AccountManager am, + private void setUserData(@NonNull AccountManager am, Account account) { am.setUserData(account, ConfigurationFieldNames.UserName, imapNotes2Account.GetUsername()); am.setUserData(account, ConfigurationFieldNames.Server, imapNotes2Account.GetServer()); @@ -396,7 +403,7 @@ private void setUserData(AccountManager am, protected void onPostExecute(Boolean result) { if (result) { - accountConfigurationActivity.settings.Clear(); + //accountConfigurationActivity.settings.Clear(); accountConfigurationActivity.accountnameTextView.setText(""); accountConfigurationActivity.usernameTextView.setText(""); accountConfigurationActivity.passwordTextView.setText(""); diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFieldNames.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFieldNames.java index ec539be9..6b769b22 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFieldNames.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFieldNames.java @@ -4,6 +4,7 @@ public final class ConfigurationFieldNames { public static final String UserName = "username"; static final String Password = "password"; public static final String UseSticky = "usesticky"; + public static final String UseAutomaticMerge = "UseAutomaticMerge"; public static final String ImapFolder = "imapfolder"; public static final String Server = "server"; public static final String PortNumber = "portnum"; diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFile.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFile.java index 63f9c55e..10b977b2 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFile.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFile.java @@ -41,6 +41,9 @@ public class ConfigurationFile { private Security security = Security.None; // ? private boolean usesticky; + + private boolean useAutomaticMerge; + // The name of the IMAP folder to be used. @Nullable private String imapfolder; @@ -71,10 +74,15 @@ public ConfigurationFile(@NonNull Context applicationContext) { } else { portnum = NodeValueFromXML(fileToLoad, ConfigurationFieldNames.PortNumber); } - // usesticky option doesn't exist, say no + usesticky = LoadItemFromXML(fileToLoad, ConfigurationFieldNames.UseSticky).getLength() != 0 && Boolean.parseBoolean(NodeValueFromXML(fileToLoad, ConfigurationFieldNames.UseSticky)); + // Automatic merge allows you to edit the same note on different devices at the same + // time an have the changes merged automatically. + useAutomaticMerge = LoadItemFromXML(fileToLoad, ConfigurationFieldNames.UseAutomaticMerge).getLength() != 0 && + Boolean.parseBoolean(NodeValueFromXML(fileToLoad, ConfigurationFieldNames.UseAutomaticMerge)); + //Log.d(TAG, "conf file present, we read data"); } catch (Exception e) { // TODO: This catch should be turned into a simple if then and the catch @@ -87,6 +95,7 @@ public ConfigurationFile(@NonNull Context applicationContext) { security = Security.None; portnum = security.defaultPort; usesticky = false; + useAutomaticMerge = false; imapfolder = ""; } } @@ -154,6 +163,10 @@ public void SetSecurity(Security security) { public boolean GetUsesticky() { return usesticky; } + + public boolean GetUseAutomaticMerge() { + return useAutomaticMerge; + } /* public void SetUsesticky(boolean usesticky) { @@ -176,6 +189,7 @@ public void Clear() { portnum = null; security = Security.None; usesticky = false; + useAutomaticMerge= false; imapfolder = null; } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/Db.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/Db.java new file mode 100644 index 00000000..f79c4f85 --- /dev/null +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/Db.java @@ -0,0 +1,113 @@ +package com.Pau.ImapNotes2.Data; + +import android.content.ContentValues; +import android.content.Context; +import android.database.sqlite.SQLiteDatabase; +import android.database.sqlite.SQLiteOpenHelper; +import android.support.annotation.NonNull; + +/** + * Created by kj on 2017-01-15 14:29. + */ + +public class Db { + + private static final String TAG = "IN_Db"; + + + SQLiteDatabase notesDb; + @NonNull + private final NotesDbHelper defaultHelper; + @NonNull + public final NotesDb notes; + @NonNull + public final VectorDb vectors; + + public Db(@NonNull Context applicationContext) { + this.defaultHelper = new NotesDbHelper(applicationContext); + notes = new NotesDb(this); + vectors = new VectorDb(this); + } + + + /** + * TODO: can we make this implement closeable? + */ + public void OpenDb() { + this.notesDb = this.defaultHelper.getWritableDatabase(); + + } + + public void CloseDb() { + this.notesDb.close(); + + } + + public void insert(@NonNull String table, + String nullColumnHack, + @NonNull ContentValues values) { + notesDb.insert(table, nullColumnHack, values); + } + + + /** + * Database helper that creates and maintains the SQLite database. + */ + + private class NotesDbHelper extends SQLiteOpenHelper { + + private static final int NOTES_VERSION = 3; + + private static final String DATABASE_NAME = "NotesDb"; + + + NotesDbHelper(@NonNull Context currentApplicationContext) { + super(currentApplicationContext, DATABASE_NAME, null, NOTES_VERSION); + } + + @Override + public void onCreate(@NonNull SQLiteDatabase _db) { + CreateNotesDb(_db); + } + + private void CreateNotesDb(@NonNull SQLiteDatabase _db) { + _db.execSQL(NotesDb.CREATE_NOTES_DB); + vectors.CreateTables(_db); + } + + @Override + public void onUpgrade(@NonNull SQLiteDatabase _db, + int oldVersion, + int newVersion) { + //Log.d(TAG,"onUpgrade from:"+oldVersion+" to:"+newVersion); + for (int i = oldVersion; i < newVersion; i++) { + PATCHES[i - 2].apply(_db); + } + } + + private class Patch { + public void apply(SQLiteDatabase _db) { + } + } + + private final Patch[] PATCHES = new Patch[]{ + new Patch() { + public void apply(@NonNull SQLiteDatabase _db) { + //Log.d(TAG,"upgrade: v2 to v3"); + _db.execSQL("Drop table notesTable;"); + CreateNotesDb(_db); + } + } +/* + ,new Patch() { + public void apply(SQLiteDatabase _db) { + Log.d(TAG,"upgrade: v3 to v4"); + _db.execSQL("Drop table notesTable;"); + _db.execSQL(NotesDb.CREATE_NOTES_DB); + } + } +*/ + }; + } + +} diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ImapNotes2Account.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ImapNotes2Account.java index baaf51ce..689685b0 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ImapNotes2Account.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ImapNotes2Account.java @@ -33,6 +33,7 @@ public class ImapNotes2Account { private String imapfolder = ""; @Nullable private Account account = null; + private boolean usesAutomaticMerge = false; public ImapNotes2Account() { @@ -45,7 +46,7 @@ public ImapNotes2Account() { private File rootDir; private ImapNotes2Account(@NonNull String accountName, - Context applicationContext) { + @NonNull Context applicationContext) { this.accountName = accountName; rootDir = new File(applicationContext.getFilesDir(), accountName); dirForNewFiles= new File(rootDir, "new"); @@ -53,7 +54,7 @@ private ImapNotes2Account(@NonNull String accountName, } public ImapNotes2Account(@NonNull Account account, - Context applicationContext) { + @NonNull Context applicationContext) { this(account.name, applicationContext); SetAccount(account, applicationContext); @@ -90,7 +91,7 @@ public String GetAccountName() { return accountName; } - public void SetAccount(Account account, + public void SetAccount(@NonNull Account account, Context applicationContext) { this.account = account; SetAccountname(account.name); @@ -206,6 +207,14 @@ public String GetFoldername() { public void SetFoldername(@NonNull String folder) { this.imapfolder = folder; } + + public boolean GetUsesAutomaticMerge() { + return this.usesAutomaticMerge; + } + public void SetUsesAutomaticMerge(boolean usesAutomaticMerge) { + this.usesAutomaticMerge = usesAutomaticMerge; + } + /* public void Clear() { this.username = null; diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NoteVector.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NoteVector.java new file mode 100644 index 00000000..6bc7475f --- /dev/null +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NoteVector.java @@ -0,0 +1,76 @@ +package com.Pau.ImapNotes2.Data; + +import android.support.annotation.NonNull; + +import java.util.HashMap; + +/** + * Created by kj on 2017-01-09 11:13. + */ + +public class NoteVector extends HashMap { + + enum ComparisonResult { + Later, + Equal, + Earlier, + Conflict; + } + + NoteVector() { + + } + + + /** + * @param deviceID + * @return Clock or zero if the deviceID is not found. + */ + int get(String deviceID) { + return containsKey(deviceID) + ? get(deviceID) + : 0; + } + + + // Returns EARLIER if this object is unambiguously earlier than other. + public ComparisonResult compareTo(@NonNull NoteVector other) { + ComparisonResult result = ComparisonResult.Equal; + for (Entry entry : this.entrySet()) { + Integer otherClock = other.get(entry.getKey()); + ComparisonResult singleResult = compareEntries(entry.getValue(), otherClock); + switch (result) { + case Equal: + result = singleResult; + break; + case Earlier: + if (singleResult == ComparisonResult.Later) { + return ComparisonResult.Conflict; + } + break; + case Later: + if (singleResult == ComparisonResult.Earlier) { + return ComparisonResult.Conflict; + } + case Conflict: + // cannot occur + break; + default: { + // Nothing to do, cannot occur. + } + } + } + return result; + } + + // Returns EARLIER if a is earlier than b. + public ComparisonResult compareEntries(@NonNull Integer aClock, + @NonNull Integer bClock) { + return (aClock < bClock) + ? ComparisonResult.Earlier + : ((bClock < aClock) + ? ComparisonResult.Later + : ComparisonResult.Equal); + } +} + diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java index 848cbb25..be08bb89 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java @@ -1,10 +1,7 @@ package com.Pau.ImapNotes2.Data; import android.content.ContentValues; -import android.content.Context; import android.database.Cursor; -import android.database.sqlite.SQLiteDatabase; -import android.database.sqlite.SQLiteOpenHelper; import android.support.annotation.NonNull; import android.util.Log; @@ -15,17 +12,16 @@ public class NotesDb { - private static final int NOTES_VERSION = 3; private static final String TAG = "IN_NotesDb"; + private static final String COL_TITLE = "title"; private static final String COL_DATE = "date"; private static final String COL_NUMBER = "number"; private static final String COL_ACCOUNT_NAME = "accountname"; private static final String TABLE_NAME = "notesTable"; - private static final String DATABASE_NAME = "NotesDb"; - private static final String CREATE_NOTES_DB = "CREATE TABLE IF NOT EXISTS " + public static final String CREATE_NOTES_DB = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (pk integer primary key autoincrement, " + COL_TITLE + " text not null, " @@ -33,25 +29,11 @@ public class NotesDb { + COL_NUMBER + " text not null, " + COL_ACCOUNT_NAME + " text not null);"; - private SQLiteDatabase notesDb; - @NonNull - private final NotesDbHelper defaultHelper; - - public NotesDb(Context applicationContext) { - this.defaultHelper = new NotesDbHelper(applicationContext); - - } - - /** - * TODO: can we make this implement closeable? - */ - public void OpenDb() { - this.notesDb = this.defaultHelper.getWritableDatabase(); - } + private final Db db; - public void CloseDb() { - this.notesDb.close(); + public NotesDb(@NonNull Db db) { + this.db = db; } @@ -62,28 +44,32 @@ public void InsertANoteInDb(@NonNull OneNote noteElement, tableRow.put(COL_DATE, noteElement.GetDate()); tableRow.put(COL_NUMBER, noteElement.GetUid()); tableRow.put(COL_ACCOUNT_NAME, accountname); - this.notesDb.insert(TABLE_NAME, null, tableRow); + db.insert(TABLE_NAME, null, tableRow); //Log.d(TAG, "note inserted"); } - public void DeleteANote(String number, String accountname) { - this.notesDb.execSQL("delete from notesTable where number = '" + number + + public void DeleteANote(@NonNull String number, + @NonNull String accountname) { + db.notesDb.execSQL("delete from notesTable where number = '" + number + "' and accountname = '" + accountname + "'"); } - public void UpdateANote(String olduid, String newuid, String accountname) { + public void UpdateANote(@NonNull String olduid, + @NonNull String newuid, + @NonNull String accountname) { /* TODO: use sql template and placeholders instead of string concatenation. */ String req = "update notesTable set number='" + newuid + "' where number='-" + olduid + "' and accountname='" + accountname + "'"; - this.notesDb.execSQL(req); + db.notesDb.execSQL(req); } - public String GetDate(String uid, String accountname) { + public String GetDate(@NonNull String uid, + @NonNull String accountname) { /* Returns a string representing the modification time of the note. TODO: use date class. */ String selectQuery = "select date from notesTable where number = '" + uid + "' and accountname='" + accountname + "'"; - try (Cursor c = this.notesDb.rawQuery(selectQuery, null)) { + try (Cursor c = db.notesDb.rawQuery(selectQuery, null)) { if (c.moveToFirst()) { return c.getString(0); } @@ -91,9 +77,9 @@ public String GetDate(String uid, String accountname) { return ""; } - public String GetTempNumber(String accountname) { + public String GetTempNumber(@NonNull String accountname) { String selectQuery = "select case when cast(max(abs(number)+1) as int) > 0 then cast(max(abs(number)+1) as int)*-1 else '-1' end from notesTable where number < '0' and accountname='" + accountname + "'"; - try (Cursor c = this.notesDb.rawQuery(selectQuery, null)) { + try (Cursor c = db.notesDb.rawQuery(selectQuery, null)) { if (c.moveToFirst()) { return c.getString(0); } @@ -105,7 +91,7 @@ public void GetStoredNotes(@NonNull ArrayList noteList, @NonNull String accountName) { noteList.clear(); Date date = null; - try (Cursor resultPointer = this.notesDb.query(TABLE_NAME, null, "accountname = ?", + try (Cursor resultPointer = db.notesDb.query(TABLE_NAME, null, "accountname = ?", new String[]{accountName}, null, null, "date DESC")) { if (resultPointer.moveToFirst()) { @@ -136,56 +122,8 @@ public void GetStoredNotes(@NonNull ArrayList noteList, } - public void ClearDb(String accountname) { - this.notesDb.execSQL("delete from notesTable where accountname = '" + accountname + "'"); + public void ClearDb(@NonNull String accountname) { + db.notesDb.execSQL("delete from notesTable where accountname = '" + accountname + "'"); } - - /** - * Database helper that creates and maintains the SQLite database. - */ - - private static class NotesDbHelper extends SQLiteOpenHelper { - - NotesDbHelper(Context currentApplicationContext) { - super(currentApplicationContext, NotesDb.DATABASE_NAME, null, NotesDb.NOTES_VERSION); - } - - @Override - public void onCreate(@NonNull SQLiteDatabase _db) { - _db.execSQL(NotesDb.CREATE_NOTES_DB); - } - - @Override - public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) { - //Log.d(TAG,"onUpgrade from:"+oldVersion+" to:"+newVersion); - for (int i = oldVersion; i < newVersion; i++) { - PATCHES[i - 2].apply(_db); - } - } - - private static class Patch { - public void apply(SQLiteDatabase _db) { - } - } - - private static final Patch[] PATCHES = new Patch[]{ - new Patch() { - public void apply(@NonNull SQLiteDatabase _db) { - //Log.d(TAG,"upgrade: v2 to v3"); - _db.execSQL("Drop table notesTable;"); - _db.execSQL(NotesDb.CREATE_NOTES_DB); - } - } -/* - ,new Patch() { - public void apply(SQLiteDatabase _db) { - Log.d(TAG,"upgrade: v3 to v4"); - _db.execSQL("Drop table notesTable;"); - _db.execSQL(NotesDb.CREATE_NOTES_DB); - } - } -*/ - }; - } } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/VectorDb.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/VectorDb.java new file mode 100644 index 00000000..60001b81 --- /dev/null +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/VectorDb.java @@ -0,0 +1,141 @@ +package com.Pau.ImapNotes2.Data; + +import android.content.ContentValues; +import android.database.Cursor; +import android.database.sqlite.SQLiteDatabase; +import android.support.annotation.NonNull; + +import java.io.File; + +/** + * Created by kj on 2017-01-09 10:28. + *

+ * This class manages the tables used for vector clocks and other data associated with automatic + * conflict resolution and merging. + */ + +class VectorDb { + + + private final Db db; + private final FileTable fileTable = new FileTable(); + private final VectorTable vectorTable = new VectorTable(); + + public VectorDb(@NonNull Db db) { + this.db = db; + + } + + public void CreateTables(@NonNull SQLiteDatabase db) { + fileTable.CreateTable(db); + vectorTable.CreateTable(db); + } + + + class VectorTable { + + private static final String TAG = "IN_FileTable"; + + private static final String COL_FILE_PATH = "filepath"; + private static final String COL_CLOCK= "clock"; + private static final String COL_ACCOUNT_NAME = "accountname"; + private static final String TABLE_NAME = "vector"; + //private static final String DATABASE_NAME = "NotesDb"; + + private static final String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS " + + TABLE_NAME + + COL_FILE_PATH + " text not null, " + + COL_CLOCK + " text not null, " + + COL_ACCOUNT_NAME + " text not null)," + + "PRIMARY KEY (" + COL_FILE_PATH + ", " + COL_ACCOUNT_NAME + ");"; + + + VectorTable() { + + } + + void CreateTable(@NonNull SQLiteDatabase db) { + db.execSQL(CREATE_TABLE); + } + + public void Insert(@NonNull File file, + @NonNull String accountname, + int clock) { + ContentValues tableRow = new ContentValues(); + tableRow.put(COL_FILE_PATH, file.getName()); + tableRow.put(COL_ACCOUNT_NAME, accountname); + tableRow.put(COL_CLOCK, clock); + db.notesDb.insertWithOnConflict(TABLE_NAME, null, tableRow, + SQLiteDatabase.CONFLICT_REPLACE); + } +/* + // TODO: Should use place holders instead of string concatenation. + public void Delete(@NonNull File file, + @NonNull String accountname) { + db.notesDb.execSQL("delete from " + TABLE_NAME + " where " + COL_FILE_PATH + " = '" + file.getAbsolutePath() + + "' and accountname = '" + accountname + "'"); + }*/ + + + } + + class FileTable { + + private static final String TAG = "IN_FileTable"; + + private static final String COL_FILE_PATH = "filepath"; + private static final String COL_MTIME = "mtime"; + private static final String COL_ACCOUNT_NAME = "accountname"; + private static final String TABLE_NAME = "file"; + //private static final String DATABASE_NAME = "NotesDb"; + + private static final String CREATE_FILE_TABLE = "CREATE TABLE IF NOT EXISTS " + + TABLE_NAME + + " (pk integer primary key autoincrement, " + + COL_FILE_PATH + " text not null, " + + COL_MTIME + " text not null, " + + COL_ACCOUNT_NAME + " text not null);"; + + + FileTable() { + + } + + void CreateTable(@NonNull SQLiteDatabase db) { + db.execSQL(CREATE_FILE_TABLE); + } + + public void Insert(@NonNull File file, + @NonNull String accountname) { + ContentValues tableRow = new ContentValues(); + tableRow.put(COL_FILE_PATH, file.getAbsolutePath()); + tableRow.put(COL_MTIME, file.lastModified()); + tableRow.put(COL_ACCOUNT_NAME, accountname); + db.notesDb.insert(TABLE_NAME, null, tableRow); + //Log.d(TAG, "note inserted"); + } + + // TODO: Should use place holders instead of string concatenation. + public void Delete(@NonNull File file, + @NonNull String accountname) { + db.notesDb.execSQL("delete from " + TABLE_NAME + " where " + COL_FILE_PATH + " = '" + file.getAbsolutePath() + + "' and accountname = '" + accountname + "'"); + } + + + public long GetMTime(@NonNull String filePath, + @NonNull String accountname) { + String selectQuery = "select mtime from " + TABLE_NAME + + " where " + COL_FILE_PATH + " = '" + filePath + "' " + " " + + " and accountname = '" + accountname + "'"; + try (Cursor c = db.notesDb.rawQuery(selectQuery, null)) { + if (c.moveToFirst()) { + return c.getLong(Cursor.FIELD_TYPE_NULL); + } + } + return 0; + } + + } + +} diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/VectorNote.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/VectorNote.java new file mode 100644 index 00000000..2ffb74aa --- /dev/null +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/VectorNote.java @@ -0,0 +1,50 @@ +package com.Pau.ImapNotes2.Data; + +import android.support.annotation.NonNull; + +import java.util.Date; +import java.util.HashMap; + + +/** + * Created by kj on 2017-01-09 10:59. + *

+ * Represents metadata about a note in a way that can be used by a ListAdapter. The list adapter + * needs objects that have a map interface because it must fetch the items by string name. + */ +public class VectorNote extends HashMap { + public static final String TITLE = "title"; + public static final String DATE = "date"; + //private static final String UID = "uid"; + + + public VectorNote(@NonNull String title, + long mtime) { + super(); + put(TITLE, title); + put(DATE, new Date(mtime).toString()); + } + + @NonNull + public String GetTitle() { + return this.get(TITLE); + } + + @NonNull + String GetDate() { + return this.get(DATE); + } + + + public void SetDate(@NonNull String date) { + this.put(DATE, date); + } + + + @NonNull + @Override + public String toString() { + return ("Title:" + this.GetTitle() + + " Date: " + this.GetDate()); + } +} diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/ImapNotes2k.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/ImapNotes2k.java index 1d3c242d..4458c75e 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/ImapNotes2k.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/ImapNotes2k.java @@ -27,18 +27,18 @@ public void onCreate() { }*/ @NonNull - public static String ConfigurationFilePath(Context applicationContext) { + public static String ConfigurationFilePath(@NonNull Context applicationContext) { return ConfigurationDirPath(applicationContext) + "/" + configurationFileName; } - public static String ConfigurationDirPath(Context applicationContext) { + public static String ConfigurationDirPath(@NonNull Context applicationContext) { return ConfigurationDir(applicationContext).getPath(); } - public static File ConfigurationDir(Context applicationContext) { + public static File ConfigurationDir(@NonNull Context applicationContext) { return applicationContext.getFilesDir(); } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java index 29c314e5..02ddb8a4 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java @@ -38,8 +38,8 @@ import android.widget.Toast; import com.Pau.ImapNotes2.Data.ConfigurationFieldNames; +import com.Pau.ImapNotes2.Data.Db; import com.Pau.ImapNotes2.Data.ImapNotes2Account; -import com.Pau.ImapNotes2.Data.NotesDb; import com.Pau.ImapNotes2.Data.OneNote; import com.Pau.ImapNotes2.Miscs.Imaper; import com.Pau.ImapNotes2.Miscs.SyncThread; @@ -60,6 +60,8 @@ import static com.Pau.ImapNotes2.AccountConfigurationActivity.ACTION; import static com.Pau.ImapNotes2.NoteDetailActivity.Colors; +//import com.Pau.ImapNotes2.Data.NotesDb; + //import com.Pau.ImapNotes2.R; //import android.widget.SimpleAdapter; @@ -78,7 +80,7 @@ public class Listactivity extends Activity implements OnItemSelectedListener, Fi public static final String EDIT_ITEM_COLOR = "EDIT_ITEM_COLOR"; private static final String SAVE_ITEM_COLOR = "SAVE_ITEM_COLOR"; private static final String SAVE_ITEM = "SAVE_ITEM"; - public static final String DELETE_ITEM_NUM_IMAP = "DELETE_ITEM_NUM_IMAP"; + private static final String DELETE_ITEM_NUM_IMAP = "DELETE_ITEM_NUM_IMAP"; public static final String ACCOUNTNAME = "ACCOUNTNAME"; public static final String SYNCINTERVAL = "SYNCINTERVAL"; public static final String CHANGED = "CHANGED"; @@ -90,7 +92,7 @@ public class Listactivity extends Activity implements OnItemSelectedListener, Fi private ArrayAdapter spinnerList; @Nullable - private static NotesDb storedNotes = null; + private static Db storedNotes = null; private Spinner accountSpinner; public static ImapNotes2Account imapNotes2Account; private static AccountManager accountManager; @@ -162,7 +164,7 @@ public void onCreate(Bundle savedInstanceState) { ((ImapNotes2k) this.getApplicationContext()).SetImaper(imapFolder); if (Listactivity.storedNotes == null) - storedNotes = new NotesDb(getApplicationContext()); + storedNotes = new Db(getApplicationContext()); // When item is clicked, we go to NoteDetailActivity listview.setOnItemClickListener(new OnItemClickListener() { @@ -241,10 +243,10 @@ public void onReceive(Context context, @NonNull Intent intent) { if (isChanged) { if (storedNotes == null) { - storedNotes = new NotesDb(getApplicationContext()); + storedNotes = new Db(getApplicationContext()); } storedNotes.OpenDb(); - storedNotes.GetStoredNotes(noteList, accountName); + storedNotes.notes.GetStoredNotes(noteList, accountName); listToView.notifyDataSetChanged(); storedNotes.CloseDb(); } @@ -267,16 +269,29 @@ private void UpdateList(String suid, String noteBody, Colors color, UpdateThread.Action action) { - new UpdateThread(Listactivity.imapNotes2Account, - noteList, - listToView, - ShowProgress(R.string.updating_notes_list), - suid, - noteBody, - color, - getApplicationContext(), - action, - storedNotes).execute(); + if (Listactivity.imapNotes2Account.GetUsesAutomaticMerge()) { + new UpdateThread(Listactivity.imapNotes2Account, + noteList, + listToView, + ShowProgress(R.string.updating_notes_list), + suid, + noteBody, + color, + getApplicationContext(), + action, + storedNotes).execute(); + } else { + new UpdateThread(Listactivity.imapNotes2Account, + noteList, + listToView, + ShowProgress(R.string.updating_notes_list), + suid, + noteBody, + color, + getApplicationContext(), + action, + storedNotes).execute(); + } } private ProgressDialog ShowProgress(int detailId) { @@ -322,6 +337,7 @@ public boolean onOptionsItemSelected(@NonNull MenuItem item) { String mClass = ".AccountConfigurationActivity"; res.setComponent(new ComponentName(mPackage, mPackage + mClass)); res.putExtra(ACTION, AccountConfigurationActivity.Actions.CREATE_ACCOUNT); + res.putExtra(ACCOUNTNAME, Listactivity.imapNotes2Account.GetAccountName()); startActivity(res); return true; case R.id.refresh: @@ -385,7 +401,7 @@ protected void onActivityResult(int requestCode, int resultCode, @NonNull Intent String res = data.getStringExtra(SAVE_ITEM); //Log.d(TAG,"Received request to save message:"+res); Colors color = (Colors) data.getSerializableExtra(SAVE_ITEM_COLOR); - this.UpdateList(null, res, color, UpdateThread.Action.Insert); + UpdateList(null, res, color, UpdateThread.Action.Insert); } } } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/SyncThread.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/SyncThread.java index e3f53cb0..ed68b2bb 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/SyncThread.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/SyncThread.java @@ -6,13 +6,15 @@ import android.support.annotation.NonNull; import android.support.annotation.Nullable; -import com.Pau.ImapNotes2.Data.NotesDb; +import com.Pau.ImapNotes2.Data.Db; import com.Pau.ImapNotes2.Data.OneNote; import com.Pau.ImapNotes2.Listactivity; import com.Pau.ImapNotes2.NotesListAdapter; import java.util.ArrayList; +//import com.Pau.ImapNotes2.Data.NotesDb; + public class SyncThread extends AsyncTask { private final ProgressDialog progressDialog; private final NotesListAdapter adapter; @@ -22,7 +24,7 @@ public class SyncThread extends AsyncTask { */ // TODO: NoteDb should probably never be null. @NonNull - private final NotesDb storedNotes; + private final Db storedNotes; // --Commented out by Inspection (11/26/16 11:48 PM):boolean bool_to_return; // --Commented out by Inspection START (11/26/16 11:48 PM): // @NonNull @@ -35,7 +37,7 @@ public class SyncThread extends AsyncTask { public SyncThread(ArrayList noteList, NotesListAdapter listToView, ProgressDialog loadingDialog, - @Nullable NotesDb storedNotes, + @Nullable Db storedNotes, Context applicationContext) { //this.imapFolder = imapFolder; //this.imapNotes2Account = imapNotes2Account; @@ -43,7 +45,7 @@ public SyncThread(ArrayList noteList, this.adapter = listToView; this.progressDialog = loadingDialog; //this.storedNotes = storedNotes; - this.storedNotes = (storedNotes == null) ? new NotesDb(applicationContext) : storedNotes; + this.storedNotes = (storedNotes == null) ? new Db(applicationContext) : storedNotes; } @@ -73,7 +75,7 @@ protected Boolean doInBackground(Object... stuffs) { storedNotes.OpenDb(); - storedNotes.GetStoredNotes(this.notesList, Listactivity.imapNotes2Account.GetAccountName()); + storedNotes.notes.GetStoredNotes(this.notesList, Listactivity.imapNotes2Account.GetAccountName()); storedNotes.CloseDb(); progressDialog.dismiss(); return true; diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java index 8b8f8605..721dfc61 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java @@ -4,10 +4,11 @@ import android.content.Context; import android.os.AsyncTask; import android.support.annotation.NonNull; +import android.text.Html; import android.util.Log; +import com.Pau.ImapNotes2.Data.Db; import com.Pau.ImapNotes2.Data.ImapNotes2Account; -import com.Pau.ImapNotes2.Data.NotesDb; import com.Pau.ImapNotes2.Data.OneNote; import com.Pau.ImapNotes2.Listactivity; import com.Pau.ImapNotes2.NotesListAdapter; @@ -25,13 +26,19 @@ import java.util.UUID; import javax.mail.Flags; +import javax.mail.Message; import javax.mail.MessagingException; +import javax.mail.Multipart; import javax.mail.Session; import javax.mail.internet.MailDateFormat; +import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; +import javax.mail.internet.MimeMultipart; import static com.Pau.ImapNotes2.NoteDetailActivity.Colors; +//import com.Pau.ImapNotes2.Data.NotesDb; + // TODO: move arguments from execute to constructor. public class UpdateThread extends AsyncTask { private final ImapNotes2Account imapNotes2Account; @@ -42,7 +49,7 @@ public class UpdateThread extends AsyncTask { private final String noteBody; private final Colors color; private boolean bool_to_return; - private NotesDb storedNotes; + private Db storedNotes; private final Context applicationContext; private final Action action; private static final String TAG = "IN_UpdateThread"; @@ -55,7 +62,7 @@ public enum Action { /* Assign all fields in the constructor because we never reuse this object. This makes the code - typesafe. Make them final to preven accidental reuse. + typesafe. Make them final to prevent accidental reuse. */ public UpdateThread(ImapNotes2Account imapNotes2Account, ArrayList noteList, @@ -66,7 +73,7 @@ public UpdateThread(ImapNotes2Account imapNotes2Account, Colors color, Context applicationContext, Action action, - NotesDb storedNotes) { + Db storedNotes) { Log.d(TAG, "UpdateThread: " + noteBody); this.imapNotes2Account = imapNotes2Account; this.notesList = noteList; @@ -80,6 +87,7 @@ public UpdateThread(ImapNotes2Account imapNotes2Account, this.storedNotes = storedNotes; } + @Override protected Boolean doInBackground(Object... stuffs) { @@ -92,7 +100,7 @@ protected Boolean doInBackground(Object... stuffs) { notesList.remove(getIndexByNumber(suid)); MoveMailToDeleted(suid); storedNotes.OpenDb(); - storedNotes.DeleteANote(suid, Listactivity.imapNotes2Account.GetAccountName()); + storedNotes.notes.DeleteANote(suid, Listactivity.imapNotes2Account.GetAccountName()); storedNotes.CloseDb(); bool_to_return = true; } @@ -101,11 +109,12 @@ protected Boolean doInBackground(Object... stuffs) { if ((action == Action.Insert) || (action == Action.Update)) { //Log.d(TAG,"Sticky ? "+((ImapNotes2Account)stuffs[1]).GetUsesticky()); //Log.d(TAG,"Color:"+color); - Log.d(TAG,"Received request to add new message: " + noteBody + "==="); + Log.d(TAG, "Received request to add new message: " + noteBody + "==="); //String noteTxt = Html.fromHtml(noteBody).toString(); - String noteTxt = noteBody; - Log.d(TAG,"noteTxt: " + noteTxt + "==="); - String[] tok = noteTxt.split("\n", 2); + String noteTxt = noteBody; + Log.d(TAG, "noteTxt: " + noteTxt + "==="); + // Use the first line as the tile + String[] tok = Html.fromHtml(noteBody).toString().split("\n", 2); String title = tok[0]; //String position = "0 0 0 0"; String body = (imapNotes2Account.GetUsesticky()) ? @@ -118,16 +127,18 @@ protected Boolean doInBackground(Object... stuffs) { String stringDate = sdf.format(date); OneNote currentNote = new OneNote(title, stringDate, ""); // Add note to database - if (storedNotes == null) storedNotes = new NotesDb(applicationContext); + if (storedNotes == null) storedNotes = new Db(applicationContext); storedNotes.OpenDb(); - suid = storedNotes.GetTempNumber(Listactivity.imapNotes2Account.GetAccountName()); + suid = storedNotes.notes.GetTempNumber(Listactivity.imapNotes2Account.GetAccountName()); currentNote.SetUid(suid); // Here we ask to add the new note to the new note folder // Must be done AFTER uid has been set in currenteNote Log.d(TAG, "doInBackground body: " + body); WriteMailToNew(currentNote, - imapNotes2Account.GetUsesticky(), body); - storedNotes.InsertANoteInDb(currentNote, Listactivity.imapNotes2Account.GetAccountName()); + imapNotes2Account.GetUsesticky(), + imapNotes2Account.GetUsesAutomaticMerge(), + body); + storedNotes.notes.InsertANoteInDb(currentNote, Listactivity.imapNotes2Account.GetAccountName()); storedNotes.CloseDb(); // Add note to noteList but chage date format before //DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(applicationContext); @@ -184,8 +195,44 @@ private void MoveMailToDeleted(@NonNull String suid) { } } + @NonNull + private Message MakeMessageWithAttachment(String subject, + String message, + String filePath, + Session session) + throws IOException, MessagingException { + + Message msg = new MimeMessage(session); + + + msg.setSubject(subject); + msg.setSentDate(new Date()); + + // creates message part + MimeBodyPart messageBodyPart = new MimeBodyPart(); + messageBodyPart.setContent(message, "text/html"); + + // creates multi-part + Multipart multipart = new MimeMultipart(); + multipart.addBodyPart(messageBodyPart); + + // add attachment + + MimeBodyPart attachPart = new MimeBodyPart(); + + attachPart.attachFile(filePath); + + + multipart.addBodyPart(attachPart); + + // sets the multi-part as e-mail's content + msg.setContent(multipart); + return msg; + } + private void WriteMailToNew(@NonNull OneNote note, boolean usesticky, + boolean usesAutomaticMerge, String noteBody) throws MessagingException, IOException { Log.d(TAG, "WriteMailToNew: " + noteBody); //String body = null; @@ -195,6 +242,7 @@ private void WriteMailToNew(@NonNull OneNote note, Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); + if (usesticky) { String body = "BEGIN:STICKYNOTE\nCOLOR:" + color.name() + "\nTEXT:" + noteBody + "\nPOSITION:0 0 0 0\nEND:STICKYNOTE"; diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java index fbb52ad3..5e605143 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java @@ -78,7 +78,7 @@ public void onCreate(Bundle savedInstanceState) { String stringres = sticky.text; //String position = sticky.position; color = sticky.color; - Spanned plainText = Html.fromHtml(stringres); + //Spanned plainText = Html.fromHtml(stringres); //EditText editText = ((EditText) findViewById(R.id.bodyView)); editText = (RichEditor) findViewById(R.id.bodyView); //editText.setText(plainText); @@ -112,7 +112,7 @@ public void afterTextChanged(Editable s) { - void SetupRichEditor(final RichEditor mEditor) { + private void SetupRichEditor(@NonNull final RichEditor mEditor) { //mEditor = (RichEditor) findViewById(R.id.editor); //mEditor.setEditorHeight(200); //mEditor.setEditorFontSize(22); @@ -384,6 +384,11 @@ public void onClick(DialogInterface dialog, int whichButton) { } } + + /** + * Note that this function does not save the note to permanent storage it just passes it back to + * the calling activity to be saved in whatever fashion it that activity wishes. + */ private void Save() { Log.d(TAG, "Save"); Intent intent = new Intent(); diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java index 5380d9a2..a2f65440 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncAdapter.java @@ -12,8 +12,8 @@ import android.util.Log; import com.Pau.ImapNotes2.Data.ConfigurationFieldNames; +import com.Pau.ImapNotes2.Data.Db; import com.Pau.ImapNotes2.Data.ImapNotes2Account; -import com.Pau.ImapNotes2.Data.NotesDb; import com.Pau.ImapNotes2.Data.Security; import com.Pau.ImapNotes2.Listactivity; import com.Pau.ImapNotes2.Miscs.ImapNotes2Result; @@ -29,6 +29,8 @@ import static com.Pau.ImapNotes2.Miscs.Imaper.ResultCodeSuccess; +//import com.Pau.ImapNotes2.Data.NotesDb; + /// A SyncAdapter provides methods to be called by the Android /// framework when the framework is ready for the synchronization to /// occur. The application does not need to consider threading @@ -36,8 +38,9 @@ /// of the application. class SyncAdapter extends AbstractThreadedSyncAdapter { private static final String TAG = "SyncAdapter"; + @NonNull private final Context applicationContext; - private NotesDb storedNotes; + private Db storedNotes; // TODO: Why was this static? //private Account account; private ImapNotes2Account account; @@ -94,12 +97,12 @@ public void onPerformSync(@NonNull Account accountArg, //SyncUtils.CreateLocalDirectories(accountArg.name, applicationContext); account.CreateLocalDirectories(); - storedNotes = new NotesDb(applicationContext); + storedNotes = new Db(applicationContext); storedNotes.OpenDb(); AccountManager am = AccountManager.get(applicationContext); //String syncInterval = am.getUserData(accountArg, "syncinterval"); - String syncInterval = account.GetSyncinterval(); + //String syncInterval = account.GetSyncinterval(); // Connect to remote and get UIDValidity ImapNotes2Result res = ConnectToRemote(); @@ -115,7 +118,7 @@ public void onPerformSync(@NonNull Account accountArg, // Replace local data by remote. UIDs are no longer valid. try { // delete notes in NotesDb for this account - storedNotes.ClearDb(accountArg.name); + storedNotes.notes.ClearDb(accountArg.name); // delete notes in folders for this account and recreate dirs //SyncUtils.ClearHomeDir(accountArg, applicationContext); account.ClearHomeDir(); @@ -241,7 +244,7 @@ private boolean handleNewNotes() { AppendUID[] uids = SyncUtils.sendMessageToRemote(msg); // Update uid in database entry String newuid = Long.toString(uids[0].uid); - storedNotes.UpdateANote(fileNew, newuid, account.GetAccountName()); + storedNotes.notes.UpdateANote(fileNew, newuid, account.GetAccountName()); // move new note from new dir, one level up File fileInNew = new File(dirNew, fileNew); File to = new File(accountDir, newuid); diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java index fdeb3c38..ebfa33c7 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java @@ -7,7 +7,7 @@ import android.support.annotation.Nullable; import android.util.Log; -import com.Pau.ImapNotes2.Data.NotesDb; +import com.Pau.ImapNotes2.Data.Db; import com.Pau.ImapNotes2.Data.OneNote; import com.Pau.ImapNotes2.Data.Security; import com.Pau.ImapNotes2.Data.Utilities; @@ -44,6 +44,8 @@ import static com.Pau.ImapNotes2.NoteDetailActivity.Colors; +//import com.Pau.ImapNotes2.Data.NotesDb; + public class SyncUtils { private static Store store; @@ -162,7 +164,7 @@ static ImapNotes2Result ConnectToRemote(@NonNull String username, static void GetNotes(@NonNull Account account, @NonNull Folder imapNotesFolder, @NonNull Context applicationContext, - @NonNull NotesDb storedNotes) throws MessagingException, IOException { + @NonNull Db storedNotes) throws MessagingException, IOException { Log.d(TAG,"GetNotes: " + account.name); //Long UIDM; //Message notesMessage; @@ -243,7 +245,7 @@ private static String getPosition(String stringres) { ""; }*/ - private static String getText(String stringres) { + private static String getText(@NonNull String stringres) { Matcher matcherText = patternText.matcher(stringres); String text = ""; if (matcherText.find()) { @@ -257,7 +259,8 @@ private static String getText(String stringres) { return text; } - private static Colors getColor(String stringres) { + @NonNull + private static Colors getColor(@NonNull String stringres) { Matcher matcherColor = patternColor.matcher(stringres); if (matcherColor.find()) { String colorName = matcherColor.group(1); @@ -542,7 +545,7 @@ private static void SaveNote(@NonNull File outfile, private static void SaveNoteAndUpdatDatabase(@NonNull File outfile, @NonNull Message notesMessage, - @NonNull NotesDb storedNotes, + @NonNull Db storedNotes, @NonNull String accountName, @NonNull String suid) throws IOException, MessagingException { Log.d(TAG,"SaveNoteAndUpdatDatabase: " + outfile.getCanonicalPath() + " " + accountName); @@ -601,12 +604,12 @@ private static void SaveNoteAndUpdatDatabase(@NonNull File outfile, title, internaldate, suid); - storedNotes.InsertANoteInDb(aNote, accountName); + storedNotes.notes.InsertANoteInDb(aNote, accountName); } static boolean handleRemoteNotes(@NonNull Context context, @NonNull Folder notesFolder, - @NonNull NotesDb storedNotes, + @NonNull Db storedNotes, @NonNull String accountName, @NonNull String usesticky) throws MessagingException, IOException { @@ -657,7 +660,7 @@ static boolean handleRemoteNotes(@NonNull Context context, } else if (usesticky.equals("true")) { //Log.d (TAG,"MANAGE STICKY"); remoteInternaldate = DateFormat.getDateInstance().format(notesMessage.getSentDate()); - localInternaldate = storedNotes.GetDate(suid, accountName); + localInternaldate = storedNotes.notes.GetDate(suid, accountName); if (!(remoteInternaldate.equals(localInternaldate))) { File outfile = new File(rootDir, suid); SaveNote(outfile, notesMessage); @@ -675,7 +678,7 @@ static boolean handleRemoteNotes(@NonNull Context context, //noinspection ResultOfMethodCallIgnored toDelete.delete(); // Remove note from database - storedNotes.DeleteANote(suid, accountName); + storedNotes.notes.DeleteANote(suid, accountName); result = true; } } @@ -700,9 +703,9 @@ static void RemoveAccount(@NonNull Context context, @NonNull Account account) { file.delete(); } // Delete account name entries in database - NotesDb storedNotes = new NotesDb(context); + Db storedNotes = new Db(context); storedNotes.OpenDb(); - storedNotes.ClearDb(account.name); + storedNotes.notes.ClearDb(account.name); storedNotes.CloseDb(); } } diff --git a/ImapNote2/src/main/res/layout/account_selection.xml b/ImapNote2/src/main/res/layout/account_selection.xml index a6ff3d2d..59bf3ad2 100644 --- a/ImapNote2/src/main/res/layout/account_selection.xml +++ b/ImapNote2/src/main/res/layout/account_selection.xml @@ -159,6 +159,13 @@ android:layout_height="wrap_content" android:text="@string/use_sticky_notes" /> + + +