From 41873ae676e4e01d4cd329ae27144441aaae054b Mon Sep 17 00:00:00 2001 From: Chris Graham Date: Mon, 12 Dec 2016 12:49:06 +0000 Subject: [PATCH 01/13] Updated Gradle --- build.gradle | 2 +- gradle/wrapper/gradle-wrapper.properties | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/build.gradle b/build.gradle index f4d8c542..2e369803 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.3' } } diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index f23df6e4..d557f1ca 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 Dec 12 12:48:47 GMT 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 8bc613d585dce628018e6060ce86de8028aa47b4 Mon Sep 17 00:00:00 2001 From: Chris Graham Date: Mon, 12 Dec 2016 12:53:20 +0000 Subject: [PATCH 02/13] Fixed ugly lower case label --- ImapNote2/src/main/res/menu/list.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ImapNote2/src/main/res/menu/list.xml b/ImapNote2/src/main/res/menu/list.xml index 69f0757d..39d30003 100644 --- a/ImapNote2/src/main/res/menu/list.xml +++ b/ImapNote2/src/main/res/menu/list.xml @@ -23,7 +23,7 @@ From bd8cf8b2d955d6d9e56d2582d32bdfe8425de882 Mon Sep 17 00:00:00 2001 From: Chris Graham Date: Mon, 12 Dec 2016 12:58:52 +0000 Subject: [PATCH 03/13] Edit account label --- .../java/com/Pau/ImapNotes2/AccontConfigurationActivity.java | 2 ++ ImapNote2/src/main/res/layout/account_selection.xml | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccontConfigurationActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccontConfigurationActivity.java index fcd54633..0f7c2e8a 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccontConfigurationActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccontConfigurationActivity.java @@ -141,6 +141,8 @@ public void onCreate(Bundle savedInstanceState) { } if (this.settings != null) { + ((TextView)(findViewById(R.id.heading))).setText("Edit Account"); + this.accountnameTextView.setText(this.settings.GetAccountname()); this.usernameTextView.setText(this.settings.GetUsername()); this.passwordTextView.setText(this.settings.GetPassword()); diff --git a/ImapNote2/src/main/res/layout/account_selection.xml b/ImapNote2/src/main/res/layout/account_selection.xml index f340f988..a2ffd55e 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" > Date: Mon, 12 Dec 2016 13:00:57 +0000 Subject: [PATCH 04/13] Renamed typo class name --- ImapNote2/src/main/AndroidManifest.xml | 2 +- ...tivity.java => AccountConfigurationActivity.java} | 12 ++++++------ .../main/java/com/Pau/ImapNotes2/Listactivity.java | 6 +++--- .../Miscs/ImapNotesAuthenticatorService.java | 4 ++-- 4 files changed, 12 insertions(+), 12 deletions(-) rename ImapNote2/src/main/java/com/Pau/ImapNotes2/{AccontConfigurationActivity.java => AccountConfigurationActivity.java} (96%) diff --git a/ImapNote2/src/main/AndroidManifest.xml b/ImapNote2/src/main/AndroidManifest.xml index 9680deb1..c101240e 100644 --- a/ImapNote2/src/main/AndroidManifest.xml +++ b/ImapNote2/src/main/AndroidManifest.xml @@ -32,7 +32,7 @@ android:resource="@xml/searchable" /> - { - private AccontConfigurationActivity accontConfigurationActivity; + private AccountConfigurationActivity accontConfigurationActivity; private ImapNotes2Result res = new ImapNotes2Result(); String action; @@ -239,12 +239,12 @@ protected Boolean doInBackground(Object... stuffs) { ((ImapNotes2Account)stuffs[1]).GetSecurity(), ((ImapNotes2Account)stuffs[1]).GetUsesticky(), ((ImapNotes2Account)stuffs[1]).GetFoldername()); - accontConfigurationActivity = (AccontConfigurationActivity)stuffs[3]; + 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(((AccontConfigurationActivity)stuffs[3])); - accontConfigurationActivity.setResult(AccontConfigurationActivity.TO_REFRESH); + AccountManager am = AccountManager.get(((AccountConfigurationActivity)stuffs[3])); + accontConfigurationActivity.setResult(AccountConfigurationActivity.TO_REFRESH); Bundle result = null; if (this.action.equals("EDIT_ACCOUNT")) { result = new Bundle(); diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java index 31796e97..e8489536 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 void onClick(View v) { // Clic on editAccount Button 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()); @@ -265,7 +265,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); @@ -457,7 +457,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/Miscs/ImapNotesAuthenticatorService.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/ImapNotesAuthenticatorService.java index 6e71bd62..00ad7bb2 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; @@ -64,7 +64,7 @@ public Bundle getAccountRemovalAllowed( @Override public Bundle addAccount(AccountAuthenticatorResponse response, String accountType, String authTokenType, String[] requiredFeatures, Bundle options) throws NetworkErrorException { - Intent toLoginActivity = new Intent(this.mContext, AccontConfigurationActivity.class); + 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); From ffaa48c6d360c7c5164d41b27865b1bb01d122b1 Mon Sep 17 00:00:00 2001 From: Chris Graham Date: Mon, 12 Dec 2016 13:09:53 +0000 Subject: [PATCH 05/13] Confirmation on note deletion --- .../Pau/ImapNotes2/NoteDetailActivity.java | 20 ++++++++++++++----- 1 file changed, 15 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 8dee10f2..51113f4f 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java @@ -21,6 +21,8 @@ import java.io.OutputStream; import android.app.Activity; +import android.app.AlertDialog; +import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; @@ -132,13 +134,21 @@ public boolean onPrepareOptionsMenu(Menu menu) { } public boolean onOptionsItemSelected (MenuItem item){ - Intent intent=new Intent(); + final 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 + 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(NoteDetailActivity.DELETE_BUTTON, intent); + finish();//finishing activity + }}) + .setNegativeButton(android.R.string.no, null).show(); return true; case R.id.save: //Log.d(TAG,"We ask to modify Message #"+this.currentNote.get("number")); From d4f89f2331a4548179a7ad27f126e926df012e33 Mon Sep 17 00:00:00 2001 From: Chris Graham Date: Mon, 12 Dec 2016 13:12:51 +0000 Subject: [PATCH 06/13] Make it clear what select account is for (maybe user will then notice the edit icon on the right) --- ImapNote2/src/main/res/layout/main.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ImapNote2/src/main/res/layout/main.xml b/ImapNote2/src/main/res/layout/main.xml index 5104500c..cffae630 100644 --- a/ImapNote2/src/main/res/layout/main.xml +++ b/ImapNote2/src/main/res/layout/main.xml @@ -19,7 +19,7 @@ android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@color/ListColor" - android:text="Select account" + android:text="Select account to view or edit" android:textAppearance="?android:attr/textAppearanceSmall" android:textColor="#000000" > From 6a371fffe8bc7ff644d5a1ab77e57a96690c0902 Mon Sep 17 00:00:00 2001 From: Chris Graham Date: Mon, 12 Dec 2016 13:16:22 +0000 Subject: [PATCH 07/13] Code reformat --- .../AccountConfigurationActivity.java | 579 ++++++------ .../ImapNotes2/Data/ConfigurationFile.java | 102 +-- .../ImapNotes2/Data/ImapNotes2Account.java | 72 +- .../java/com/Pau/ImapNotes2/Data/NotesDb.java | 155 ++-- .../java/com/Pau/ImapNotes2/ImapNotes2.java | 76 +- .../java/com/Pau/ImapNotes2/Listactivity.java | 430 ++++----- .../ImapNotes2/Miscs/ImapNotes2Result.java | 26 +- .../Miscs/ImapNotesAuthenticatorService.java | 157 ++-- .../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 | 283 +++--- .../com/Pau/ImapNotes2/NotesListAdapter.java | 81 +- .../com/Pau/ImapNotes2/Sync/StubProvider.java | 5 + .../com/Pau/ImapNotes2/Sync/SyncAdapter.java | 87 +- .../com/Pau/ImapNotes2/Sync/SyncUtils.java | 851 +++++++++--------- 19 files changed, 1824 insertions(+), 1786 deletions(-) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java index 9e1adb8c..474068d9 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java @@ -33,319 +33,326 @@ 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 = "AccountConfigurationActivity"; - - 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; +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 = "AccountConfigurationActivity"; - 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 Imaper imapFolder; - 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 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 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 - } - }; + 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); + @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); + 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()); + 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"); + Bundle extras = getIntent().getExtras(); + if (extras != null) { + if (extras.containsKey("action")) { + action = extras.getString("action"); + } + if (extras.containsKey("accountname")) { + accountname = extras.getString("accountname"); + } } - if (extras.containsKey("accountname")) { - accountname = extras.getString("accountname"); + + if (this.settings != null) { + ((TextView) (findViewById(R.id.heading))).setText("Edit Account"); + + 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()); } - } - if (this.settings != null) { - ((TextView)(findViewById(R.id.heading))).setText("Edit Account"); + 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; + } + } - 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()); - } + if ((this.action == null) || (this.myAccount == null)) { + this.action = "CREATE_ACCOUNT"; + } - 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.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 + ); } - if ((this.action == null) || (this.myAccount == null)) { this.action = "CREATE_ACCOUNT"; } + // 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); - 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 - ); - } + class LoginThread extends AsyncTask { - // 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; + 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; - } + 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; } - } 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); + + 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(); } - 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); + 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 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 - } + @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 b4ec7b09..1f546a77 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFile.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFile.java @@ -18,7 +18,7 @@ public class ConfigurationFile { private Context applicationContext; private static final String TAG = "IN_ConfigurationFile"; - + private String accountname; private String username; private String password; @@ -27,14 +27,14 @@ public class ConfigurationFile { private String security; private String usesticky; private String imapfolder; - - - public ConfigurationFile(Context myContext){ + + + public ConfigurationFile(Context myContext) { this.applicationContext = myContext; - + try { Document fileToLoad = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse( - new File(this.applicationContext.getFilesDir()+"/ImapNotes2.conf")); + new File(this.applicationContext.getFilesDir() + "/ImapNotes2.conf")); 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(); @@ -69,80 +69,80 @@ 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(this.applicationContext.getFilesDir() + "/ImapNotes2.conf").delete(); + this.username = null; + this.password = null; + this.server = null; + this.portnum = null; + this.security = null; + this.usesticky = null; this.imapfolder = null; } - - public void SaveConfigurationToXML() throws IllegalArgumentException, IllegalStateException, IOException{ + + public void SaveConfigurationToXML() throws IllegalArgumentException, IllegalStateException, IOException { FileOutputStream configurationFile = this.applicationContext.openFileOutput("ImapNotes2.conf", Context.MODE_PRIVATE); XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(configurationFile, "UTF-8"); - serializer.startDocument(null, Boolean.valueOf(true)); - serializer.startTag(null, "Configuration"); + serializer.startDocument(null, Boolean.valueOf(true)); + serializer.startTag(null, "Configuration"); serializer.startTag(null, "username"); serializer.text(this.username); serializer.endTag(null, "username"); @@ -158,20 +158,20 @@ public void SaveConfigurationToXML() throws IllegalArgumentException, IllegalSta serializer.startTag(null, "security"); serializer.text(this.security); serializer.endTag(null, "security"); - serializer.startTag(null,"imapfolder"); + 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.endTag(null, "Configuration"); serializer.endDocument(); serializer.flush(); configurationFile.close(); } - - private NodeList LoadItemFromXML(Document fileLoaded, String tag){ + + private NodeList LoadItemFromXML(Document fileLoaded, String tag) { return fileLoaded.getElementsByTagName(tag); - + } } 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..cf25abf5 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java @@ -18,38 +18,38 @@ 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()); @@ -59,108 +59,109 @@ public void InsertANoteInDb(OneNote noteElement, String accountname){ //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; - - public void onCreate(){ - super.onCreate(); - ImapNotes2.context = getApplicationContext(); - } - - 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; - } + + private ConfigurationFile thisSessionConfigurationFile; + private Imaper thisSessionImapFolder; + private ArrayList noteList; + private static Context context; + + public void onCreate() { + super.onCreate(); + ImapNotes2.context = getApplicationContext(); + } + + 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; + } } diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java index e8489536..18d9b2d1 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java @@ -58,17 +58,17 @@ 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; @@ -78,11 +78,11 @@ 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 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 @@ -91,69 +91,71 @@ public void onClick(View v) { Intent res = new Intent(); String mPackage = "com.Pau.ImapNotes2"; String mClass = ".AccountConfigurationActivity"; - 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); + + // 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); + } + }); - editAccountButton = (Button) findViewById(R.id.editAccountButton); - editAccountButton.setOnClickListener(clickListenerEditAccount); + editAccountButton = (Button) findViewById(R.id.editAccountButton); + editAccountButton.setOnClickListener(clickListenerEditAccount); } @@ -171,7 +173,7 @@ public void onStart() { int len = this.accounts == null ? 0 : this.accounts.length; if (len > 0) updateAccountSpinner(); } - + @Override protected void onResume() { super.onResume(); @@ -195,9 +197,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 +208,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,119 +218,119 @@ 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()); status.setText("Welcome"); } - - public void UpdateList(String suid, String noteBody, String color, String action){ - ProgressDialog loadingDialog = ProgressDialog.show(this, "imapnote2" , "Updating notes list... ", true); + + 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 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 = ".AccountConfigurationActivity"; - 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; + } + + @Override + public boolean onQueryTextSubmit(String query) { + // this is your adapter that will be filtered + listToView.getFilter().filter(query); + return true; } - return true; - default: - return super.onOptionsItemSelected(item); + }; + 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 = ".AccountConfigurationActivity"; + 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"); + } + 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"); + } } } @@ -340,7 +342,7 @@ public void onItemSelected(AdapterView parent, View view, int pos, long id) { // 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,50 +354,48 @@ 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; @@ -408,7 +408,7 @@ public void onAccountsUpdated(Account[] accounts) { } } 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 +416,20 @@ 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; try { - FileUtils.deleteDirectory(new File (stringDir)); + FileUtils.deleteDirectory(new File(stringDir)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); @@ -437,11 +437,11 @@ 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; } } @@ -458,7 +458,7 @@ public void onAccountsUpdated(Account[] accounts) { Intent res = new Intent(); String mPackage = "com.Pau.ImapNotes2"; String mClass = ".AccountConfigurationActivity"; - res.setComponent(new ComponentName(mPackage,mPackage+mClass)); + res.setComponent(new ComponentName(mPackage, mPackage + mClass)); startActivity(res); } } @@ -466,38 +466,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 +509,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 00ad7bb2..92a3c0ff 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/ImapNotesAuthenticatorService.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/ImapNotesAuthenticatorService.java @@ -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, 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; - } - + 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 51113f4f..d9662214 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; @@ -37,7 +38,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; @@ -52,159 +53,160 @@ 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){ - final Intent intent=new Intent(); - switch (item.getItemId()){ - case R.id.delete: - 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(NoteDetailActivity.DELETE_BUTTON, intent); - finish();//finishing activity - }}) - .setNegativeButton(android.R.string.no, null).show(); - 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) { + final Intent intent = new Intent(); + switch (item.getItemId()) { + case R.id.delete: + 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(NoteDetailActivity.DELETE_BUTTON, intent); + finish();//finishing activity + } + }) + .setNegativeButton(android.R.string.no, null).show(); + 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; @@ -213,22 +215,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 @@ -238,35 +240,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) { @@ -289,19 +291,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..079c40d2 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java @@ -38,18 +38,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 +69,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 +91,7 @@ public NotesListAdapter(Context context, List> data, mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } - + /** * @see android.widget.Adapter#getCount() */ @@ -121,7 +121,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 +193,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,7 +210,6 @@ 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) */ public ViewBinder getViewBinder() { @@ -221,8 +220,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 +231,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 +247,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 +272,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 +289,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 +301,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 +346,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 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(); } - 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))) { - File outfile = new File (rootDir, suid); - GetOneNote(outfile, notesMessage, storedNotes, accountName, suid, false); - result = true; + + 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(); } } - } - // 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; + // 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); } - return result; - } + 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, 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; + } + } + + return result; + } public static void RemoveAccount(Context context, Account account) { // remove Shared Preference file String rootString = context.getFilesDir().getParent() + - File.separator + "shared_prefs"; - File rootDir = new File (rootString); - File toDelete = new File (rootDir, account.name + ".xml"); + File.separator + "shared_prefs"; + File rootDir = new File(rootString); + File toDelete = new File(rootDir, account.name + ".xml"); toDelete.delete(); // Remove all files and sub directories File filesDir = context.getFilesDir(); From 831a3b894b33660a68864c2ca18a0c55874359de Mon Sep 17 00:00:00 2001 From: Chris Graham Date: Mon, 12 Dec 2016 13:18:08 +0000 Subject: [PATCH 08/13] Further cleanup --- .../ImapNotes2/Miscs/ImapNotesAuthenticatorService.java | 7 ------- .../src/main/java/com/Pau/ImapNotes2/Miscs/OneNote.java | 3 --- .../src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java | 1 - .../src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java | 1 - 4 files changed, 12 deletions(-) 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..d38c9215 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/ImapNotesAuthenticatorService.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/ImapNotesAuthenticatorService.java @@ -64,7 +64,6 @@ public Bundle getAccountRemovalAllowed( @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(); @@ -75,37 +74,31 @@ public Bundle addAccount(AccountAuthenticatorResponse response, String accountTy @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/OneNote.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/OneNote.java index d3951ee8..43a90b27 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/OneNote.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/OneNote.java @@ -4,9 +4,6 @@ public class OneNote extends HashMap { - /** - * - */ private static final long serialVersionUID = 1L; public OneNote() { diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java index 079c40d2..47c751b4 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NotesListAdapter.java @@ -346,7 +346,6 @@ 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 < len; j++) { 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 43a810c9..b183ec26 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java @@ -436,7 +436,6 @@ public static void GetOneNote(File outfile, Message notesMessage, NotesDb stored 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(); From 5d18b7504c0a892804a1cfbb5540e6464d697e3b Mon Sep 17 00:00:00 2001 From: Chris Graham Date: Mon, 12 Dec 2016 13:19:50 +0000 Subject: [PATCH 09/13] Further cleanup --- .../AccountConfigurationActivity.java | 26 +++++++++---------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java index 474068d9..a0352b19 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java @@ -226,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; @@ -241,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(); @@ -301,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(); From ccfdcbdc92729486e6ab296df7554341e85cf372 Mon Sep 17 00:00:00 2001 From: Chris Graham Date: Mon, 12 Dec 2016 13:22:31 +0000 Subject: [PATCH 10/13] Further cleanup --- .../AccountConfigurationActivity.java | 2 +- .../ImapNotes2/Data/ConfigurationFile.java | 4 ++-- .../java/com/Pau/ImapNotes2/Data/NotesDb.java | 4 ++-- .../Miscs/ImapNotesAuthenticatorService.java | 6 +++--- .../java/com/Pau/ImapNotes2/Miscs/Imaper.java | 20 +++++++++---------- .../Pau/ImapNotes2/Miscs/UpdateThread.java | 4 ++-- .../Pau/ImapNotes2/NoteDetailActivity.java | 12 +++++------ .../com/Pau/ImapNotes2/Sync/SyncUtils.java | 8 ++++---- 8 files changed, 30 insertions(+), 30 deletions(-) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java index a0352b19..54ffc3de 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/AccountConfigurationActivity.java @@ -89,7 +89,7 @@ public void onClick(View v) { private 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(), "Account has been removed", Toast.LENGTH_LONG).show(); 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 1f546a77..6ee5383e 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFile.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/ConfigurationFile.java @@ -56,9 +56,9 @@ public ConfigurationFile(Context myContext) { else this.usesticky = this.LoadItemFromXML(fileToLoad, "usesticky").item(0).getChildNodes().item(0).getNodeValue(); -//Log.d(TAG, "conf file present, we read data"); + //Log.d(TAG, "conf file present, we read data"); } catch (Exception e) { -//Log.d(TAG, "Conf file absent, go to the exception that initializes variables"); + //Log.d(TAG, "Conf file absent, go to the exception that initializes variables"); this.accountname = ""; this.username = ""; this.password = ""; 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 cf25abf5..de6a6ad7 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Data/NotesDb.java @@ -162,7 +162,7 @@ public void apply(SQLiteDatabase _db) { _db.execSQL(NotesDb.CREATE_NOTES_DB); } } -/* + /* ,new Patch() { public void apply(SQLiteDatabase _db) { Log.d(TAG,"upgrade: v3 to v4"); @@ -170,7 +170,7 @@ public void apply(SQLiteDatabase _db) { _db.execSQL(NotesDb.CREATE_NOTES_DB); } } -*/ + */ }; } } 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 d38c9215..d4c3e6f1 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/ImapNotesAuthenticatorService.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/ImapNotesAuthenticatorService.java @@ -55,10 +55,10 @@ public Bundle getAccountRemovalAllowed( Bundle ret = super.getAccountRemovalAllowed(response, account); if (ret.getBoolean(AccountManager.KEY_BOOLEAN_RESULT)) SyncUtils.RemoveAccount(this.mContext, account); -/* + /* mContext.getContentResolver().delete(ListProvider.getClearUri(), - null, null); -*/ + null, null); + */ return ret; } 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..ff0aea2e 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Imaper.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/Imaper.java @@ -126,25 +126,25 @@ public ImapNotes2Result ConnectToProvider(String username, String password, Stri 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"); - props.put("socksProxyPort","1080"); - props.put("sun.net.spi.nameservice.provider.1", "dns,sun"); - props.put("sun.net.spi.nameservice.nameservers", "192.168.0.99"); -*/ + /* + props.put("proxySet","true"); + props.put("socksProxyHost","10.0.2.2"); + props.put("socksProxyPort","1080"); + 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.setDebug(true); + //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"); -//Log.d(TAG, "has UIDPLUS="+hasUIDPLUS); + //Log.d(TAG, "has UIDPLUS="+hasUIDPLUS); Folder[] folders = store.getPersonalNamespaces(); Folder folder = folders[0]; -//Log.d(TAG,"Personal Namespaces="+folder.getFullName()); + //Log.d(TAG,"Personal Namespaces="+folder.getFullName()); if (this.folderoverride.length() > 0) { Imaper.sfolder = this.folderoverride; } else if (folder.getFullName().length() == 0) { 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..19d2ca3a 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Miscs/UpdateThread.java @@ -74,8 +74,8 @@ protected Boolean doInBackground(Object... stuffs) { // Do we have a note to add? if (this.action.equals("insert") || this.action.equals("update")) { -//Log.d(TAG,"Sticky ? "+((ImapNotes2Account)stuffs[1]).GetUsesticky()); -//Log.d(TAG,"Color:"+this.color); + //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(); String[] tok = noteTxt.split("\n", 2); diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java index d9662214..e3e32505 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/NoteDetailActivity.java @@ -214,7 +214,7 @@ private Sticky GetInfoFromMessage(Message message) { String charset; Sticky sticky = null; try { -//Log.d(TAG, "Contenttype as string:"+message.getContentType()); + //Log.d(TAG, "Contenttype as string:"+message.getContentType()); contentType = new ContentType(message.getContentType()); charset = contentType.getParameter("charset"); iis = (InputStream) message.getContent(); @@ -224,7 +224,7 @@ private Sticky GetInfoFromMessage(Message message) { e.printStackTrace(); } -//Log.d(TAG,"contentType:"+contentType); + //Log.d(TAG,"contentType:"+contentType); if (contentType.match("text/x-stickynote")) { sticky = SyncUtils.ReadStickynote(stringres); } else if (contentType.match("TEXT/HTML")) { @@ -232,8 +232,8 @@ private Sticky GetInfoFromMessage(Message message) { } else if (contentType.match("TEXT/PLAIN")) { 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 + // All next is a workaround + // All function need to be rewritten to handle correctly multipart and images if (contentType.getParameter("type").equalsIgnoreCase("TEXT/HTML")) { sticky = ReadHtmlnote(stringres); } else if (contentType.getParameter("type").equalsIgnoreCase("TEXT/PLAIN")) { @@ -272,7 +272,7 @@ private void GetPart(Part message) throws Exception { } private Sticky ReadHtmlnote(String stringres) { -// Log.d(TAG,"From server (html):"+stringres); + // Log.d(TAG,"From server (html):"+stringres); Spanned spanres = Html.fromHtml(stringres); stringres = Html.toHtml(spanres); stringres = stringres.replaceFirst("

", ""); @@ -285,7 +285,7 @@ private Sticky ReadHtmlnote(String stringres) { } private Sticky ReadPlainnote(String stringres) { -// Log.d(TAG,"From server (plain):"+stringres); + // Log.d(TAG,"From server (plain):"+stringres); stringres = stringres.replaceAll("\n", "
"); return new Sticky(stringres, "", "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 b183ec26..e1c59b3f 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Sync/SyncUtils.java @@ -99,8 +99,8 @@ public static ImapNotes2Result ConnectToRemote(String username, String password, proto = "imap"; acceptcrt = "true"; break; -////////////////////// Change this default: + ////////////////////// Change this proto = "Invalid proto"; break; } @@ -143,16 +143,16 @@ public static ImapNotes2Result ConnectToRemote(String username, String password, props.put("mail.imap.socks.port", "1080"); } session = Session.getInstance(props, null); -//this.session.setDebug(true); + //this.session.setDebug(true); store = session.getStore(proto); try { store.connect(server, username, password); res.hasUIDPLUS = ((IMAPStore) store).hasCapability("UIDPLUS"); -//Log.d(TAG, "has UIDPLUS="+res.hasUIDPLUS); + //Log.d(TAG, "has UIDPLUS="+res.hasUIDPLUS); Folder[] folders = store.getPersonalNamespaces(); Folder folder = folders[0]; -//Log.d(TAG,"Personal Namespaces="+folder.getFullName()); + //Log.d(TAG,"Personal Namespaces="+folder.getFullName()); if (folderoverride.length() > 0) { sfolder = folderoverride; } else if (folder.getFullName().length() == 0) { From c8c764d42c1fbb742fe469593f40328eee678b34 Mon Sep 17 00:00:00 2001 From: Chris Graham Date: Mon, 12 Dec 2016 13:23:31 +0000 Subject: [PATCH 11/13] Further cleanup --- ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java index 18d9b2d1..2b2961c9 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java @@ -165,7 +165,7 @@ public void onDestroy() { // logcat will be sent by mail // send mail action is done by the user, so he can refuse // SendLogcatMail(); -// this.imapFolder.SetPrefs(); + // this.imapFolder.SetPrefs(); } public void onStart() { From c3effcafb7ce0f915835b3e0c50ee1a8cb437886 Mon Sep 17 00:00:00 2001 From: Chris Graham Date: Mon, 12 Dec 2016 13:29:18 +0000 Subject: [PATCH 12/13] Auto-sync on save --- .../src/main/java/com/Pau/ImapNotes2/Listactivity.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java index 2b2961c9..0308fb23 100644 --- a/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java +++ b/ImapNote2/src/main/java/com/Pau/ImapNotes2/Listactivity.java @@ -151,6 +151,8 @@ public void onItemClick(AdapterView arg0, View widget, int selectedNote, long toDetail.putExtra("selectedNote", (OneNote) arg0.getItemAtPosition(selectedNote)); toDetail.putExtra("useSticky", Listactivity.imapNotes2Account.GetUsesticky()); startActivityForResult(toDetail, SEE_DETAIL); + + TriggerSync(status); } }); @@ -319,9 +321,11 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) { 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 edit message:"+suid); //Log.d(TAG,"Received request to replace message with:"+txt); this.UpdateList(suid, txt, color, "update"); + + this.TriggerSync(this.status); } case Listactivity.NEW_BUTTON: // Returning from NewNoteActivity From ff33eddc49872f92f4da1e3f0db55e1b2d4a1810 Mon Sep 17 00:00:00 2001 From: Chris Graham Date: Tue, 13 Dec 2016 12:40:48 +0000 Subject: [PATCH 13/13] Note layout broken on some simulators, makes unnecessary height assumption --- .../src/main/res/layout/note_element.xml | 27 +++++++++---------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/ImapNote2/src/main/res/layout/note_element.xml b/ImapNote2/src/main/res/layout/note_element.xml index c43c4a1f..a940f5ca 100644 --- a/ImapNote2/src/main/res/layout/note_element.xml +++ b/ImapNote2/src/main/res/layout/note_element.xml @@ -1,17 +1,17 @@ - - +