();
+ temp.add((HSTicket) data.getSerializableExtra(NewIssueActivity.RESULT_TICKET));
+ temp.addAll(Arrays.asList(fetchedTickets));
+ HSTicket[] array = new HSTicket[0];
+ array = temp.toArray(array);
+ fetchedTickets = array;
+ refreshList();
+ mExpandableListView.setSelectedGroup(1);
+ }
+ }
+ }
+
+ @Override
+ public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
+ super.onCreateOptionsMenu(menu, inflater);
+
+ inflater.inflate(R.menu.hs_search_menu, menu);
+ MenuItem searchItem = menu.findItem(R.id.search);
+ mSearchFragment.addSearchViewInMenuItem(getActivity(), searchItem);
+ }
+
+ @Override
+ public void onDetach() {
+ gearSource.cancelOperation("FAQ");
+ super.onDetach();
+ }
+
+ private void refreshList() {
+ mAdapter.clearAll();
if (fetchedTickets != null && fetchedTickets.length > 0) {
faq_position = 1;
- mAdapter.addParent(0, getString(R.string.hs_issues_title));
+ mAdapter.addParent(0, getString(R.string.hs_issues_title));
- for (int i = 0; i < fetchedTickets.length ; i++) {
- HSTicket item = fetchedTickets[i];
- mAdapter.addChild(0, item);
- }
- }
+ for (int i = 0; i < fetchedTickets.length; i++) {
+ HSTicket item = fetchedTickets[i];
+ mAdapter.addChild(0, item);
+ }
+ }
mAdapter.addParent(faq_position, getString(R.string.hs_articles_title));
if (fetchedKbArticles != null) {
- for (int i = 0; i < fetchedKbArticles.length ; i++) {
+ for (int i = 0; i < fetchedKbArticles.length; i++) {
HSKBItem item = fetchedKbArticles[i];
mAdapter.addChild(faq_position, item);
}
}
- mAdapter.notifyDataSetChanged();
- expandAll();
- }
-
- private void expandAll() {
- int count = mAdapter.getGroupCount();
- for (int i = 0; i < count; i++) {
- mExpandableListView.expandGroup(i);
- }
- }
-
- protected void articleClickedOnPosition(HSKBItem kbItemClicked) {
- if(kbItemClicked.getArticleType() == HSKBItem.TYPE_ARTICLE) {
- HSActivityManager.startArticleActivity(this, kbItemClicked, REQUEST_CODE_NEW_TICKET);
- }
- else {
- HSActivityManager.startSectionActivity(this, kbItemClicked, REQUEST_CODE_NEW_TICKET);
- }
- }
-
- private class LocalAdapter extends HSBaseExpandableListAdapter {
-
- public LocalAdapter(Context context) {
- super(context);
- }
-
- @Override
- public View getChildView(final int groupPosition,final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
- ChildViewHolder holder;
-
- if (convertView == null) {
- convertView = mLayoutInflater.inflate(R.layout.hs_expandable_child_home_default, null);
- holder = new ChildViewHolder();
- holder.textView1 = (TextView) convertView.findViewById(R.id.textView1);
- convertView.setTag(holder);
- }
- else {
- holder = (ChildViewHolder) convertView.getTag();
- }
-
- if (groupPosition == faq_position) {
+ mAdapter.notifyDataSetChanged();
+ expandAll();
+ }
+
+ private void expandAll() {
+ int count = mAdapter.getGroupCount();
+ for (int i = 0; i < count; i++) {
+ mExpandableListView.expandGroup(i);
+ }
+ }
+
+ protected void articleClickedOnPosition(HSKBItem kbItemClicked) {
+ if (kbItemClicked.getArticleType() == HSKBItem.TYPE_ARTICLE) {
+ HSActivityManager.startArticleActivity(this, kbItemClicked, REQUEST_CODE_NEW_TICKET);
+ } else {
+ HSActivityManager.startSectionActivity(this, kbItemClicked, REQUEST_CODE_NEW_TICKET);
+ }
+ }
+
+ private int get_issues_position() {
+ return 1 - faq_position;
+ }
+
+ @Override
+ public void onPreExecute() {
+ mProgressBar.setVisibility(View.VISIBLE);
+ }
+
+ @Override
+ public void onProgressUpdate(int percent) {
+
+ }
+
+ @Override
+ public void onCancelled() {
+ mProgressBar.setVisibility(View.GONE);
+ }
+
+ @Override
+ public void onPostExecute(final Object object) {
+ if (object != null) {
+ getActivity().runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ mProgressBar.setVisibility(View.GONE);
+ if (object instanceof TaskFragment.TaskResponse) {
+ TaskFragment.TaskResponse response = (TaskFragment.TaskResponse) object;
+ fetchedKbArticles = response.kbArticles;
+ fetchedTickets = response.tickets;
+ mSearchFragment.setKBArticleList(fetchedKbArticles);
+ refreshList();
+ } else if (object instanceof HSError) {
+ HSUtils.showAlertDialog(getActivity(), getResources().getString(R.string.hs_error), ((HSError) object).message);
+ }
+ }
+ });
+ }
+ }
+
+ private class LocalAdapter extends HSBaseExpandableListAdapter {
+
+ public LocalAdapter(Context context) {
+ super(context);
+ }
+
+ @Override
+ public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
+ ChildViewHolder holder;
+
+ if (convertView == null) {
+ convertView = mLayoutInflater.inflate(R.layout.hs_expandable_child_home_default, null);
+ holder = new ChildViewHolder();
+ holder.textView1 = (TextView) convertView.findViewById(R.id.textView1);
+ convertView.setTag(holder);
+ } else {
+ holder = (ChildViewHolder) convertView.getTag();
+ }
+
+ if (groupPosition == faq_position) {
HSKBItem item = (HSKBItem) getChild(groupPosition, childPosition);
holder.textView1.setText(item.getSubject());
- }
- else if (groupPosition == get_issues_position()){
+ } else if (groupPosition == get_issues_position()) {
HSTicket item = (HSTicket) getChild(groupPosition, childPosition);
holder.textView1.setText(item.getSubject());
- }
-
- return convertView;
- }
-
- @Override
- public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
- ParentViewHolder holder;
-
- if (convertView == null) {
- convertView = mLayoutInflater.inflate(R.layout.hs_expandable_parent_home_default, null);
- holder = new ParentViewHolder();
- holder.textView1 = (TextView) convertView.findViewById(R.id.textView1);
- convertView.setTag(holder);
- }
- else {
- holder = (ParentViewHolder) convertView.getTag();
- }
-
- String text = (String) getGroup(groupPosition);
- holder.textView1.setText(text);
- return convertView;
- }
-
- private class ParentViewHolder {
- TextView textView1;
- }
-
- private class ChildViewHolder {
- TextView textView1;
- }
- }
+ }
- private int get_issues_position() {
- return 1 - faq_position;
+ return convertView;
+ }
+
+ @Override
+ public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
+ ParentViewHolder holder;
+
+ if (convertView == null) {
+ convertView = mLayoutInflater.inflate(R.layout.hs_expandable_parent_home_default, null);
+ holder = new ParentViewHolder();
+ holder.textView1 = (TextView) convertView.findViewById(R.id.textView1);
+ convertView.setTag(holder);
+ } else {
+ holder = (ParentViewHolder) convertView.getTag();
+ }
+
+ String text = (String) getGroup(groupPosition);
+ holder.textView1.setText(text);
+ return convertView;
+ }
+
+ private class ParentViewHolder {
+ TextView textView1;
+ }
+
+ private class ChildViewHolder {
+ TextView textView1;
+ }
}
}
diff --git a/helpstack/src/com/tenmiles/helpstack/fragments/SearchFragment.java b/helpstack/src/com/tenmiles/helpstack/fragments/SearchFragment.java
index 12e626c..3177364 100644
--- a/helpstack/src/com/tenmiles/helpstack/fragments/SearchFragment.java
+++ b/helpstack/src/com/tenmiles/helpstack/fragments/SearchFragment.java
@@ -109,7 +109,7 @@ public void setVisibility(boolean visible) {
}
public void setKBArticleList(HSKBItem[] fetchedKbArticles) {
- this.allKbArticles = fetchedKbArticles;
+ this.allKbArticles = (fetchedKbArticles == null) ? new HSKBItem[0] : fetchedKbArticles;
if (isSearchVisible()) {
searchAdapter.refreshList(allKbArticles);
searchAdapter.getFilter().filter("");
@@ -211,11 +211,11 @@ private class SearchAdapter extends BaseAdapter implements Filterable {
private CustomFilter filter;
public SearchAdapter(HSKBItem[] list) {
- this.allKBItems = list;
+ this.allKBItems = (list == null) ? new HSKBItem[0] : list;
}
public void refreshList(HSKBItem[] list) {
- this.allKBItems = list;
+ this.allKBItems = (list == null) ? new HSKBItem[0] : list;
}
@Override
diff --git a/helpstack/src/com/tenmiles/helpstack/fragments/TaskFragment.java b/helpstack/src/com/tenmiles/helpstack/fragments/TaskFragment.java
new file mode 100644
index 0000000..42f46c0
--- /dev/null
+++ b/helpstack/src/com/tenmiles/helpstack/fragments/TaskFragment.java
@@ -0,0 +1,259 @@
+package com.tenmiles.helpstack.fragments;
+
+import android.annotation.TargetApi;
+import android.app.Activity;
+import android.content.Context;
+import android.os.AsyncTask;
+import android.os.Build;
+import android.os.Bundle;
+import android.support.annotation.Nullable;
+import android.util.Log;
+
+import com.android.volley.NoConnectionError;
+import com.android.volley.Response;
+import com.android.volley.TimeoutError;
+import com.android.volley.VolleyError;
+import com.tenmiles.helpstack.R;
+import com.tenmiles.helpstack.activities.HSActivityParent;
+import com.tenmiles.helpstack.logic.HSSource;
+import com.tenmiles.helpstack.logic.OnFetchedArraySuccessListener;
+import com.tenmiles.helpstack.model.HSError;
+import com.tenmiles.helpstack.model.HSKBItem;
+import com.tenmiles.helpstack.model.HSTicket;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * Created by Sureshkumar on 24/12/16.
+ */
+
+
+/**
+ * TaskFragment manages a single background task and retains itself across
+ * configuration changes.
+ *
+ * ref: http://www.vogella.com/tutorials/AndroidFragments/article.html#headless-fragments
+ */
+@TargetApi(Build.VERSION_CODES.HONEYCOMB)
+public class TaskFragment extends HSFragmentParent {
+
+ protected static final String TASK_TICKETS = "task_tickets";
+ protected static final String TASK_KB_ARTICLES = "task_kb_articles";
+
+ private Activity mActivity;
+ private List mTasks;
+ private Task mTask;
+ private TaskResponse mResponse;
+ private TaskCallbacks mCallbacks;
+ private boolean mRunning;
+ private boolean isFailed;
+ private HSSource mGearSource;
+
+ /**
+ * Hold a reference to the parent Activity so we can report the task's current
+ * progress and results. The Android framework will pass us a reference to the
+ * newly created Activity after each configuration change.
+ */
+ @Override
+ public void onAttach(Context context) {
+ super.onAttach(context);
+ mActivity = (HSActivityParent) context;
+ }
+
+ /**
+ * This method is called once when the Fragment is first created.
+ */
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setRetainInstance(true);
+ }
+
+ @Override
+ public void onActivityCreated(@Nullable Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+ if (savedInstanceState == null)
+ mCallbacks = (TaskCallbacks) getTargetFragment();
+ }
+
+ /**
+ * Note that this method is not called when the Fragment is being
+ * retained across Activity instances. It will, however, be called when its
+ * parent Activity is being destroyed for good (such as when the user clicks
+ * the back button, etc.).
+ */
+ @Override
+ public void onDestroy() {
+ super.onDestroy();
+ cancelTask();
+ }
+
+ @Override
+ public void onDetach() {
+ super.onDetach();
+ mActivity = null;
+ }
+
+ /**
+ * Start the background task.
+ */
+ public void startTask(HSSource gearSource, String[] tasks) {
+ if (!mRunning) {
+ mGearSource = gearSource;
+ mTasks = new ArrayList<>(Arrays.asList(tasks));
+ mTask = new Task();
+ mTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, tasks);
+ mResponse = new TaskResponse();
+ mRunning = true;
+ }
+ }
+
+ /**
+ * Cancel the background task.
+ */
+ public void cancelTask() {
+ if (mRunning) {
+ mGearSource = null;
+ mTask.cancel(false);
+ mTask = null;
+ mRunning = false;
+ }
+ }
+
+ /**
+ * Returns the current state of the background task.
+ */
+ public boolean isRunning() {
+ return mRunning;
+ }
+
+ private void fetchKbArticles(final Task task) {
+ mGearSource.requestKBArticle("FAQ", null, new OnFetchedArraySuccessListener() {
+ @Override
+ public void onSuccess(Object[] kbArticles) {
+ mResponse.kbArticles = (HSKBItem[]) kbArticles;
+ mTasks.remove(TASK_KB_ARTICLES);
+ task.onPostExecute(mResponse);
+ }
+ }, new Response.ErrorListener() {
+
+ @Override
+ public void onErrorResponse(VolleyError error) {
+ task.onPostExecute(handleError(mActivity, error));
+ }
+ });
+ }
+
+ private void fetchTickets(final Task task) {
+ mGearSource.requestAllTickets(new OnFetchedArraySuccessListener() {
+ @Override
+ public void onSuccess(Object[] tickets) {
+ mResponse.tickets = (HSTicket[]) tickets;
+ mTasks.remove(TASK_TICKETS);
+ task.onPostExecute(mResponse);
+ }
+ }, new Response.ErrorListener() {
+ @Override
+ public void onErrorResponse(VolleyError error) {
+ task.onPostExecute(handleError(mActivity, error));
+ }
+ });
+ }
+
+ private HSError handleError(Context context, VolleyError error) {
+ HSError hsError = new HSError();
+ String message = "";
+ if ((error instanceof NoConnectionError) || (error instanceof TimeoutError)) {
+ hsError.initWithNetworkError(context.getResources().getString(R.string.hs_error_check_network_connection));
+ message = context.getResources().getString(R.string.hs_error_check_network_connection);
+ } else {
+ hsError.initWithAppError(context.getResources().getString(R.string.hs_error_fetching_articles_issues));
+ message = context.getResources().getString(R.string.hs_error_fetching_articles_issues);
+ }
+ hsError.message = message;
+ if(error.networkResponse != null)
+ hsError.httpResponseCode = error.networkResponse.statusCode;
+ return hsError;
+ }
+
+ /**
+ * Callback interface through which the fragment can report the task's
+ * progress and results back to the Activity.
+ */
+ static interface TaskCallbacks {
+ void onPreExecute();
+
+ void onProgressUpdate(int percent);
+
+ void onCancelled();
+
+ void onPostExecute(Object object);
+ }
+
+ private class Task extends AsyncTask {
+ @Override
+ protected void onPreExecute() {
+ // Proxy the call to the Activity.
+ if (mCallbacks != null)
+ mCallbacks.onPreExecute();
+ mRunning = true;
+ }
+
+ @Override
+ protected Object doInBackground(String... params) {
+ for (int i = 0; i < params.length; i++) {
+ Log.d("Loading task", params[i]);
+ if (params[i].equals(TASK_KB_ARTICLES)) {
+ fetchKbArticles(this);
+ } else if (params[i].equals(TASK_TICKETS)) {
+ fetchTickets(this);
+ }
+ }
+ return null;
+ }
+
+ @Override
+ protected void onProgressUpdate(Integer... percent) {
+ // Proxy the call to the Activity.
+ if (mCallbacks != null)
+ mCallbacks.onProgressUpdate(percent[0]);
+ }
+
+ @Override
+ protected void onCancelled() {
+ // Proxy the call to the Activity.
+ if (mCallbacks != null)
+ mCallbacks.onCancelled();
+ mRunning = false;
+ }
+
+ @Override
+ protected void onPostExecute(Object object) {
+ // Proxy the call to the Activity.
+ if(object != null) {
+ if (object instanceof HSError && !isFailed) {
+ mRunning = false;
+ isFailed = true;
+ if (mCallbacks != null)
+ mCallbacks.onPostExecute(object);
+ cancelTask();
+ }
+
+ if (mTasks.size() == 0 && !isFailed) {
+ mRunning = false;
+ if (mCallbacks != null)
+ mCallbacks.onPostExecute(object);
+ cancelTask();
+ }
+ }
+ }
+ }
+
+ class TaskResponse {
+ HSKBItem[] kbArticles;
+ HSTicket[] tickets;
+ }
+
+}
diff --git a/helpstack/src/com/tenmiles/helpstack/gears/HSDeskGear.java b/helpstack/src/com/tenmiles/helpstack/gears/HSDeskGear.java
index af637c1..57f4d92 100644
--- a/helpstack/src/com/tenmiles/helpstack/gears/HSDeskGear.java
+++ b/helpstack/src/com/tenmiles/helpstack/gears/HSDeskGear.java
@@ -158,7 +158,7 @@ public void onResponse(JSONObject responseObject) {
int emailsArrayLength = emailsArray.length();
for (int j = 0; j < emailsArrayLength; j++) {
- JSONObject emailDetails = couldBeValidUsersArray.getJSONObject(j);
+ JSONObject emailDetails = emailsArray.getJSONObject(j);
if (emailDetails.getString("value").equals(user.getEmail())) {
validUserDetail = couldBeValidUserDetail;
diff --git a/helpstack/src/com/tenmiles/helpstack/logic/HSGear.java b/helpstack/src/com/tenmiles/helpstack/logic/HSGear.java
index 025949b..ef389fb 100644
--- a/helpstack/src/com/tenmiles/helpstack/logic/HSGear.java
+++ b/helpstack/src/com/tenmiles/helpstack/logic/HSGear.java
@@ -249,5 +249,4 @@ public boolean canIgnoreTicketUpdateInformationAfterAddingReply() {
private boolean supportHtmlMessage = false;
private boolean ignoreTicketUpdateInformationAfterAddingReply = false;
-
}
diff --git a/helpstack/src/com/tenmiles/helpstack/logic/HSSource.java b/helpstack/src/com/tenmiles/helpstack/logic/HSSource.java
index 7f6b047..603d397 100644
--- a/helpstack/src/com/tenmiles/helpstack/logic/HSSource.java
+++ b/helpstack/src/com/tenmiles/helpstack/logic/HSSource.java
@@ -61,126 +61,175 @@
import java.util.Calendar;
public class HSSource {
- private static final String TAG = HSSource.class.getSimpleName();
-
- private static final String HELPSTACK_DIRECTORY = "helpstack";
- private static final String HELPSTACK_TICKETS_FILE_NAME = "tickets";
- private static final String HELPSTACK_TICKETS_USER_DATA = "user_credential";
+ private static final String TAG = HSSource.class.getSimpleName();
+
+ private static final String HELPSTACK_DIRECTORY = "helpstack";
+ private static final String HELPSTACK_TICKETS_FILE_NAME = "tickets";
+ private static final String HELPSTACK_TICKETS_USER_DATA = "user_credential";
private static final String HELPSTACK_DRAFT = "draft";
-
+
private static HSSource singletonInstance = null;
-
- /**
- *
- * @param context
- * @return singleton instance of this class.
- */
- public static HSSource getInstance(Context context) {
- if (singletonInstance == null) {
- synchronized (HSSource.class) { // 1
- if (singletonInstance == null) // 2
- {
- Log.d(TAG, "New Instance");
- singletonInstance = new HSSource(
- context.getApplicationContext()); // 3
- }
- }
- }
- // As this singleton can be called even before gear is set, refreshing it
- singletonInstance.setGear(HSHelpStack.getInstance(context).getGear());
- return singletonInstance;
- }
-
- private HSGear gear;
- private Context mContext;
- private RequestQueue mRequestQueue;
- private HSCachedTicket cachedTicket;
- private HSCachedUser cachedUser;
+ private HSGear gear;
+ private Context mContext;
+ private RequestQueue mRequestQueue;
+ private HSCachedTicket cachedTicket;
+ private HSCachedUser cachedUser;
private HSDraft draftObject;
-
- private HSSource(Context context) {
- this.mContext = context;
- setGear(HSHelpStack.getInstance(context).getGear());
- mRequestQueue = HSHelpStack.getInstance(context).getRequestQueue();
- refreshFieldsFromCache();
- }
-
- public void requestKBArticle(String cancelTag, HSKBItem section, OnFetchedArraySuccessListener success, ErrorListener errorListener ) {
-
- if (gear.haveImplementedKBFetching()) {
- gear.fetchKBArticle(cancelTag, section,mRequestQueue, new SuccessWrapper(success) {
+ private HSSource(Context context) {
+ this.mContext = context;
+ setGear(HSHelpStack.getInstance(context).getGear());
+ mRequestQueue = HSHelpStack.getInstance(context).getRequestQueue();
+ refreshFieldsFromCache();
+ }
+
+ /**
+ * @param context
+ * @return singleton instance of this class.
+ */
+ public static HSSource getInstance(Context context) {
+ if (singletonInstance == null) {
+ synchronized (HSSource.class) { // 1
+ if (singletonInstance == null) // 2
+ {
+ Log.d(TAG, "New Instance");
+ singletonInstance = new HSSource(
+ context.getApplicationContext()); // 3
+ }
+ }
+ }
+ // As this singleton can be called even before gear is set, refreshing it
+ singletonInstance.setGear(HSHelpStack.getInstance(context).getGear());
+ return singletonInstance;
+ }
+
+ private static String getDeviceInformation(Context activity) {
+ StringBuilder builder = new StringBuilder();
+ builder.append("\n\n\n");
+ builder.append("========");
+ builder.append("\nDevice brand: ");
+ builder.append(Build.MODEL);
+ builder.append("\nAndroid version: ");
+ builder.append(Build.VERSION.SDK_INT);
+ builder.append("\nApp package: ");
+ try {
+ builder.append(activity.getPackageManager().getPackageInfo(activity.getPackageName(), 0).packageName);
+ } catch (NameNotFoundException e) {
+ builder.append("NA");
+ }
+ builder.append("\nApp version: ");
+ try {
+ builder.append(activity.getPackageManager().getPackageInfo(activity.getPackageName(), 0).versionCode);
+ } catch (NameNotFoundException e) {
+ builder.append("NA");
+ }
+
+ return builder.toString();
+ }
+
+ public static void throwError(ErrorListener errorListener, String error) {
+ VolleyError volleyError = new VolleyError(error);
+ printErrorDescription(null, volleyError);
+ errorListener.onErrorResponse(volleyError);
+ }
+
+ private static void printErrorDescription(String methodName, VolleyError error) {
+ if (methodName == null) {
+ Log.e(HSHelpStack.LOG_TAG, "Error occurred in HelpStack");
+ } else {
+ Log.e(HSHelpStack.LOG_TAG, "Error occurred when executing " + methodName);
+ }
+
+ Log.e(HSHelpStack.LOG_TAG, error.toString());
+ if (error.getMessage() != null) {
+ Log.e(HSHelpStack.LOG_TAG, error.getMessage());
+ }
+
+ if (error.networkResponse != null && error.networkResponse.data != null) {
+ try {
+ Log.e(HSHelpStack.LOG_TAG, new String(error.networkResponse.data, "utf-8"));
+
+ } catch (UnsupportedEncodingException e) {
+ e.printStackTrace();
+ }
+ }
+
+ error.printStackTrace();
+ }
+
+ public void requestKBArticle(String cancelTag, HSKBItem section, OnFetchedArraySuccessListener success, ErrorListener errorListener) {
+
+ if (gear.haveImplementedKBFetching()) {
+ gear.fetchKBArticle(cancelTag, section, mRequestQueue, new SuccessWrapper(success) {
@Override
- public void onSuccess(Object[] successObject) {
- assert successObject != null : "It seems requestKBArticle was not implemented in gear" ;
-
- // Do your work here, may be caching, data validation etc.
- super.onSuccess(successObject);
- }
- }, new ErrorWrapper("Fetching KB articles", errorListener));
- }
- else {
- try {
- HSArticleReader reader = new HSArticleReader(gear.getLocalArticleResourceId());
- success.onSuccess(reader.readArticlesFromResource(mContext));
- } catch (XmlPullParserException e) {
- e.printStackTrace();
- throwError(errorListener, "Unable to parse local article XML");
- } catch (IOException e) {
- e.printStackTrace();
- throwError(errorListener, "Unable to read local article XML");
- }
- }
- }
-
- public void requestAllTickets(OnFetchedArraySuccessListener success, ErrorListener error ) {
- if (cachedTicket == null) {
- success.onSuccess(new HSTicket[0]);
- }
- else {
- success.onSuccess(cachedTicket.getTickets());
- }
- }
-
- public void checkForUserDetailsValidity(String cancelTag, String firstName, String lastName, String email,OnFetchedSuccessListener success, ErrorListener errorListener) {
- gear.registerNewUser(cancelTag, firstName, lastName, email, mRequestQueue, success, new ErrorWrapper("Registering New User", errorListener));
- }
-
- public void createNewTicket(String cancelTag, HSUser user, String subject, String message, HSAttachment[] attachment, OnNewTicketFetchedSuccessListener successListener, ErrorListener errorListener) {
-
- HSUploadAttachment[] upload_attachments = convertAttachmentArrayToUploadAttachment(attachment);
- message = message + getDeviceInformation(mContext);
-
- if (gear.canUploadMessageAsHtmlString()) {
- message = Html.toHtml(new SpannableString(message));
- }
-
- gear.createNewTicket(cancelTag, user, subject, message, upload_attachments, mRequestQueue, new NewTicketSuccessWrapper(successListener) {
-
- @Override
- public void onSuccess(HSUser udpatedUserDetail, HSTicket ticket) {
-
- // Save ticket and user details in cache
- // Save properties also later.
- doSaveNewTicketPropertiesForGearInCache(ticket);
- doSaveNewUserPropertiesForGearInCache(udpatedUserDetail);
- super.onSuccess(udpatedUserDetail, ticket);
- }
- }, new ErrorWrapper("Creating New Ticket", errorListener));
-
- }
-
- public void requestAllUpdatesOnTicket(String cancelTag, HSTicket ticket, OnFetchedArraySuccessListener success, ErrorListener errorListener ) {
- gear.fetchAllUpdateOnTicket(cancelTag, ticket, cachedUser.getUser(), mRequestQueue, success, new ErrorWrapper("Fetching updates on Ticket", errorListener));
- }
-
- public void addReplyOnATicket(String cancelTag, String message, HSAttachment[] attachments, HSTicket ticket, OnFetchedSuccessListener success, ErrorListener errorListener) {
-
- if (gear.canUploadMessageAsHtmlString()) {
- message = Html.toHtml(new SpannableString(message));
- }
-
- gear.addReplyOnATicket(cancelTag, message, convertAttachmentArrayToUploadAttachment(attachments), ticket, getUser(), mRequestQueue, new OnFetchedSuccessListenerWrapper(success, message, attachments) {
+ public void onSuccess(Object[] successObject) {
+ assert successObject != null : "It seems requestKBArticle was not implemented in gear";
+
+ // Do your work here, may be caching, data validation etc.
+ super.onSuccess(successObject);
+ }
+ }, new ErrorWrapper("Fetching KB articles", errorListener));
+ } else {
+ try {
+ HSArticleReader reader = new HSArticleReader(gear.getLocalArticleResourceId());
+ success.onSuccess(reader.readArticlesFromResource(mContext));
+ } catch (XmlPullParserException e) {
+ e.printStackTrace();
+ throwError(errorListener, "Unable to parse local article XML");
+ } catch (IOException e) {
+ e.printStackTrace();
+ throwError(errorListener, "Unable to read local article XML");
+ }
+ }
+ }
+
+ public void requestAllTickets(OnFetchedArraySuccessListener success, ErrorListener error) {
+ if (cachedTicket == null) {
+ success.onSuccess(new HSTicket[0]);
+ } else {
+ success.onSuccess(cachedTicket.getTickets());
+ }
+ }
+
+ public void checkForUserDetailsValidity(String cancelTag, String firstName, String lastName, String email, OnFetchedSuccessListener success, ErrorListener errorListener) {
+ gear.registerNewUser(cancelTag, firstName, lastName, email, mRequestQueue, success, new ErrorWrapper("Registering New User", errorListener));
+ }
+
+ public void createNewTicket(String cancelTag, HSUser user, String subject, String message, HSAttachment[] attachment, OnNewTicketFetchedSuccessListener successListener, ErrorListener errorListener) {
+
+ HSUploadAttachment[] upload_attachments = convertAttachmentArrayToUploadAttachment(attachment);
+ message = message + getDeviceInformation(mContext);
+
+ if (gear.canUploadMessageAsHtmlString()) {
+ message = Html.toHtml(new SpannableString(message));
+ }
+
+ gear.createNewTicket(cancelTag, user, subject, message, upload_attachments, mRequestQueue, new NewTicketSuccessWrapper(successListener) {
+
+ @Override
+ public void onSuccess(HSUser udpatedUserDetail, HSTicket ticket) {
+
+ // Save ticket and user details in cache
+ // Save properties also later.
+ doSaveNewTicketPropertiesForGearInCache(ticket);
+ doSaveNewUserPropertiesForGearInCache(udpatedUserDetail);
+ super.onSuccess(udpatedUserDetail, ticket);
+ }
+ }, new ErrorWrapper("Creating New Ticket", errorListener));
+
+ }
+
+ public void requestAllUpdatesOnTicket(String cancelTag, HSTicket ticket, OnFetchedArraySuccessListener success, ErrorListener errorListener) {
+ gear.fetchAllUpdateOnTicket(cancelTag, ticket, cachedUser.getUser(), mRequestQueue, success, new ErrorWrapper("Fetching updates on Ticket", errorListener));
+ }
+
+ public void addReplyOnATicket(String cancelTag, String message, HSAttachment[] attachments, HSTicket ticket, OnFetchedSuccessListener success, ErrorListener errorListener) {
+
+ if (gear.canUploadMessageAsHtmlString()) {
+ message = Html.toHtml(new SpannableString(message));
+ }
+
+ gear.addReplyOnATicket(cancelTag, message, convertAttachmentArrayToUploadAttachment(attachments), ticket, getUser(), mRequestQueue, new OnFetchedSuccessListenerWrapper(success, message, attachments) {
@Override
public void onSuccess(Object successObject) {
@@ -188,71 +237,70 @@ public void onSuccess(Object successObject) {
if (gear.canIgnoreTicketUpdateInformationAfterAddingReply()) {
HSTicketUpdate update = HSTicketUpdate.createUpdateByUser(null, null, this.message, Calendar.getInstance().getTime(), this.attachments);
super.onSuccess(update);
- }
- else {
+ } else {
super.onSuccess(successObject);
}
}
}, new ErrorWrapper("Adding reply to a ticket", errorListener));
- }
-
- public HSGear getGear() {
- return gear;
- }
-
- private void setGear(HSGear gear) {
- this.gear = gear;
- }
-
- public boolean isNewUser() {
- return cachedUser.getUser() == null;
- }
-
- public void refreshUser() {
- doReadUserFromCache();
- }
-
- public HSUser getUser() {
- return cachedUser.getUser();
- }
+ }
+
+ public HSGear getGear() {
+ return gear;
+ }
+
+ private void setGear(HSGear gear) {
+ this.gear = gear;
+ }
+
+ public boolean isNewUser() {
+ return cachedUser.getUser() == null;
+ }
+
+ public void refreshUser() {
+ doReadUserFromCache();
+ }
+
+ public HSUser getUser() {
+ return cachedUser.getUser();
+ }
public String getDraftSubject() {
- if(draftObject != null) {
+ if (draftObject != null) {
return draftObject.getSubject();
}
return null;
}
public String getDraftMessage() {
- if(draftObject != null) {
+ if (draftObject != null) {
return draftObject.getMessage();
}
return null;
}
public HSUser getDraftUser() {
- if(draftObject != null) {
+ if (draftObject != null) {
return draftObject.getDraftUser();
}
return null;
}
public HSAttachment[] getDraftAttachments() {
- if(draftObject != null) {
+ if (draftObject != null) {
return draftObject.getAttachments();
}
return null;
}
public String getDraftReplyMessage() {
- if(draftObject != null) {
+ if (draftObject != null) {
return draftObject.getDraftReplyMessage();
}
return null;
}
public HSAttachment[] getDraftReplyAttachments() {
- if(draftObject != null) {
+ if (draftObject != null) {
return draftObject.getDraftReplyAttachments();
}
return null;
@@ -270,108 +318,82 @@ public void saveReplyDetailsInDraft(String message, HSAttachment[] attachmentsAr
doSaveReplyDraftForGearInCache(message, attachmentsArray);
}
- public boolean haveImplementedTicketFetching() {
- return gear.haveImplementedTicketFetching();
- }
-
- public String getSupportEmailAddress() {
- return gear.getCompanySupportEmailAddress();
- }
-
- /***
- *
- * Depending on the setting set on gear, it launches new ticket activity.
- *
- * if email : launches email [Done]
- * else:
- * if user logged in : launches user details [Done]
- * else: launches new ticket [Done]
- *
- * @param fragment
- * @param requestCode
- */
- public void launchCreateNewTicketScreen(HSFragmentParent fragment, int requestCode) {
-
- if (haveImplementedTicketFetching()) {
- if(isNewUser()) {
+ public boolean haveImplementedTicketFetching() {
+ return gear.haveImplementedTicketFetching();
+ }
+
+ public String getSupportEmailAddress() {
+ return gear.getCompanySupportEmailAddress();
+ }
+
+ /***
+ * Depending on the setting set on gear, it launches new ticket activity.
+ *
+ * if email : launches email [Done]
+ * else:
+ * if user logged in : launches user details [Done]
+ * else: launches new ticket [Done]
+ *
+ * @param fragment
+ * @param requestCode
+ */
+ public void launchCreateNewTicketScreen(HSFragmentParent fragment, int requestCode) {
+
+ if (haveImplementedTicketFetching()) {
+ if (isNewUser()) {
HSActivityManager.startNewIssueActivity(fragment, null, requestCode);
- }
- else {
- HSActivityManager.startNewIssueActivity(fragment, getUser(), requestCode);
- }
- }
- else {
- launchEmailAppWithEmailAddress(fragment.getActivity());
- }
- }
-
- public void launchEmailAppWithEmailAddress(Activity activity) {
- Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
- emailIntent.setType("plain/text");
- emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{ getSupportEmailAddress()});
- emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
- emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, getDeviceInformation(activity));
-
- activity.startActivity(Intent.createChooser(emailIntent, "Email"));
- }
-
- private static String getDeviceInformation(Context activity) {
- StringBuilder builder = new StringBuilder();
- builder.append("\n\n\n");
- builder.append("========");
- builder.append("\nDevice brand: ");
- builder.append(Build.MODEL);
- builder.append("\nAndroid version: ");
- builder.append(Build.VERSION.SDK_INT);
- builder.append("\nApp package :");
- try {
- builder.append(activity.getPackageManager().getPackageInfo(activity.getPackageName(),0).packageName);
- } catch (NameNotFoundException e) {
- builder.append("NA");
- }
- builder.append("\nApp version :");
- try {
- builder.append(activity.getPackageManager().getPackageInfo(activity.getPackageName(),0).versionCode);
- } catch (NameNotFoundException e) {
- builder.append("NA");
- }
-
- return builder.toString();
- }
-
- public void cancelOperation(String cancelTag) {
- mRequestQueue.cancelAll(cancelTag);
- }
-
- /////////////////////////////////////////////////
- //////// Utility Functions /////////////////
- /////////////////////////////////////////////////
-
- public void refreshFieldsFromCache() {
- // read the ticket data from cache and maintain here
- doReadTicketsFromCache();
- doReadUserFromCache();
+ } else {
+ HSActivityManager.startNewIssueActivity(fragment, getUser(), requestCode);
+ }
+ } else {
+ launchEmailAppWithEmailAddress(fragment.getActivity());
+ }
+ }
+
+ /////////////////////////////////////////////////
+ //////// Utility Functions /////////////////
+ /////////////////////////////////////////////////
+
+ public void launchEmailAppWithEmailAddress(Activity activity) {
+ Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
+ emailIntent.setType("plain/text");
+ emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{getSupportEmailAddress()});
+ emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
+ emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, getDeviceInformation(activity));
+
+ activity.startActivity(Intent.createChooser(emailIntent, "Email"));
+ }
+
+ public void cancelOperation(String cancelTag) {
+ mRequestQueue.cancelAll(cancelTag);
+ }
+
+ public void refreshFieldsFromCache() {
+ // read the ticket data from cache and maintain here
+ doReadTicketsFromCache();
+ doReadUserFromCache();
doReadDraftFromCache();
- }
-
- /**
- * Opens a file and read its content. Return null if any error occured or file not found
- * @param file
- * @return
- */
- private String readJsonFromFile(File file) {
-
- if (!file.exists()) {
- return null;
- }
-
- String json = null;
- FileInputStream inputStream;
-
- try {
- StringBuilder datax = new StringBuilder();
- inputStream = new FileInputStream(file);
- InputStreamReader isr = new InputStreamReader(inputStream);
+ }
+
+ /**
+ * Opens a file and read its content. Return null if any error occured or file not found
+ *
+ * @param file
+ * @return
+ */
+ private String readJsonFromFile(File file) {
+
+ if (!file.exists()) {
+ return null;
+ }
+
+ String json = null;
+ FileInputStream inputStream;
+
+ try {
+ StringBuilder datax = new StringBuilder();
+ inputStream = new FileInputStream(file);
+ InputStreamReader isr = new InputStreamReader(inputStream);
BufferedReader bufferReader = new BufferedReader(isr);
String readString = bufferReader.readLine();
@@ -381,85 +403,82 @@ private String readJsonFromFile(File file) {
}
isr.close();
-
+
json = datax.toString();
return json;
-
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return null;
- }
-
- private void writeJsonIntoFile (File file, String json) {
- FileOutputStream outputStream;
-
- try {
- outputStream = new FileOutputStream(file);
- outputStream.write(json.getBytes());
- outputStream.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- protected void doSaveNewTicketPropertiesForGearInCache(HSTicket ticket) {
+
+ } catch (FileNotFoundException e) {
+ e.printStackTrace();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+ private void writeJsonIntoFile(File file, String json) {
+ FileOutputStream outputStream;
+
+ try {
+ outputStream = new FileOutputStream(file);
+ outputStream.write(json.getBytes());
+ outputStream.close();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ protected void doSaveNewTicketPropertiesForGearInCache(HSTicket ticket) {
cachedTicket.addTicketAtStart(ticket);
-
- Gson gson = new Gson();
- String ticketsgson = gson.toJson(cachedTicket);
+
+ Gson gson = new Gson();
+ String ticketsgson = gson.toJson(cachedTicket);
File ticketFile = new File(getProjectDirectory(), HELPSTACK_TICKETS_FILE_NAME);
-
- writeJsonIntoFile(ticketFile, ticketsgson);
- }
-
- protected void doSaveNewUserPropertiesForGearInCache(HSUser user) {
- cachedUser.setUser(user);
-
- Gson gson = new Gson();
- String userjson = gson.toJson(cachedUser);
+
+ writeJsonIntoFile(ticketFile, ticketsgson);
+ }
+
+ protected void doSaveNewUserPropertiesForGearInCache(HSUser user) {
+ cachedUser.setUser(user);
+
+ Gson gson = new Gson();
+ String userjson = gson.toJson(cachedUser);
File userFile = new File(getProjectDirectory(), HELPSTACK_TICKETS_USER_DATA);
-
- writeJsonIntoFile(userFile, userjson);
- }
-
- protected void doReadTicketsFromCache() {
- File ticketFile = new File(getProjectDirectory(), HELPSTACK_TICKETS_FILE_NAME);
+
+ writeJsonIntoFile(userFile, userjson);
+ }
+
+ protected void doReadTicketsFromCache() {
+ File ticketFile = new File(getProjectDirectory(), HELPSTACK_TICKETS_FILE_NAME);
String json = readJsonFromFile(ticketFile);
-
- if (json == null) {
- cachedTicket = new HSCachedTicket();
- }
- else {
- Gson gson = new Gson();
- cachedTicket = gson.fromJson(json, HSCachedTicket.class);
- }
- }
-
+
+ if (json == null) {
+ cachedTicket = new HSCachedTicket();
+ } else {
+ Gson gson = new Gson();
+ cachedTicket = gson.fromJson(json, HSCachedTicket.class);
+ }
+ }
+
protected void doReadUserFromCache() {
File userFile = new File(getProjectDirectory(), HELPSTACK_TICKETS_USER_DATA);
String json = readJsonFromFile(userFile);
-
- if (json == null) {
- cachedUser = new HSCachedUser();
- }
- else {
- Gson gson = new Gson();
- cachedUser = gson.fromJson(json, HSCachedUser.class);
- }
- }
+
+ if (json == null) {
+ cachedUser = new HSCachedUser();
+ } else {
+ Gson gson = new Gson();
+ cachedUser = gson.fromJson(json, HSCachedUser.class);
+ }
+ }
protected void doReadDraftFromCache() {
File draftFile = new File(getProjectDirectory(), HELPSTACK_DRAFT);
String json = readJsonFromFile(draftFile);
if (json == null) {
- draftObject = new HSDraft();
- }
- else {
- Gson gson = new Gson();
+ draftObject = new HSDraft();
+ } else {
+ Gson gson = new Gson();
draftObject = gson.fromJson(json, HSDraft.class);
}
}
@@ -484,7 +503,6 @@ protected void doSaveReplyDraftForGearInCache(String message, HSAttachment[] att
writeDraftIntoFile();
}
-
private void writeDraftIntoFile() {
Gson gson = new Gson();
String draftJson = gson.toJson(draftObject);
@@ -494,12 +512,12 @@ private void writeDraftIntoFile() {
}
protected File getProjectDirectory() {
- File projDir = new File(mContext.getFilesDir(), HELPSTACK_DIRECTORY);
- if (!projDir.exists())
- projDir.mkdirs();
-
- return projDir;
- }
+ File projDir = new File(mContext.getFilesDir(), HELPSTACK_DIRECTORY);
+ if (!projDir.exists())
+ projDir.mkdirs();
+
+ return projDir;
+ }
public void clearTicketDraft() {
saveTicketDetailsInDraft("", "", null);
@@ -509,57 +527,76 @@ public void clearReplyDraft() {
saveReplyDetailsInDraft("", null);
}
+ protected HSUploadAttachment[] convertAttachmentArrayToUploadAttachment(HSAttachment[] attachment) {
+
+ HSUploadAttachment[] upload_attachments = new HSUploadAttachment[0];
+
+ if (attachment != null && attachment.length > 0) {
+ int attachmentCount = gear.getNumberOfAttachmentGearCanHandle();
+ assert attachmentCount >= attachment.length : "Gear cannot handle more than " + attachmentCount + " attachments";
+ upload_attachments = new HSUploadAttachment[attachment.length];
+ for (int i = 0; i < upload_attachments.length; i++) {
+ upload_attachments[i] = new HSUploadAttachment(mContext, attachment[i]);
+ }
+ }
+
+ return upload_attachments;
+ }
+
+ public void deleteAllFiles() {
+ try {
+ File dir = getProjectDirectory();
+ deleteRecursive(dir);
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ }
+ }
+
+ private void deleteRecursive(File fileOrDirectory) {
+ if (fileOrDirectory != null) {
+ if (fileOrDirectory.isDirectory())
+ for (File child : fileOrDirectory.listFiles())
+ deleteRecursive(child);
+
+ fileOrDirectory.delete();
+ }
+ }
+
private class NewTicketSuccessWrapper implements OnNewTicketFetchedSuccessListener {
- private OnNewTicketFetchedSuccessListener lastListener;
-
- public NewTicketSuccessWrapper(OnNewTicketFetchedSuccessListener lastListener) {
- this.lastListener = lastListener;
- }
-
- @Override
- public void onSuccess(HSUser udpatedUserDetail, HSTicket ticket) {
- if (lastListener != null)
- lastListener.onSuccess(udpatedUserDetail, ticket);
- }
- }
-
- protected HSUploadAttachment[] convertAttachmentArrayToUploadAttachment(HSAttachment[] attachment) {
-
- HSUploadAttachment[] upload_attachments = new HSUploadAttachment[0];
-
- if (attachment != null && attachment.length > 0) {
- int attachmentCount = gear.getNumberOfAttachmentGearCanHandle();
- assert attachmentCount >= attachment.length : "Gear cannot handle more than "+attachmentCount+" attachments";
- upload_attachments = new HSUploadAttachment[attachment.length];
- for (int i = 0; i < upload_attachments.length; i++) {
- upload_attachments[i] = new HSUploadAttachment(mContext, attachment[i]);
- }
- }
-
- return upload_attachments;
- }
-
- private class SuccessWrapper implements OnFetchedArraySuccessListener {
-
- private OnFetchedArraySuccessListener lastListener;
-
- public SuccessWrapper(OnFetchedArraySuccessListener lastListener) {
- this.lastListener = lastListener;
- }
-
- @Override
- public void onSuccess(Object[] successObject) {
- if (lastListener != null)
- lastListener.onSuccess(successObject);
- }
- }
+ private OnNewTicketFetchedSuccessListener lastListener;
+
+ public NewTicketSuccessWrapper(OnNewTicketFetchedSuccessListener lastListener) {
+ this.lastListener = lastListener;
+ }
+
+ @Override
+ public void onSuccess(HSUser udpatedUserDetail, HSTicket ticket) {
+ if (lastListener != null)
+ lastListener.onSuccess(udpatedUserDetail, ticket);
+ }
+ }
+
+ private class SuccessWrapper implements OnFetchedArraySuccessListener {
+
+ private OnFetchedArraySuccessListener lastListener;
+
+ public SuccessWrapper(OnFetchedArraySuccessListener lastListener) {
+ this.lastListener = lastListener;
+ }
+
+ @Override
+ public void onSuccess(Object[] successObject) {
+ if (lastListener != null)
+ lastListener.onSuccess(successObject);
+ }
+ }
private class OnFetchedSuccessListenerWrapper implements OnFetchedSuccessListener {
- private OnFetchedSuccessListener listener;
protected String message;
protected HSAttachment[] attachments;
+ private OnFetchedSuccessListener listener;
private OnFetchedSuccessListenerWrapper(OnFetchedSuccessListener listener, String message, HSAttachment[] attachments) {
this.listener = listener;
@@ -574,52 +611,21 @@ public void onSuccess(Object successObject) {
}
}
}
-
- private class ErrorWrapper implements ErrorListener {
-
- private ErrorListener errorListener;
- private String methodName;
-
- public ErrorWrapper(String methodName, ErrorListener errorListener) {
- this.errorListener = errorListener;
- this.methodName = methodName;
- }
-
- @Override
- public void onErrorResponse(VolleyError error) {
- printErrorDescription(methodName, error);
- this.errorListener.onErrorResponse(error);
- }
- }
-
- public static void throwError(ErrorListener errorListener, String error) {
- VolleyError volleyError = new VolleyError(error);
- printErrorDescription(null, volleyError);
- errorListener.onErrorResponse(volleyError);
- }
-
- private static void printErrorDescription (String methodName, VolleyError error) {
- if (methodName == null) {
- Log.e(HSHelpStack.LOG_TAG, "Error occurred in HelpStack");
- }
- else {
- Log.e(HSHelpStack.LOG_TAG, "Error occurred when executing " + methodName);
- }
-
- Log.e(HSHelpStack.LOG_TAG, error.toString());
- if (error.getMessage() != null) {
- Log.e(HSHelpStack.LOG_TAG, error.getMessage());
- }
-
- if (error.networkResponse != null && error.networkResponse.data != null) {
- try {
- Log.e(HSHelpStack.LOG_TAG, new String(error.networkResponse.data, "utf-8"));
-
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- }
-
- error.printStackTrace();
- }
+
+ private class ErrorWrapper implements ErrorListener {
+
+ private ErrorListener errorListener;
+ private String methodName;
+
+ public ErrorWrapper(String methodName, ErrorListener errorListener) {
+ this.errorListener = errorListener;
+ this.methodName = methodName;
+ }
+
+ @Override
+ public void onErrorResponse(VolleyError error) {
+ printErrorDescription(methodName, error);
+ this.errorListener.onErrorResponse(error);
+ }
+ }
}
diff --git a/helpstack/src/com/tenmiles/helpstack/logic/HSUtils.java b/helpstack/src/com/tenmiles/helpstack/logic/HSUtils.java
index 37a1d04..8c48c9f 100644
--- a/helpstack/src/com/tenmiles/helpstack/logic/HSUtils.java
+++ b/helpstack/src/com/tenmiles/helpstack/logic/HSUtils.java
@@ -26,6 +26,9 @@
import android.content.Context;
import android.content.DialogInterface;
+import com.google.gson.Gson;
+
+import java.lang.reflect.Type;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
@@ -98,4 +101,17 @@ public void onClick(DialogInterface dialog, int which) {
});
dialog.show();
}
+
+ public static T getObjectFromJson(String json, Type type) {
+ Gson gson = new Gson();
+ if ((json != null) && (json.isEmpty())) {
+ return null;
+ }
+ return gson.fromJson(json, type);
+ }
+
+ public static String convertObjectToStringJson(T object, Type type) {
+ Gson gson = new Gson();
+ return gson.toJson(object, type);
+ }
}
diff --git a/helpstack/src/com/tenmiles/helpstack/model/HSError.java b/helpstack/src/com/tenmiles/helpstack/model/HSError.java
new file mode 100644
index 0000000..fefc7c1
--- /dev/null
+++ b/helpstack/src/com/tenmiles/helpstack/model/HSError.java
@@ -0,0 +1,44 @@
+package com.tenmiles.helpstack.model;
+
+/**
+ * Created by muthukumarkrishnan on 10/15/15.
+ */
+public class HSError implements Cloneable {
+ private enum ErrorCode {
+ AppError,
+ HttpError,
+ NetworkError
+ }
+
+ public String message;
+ public int httpResponseCode;
+ public ErrorCode errorCode;
+
+ public void initWithAppError(String msg) {
+ message = msg;
+ errorCode = ErrorCode.AppError;
+ }
+
+ public void initWithHttpError(int responseCode, String msg) {
+ errorCode = ErrorCode.HttpError;
+ httpResponseCode = responseCode;
+ message = msg;
+ }
+
+ public void initWithNetworkError(String msg) {
+ errorCode = ErrorCode.NetworkError;
+ message = msg;
+ }
+
+ public boolean isAppError() {
+ return (errorCode == ErrorCode.AppError);
+ }
+
+ public boolean isNetworkError() {
+ return (errorCode == ErrorCode.NetworkError);
+ }
+
+ public boolean isHttpError() {
+ return (errorCode == ErrorCode.HttpError);
+ }
+}
diff --git a/helpstack/src/com/tenmiles/helpstack/service/AttachmentDownloadReceiver.java b/helpstack/src/com/tenmiles/helpstack/service/AttachmentDownloadReceiver.java
index 1877928..a71077d 100644
--- a/helpstack/src/com/tenmiles/helpstack/service/AttachmentDownloadReceiver.java
+++ b/helpstack/src/com/tenmiles/helpstack/service/AttachmentDownloadReceiver.java
@@ -33,85 +33,81 @@
import android.database.Cursor;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
-
import com.tenmiles.helpstack.R;
public class AttachmentDownloadReceiver extends BroadcastReceiver {
- private static final int NOTIFICATION_ID = 1008;
- private static final int PENDING_INTENT_REQUEST_CODE = 108;
+ private static final int NOTIFICATION_ID = 1008;
+ private static final int PENDING_INTENT_REQUEST_CODE = 108;
- @Override
- public void onReceive(Context context, Intent intent) {
- String action = intent.getAction();
- String intendedPackage = intent.getPackage();
- String contextPackage = context.getPackageName();
-
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ String action = intent.getAction();
+ String intendedPackage = intent.getPackage();
+ String contextPackage = (context.getPackageName() != null) ? context.getPackageName() : "";
if (intendedPackage.equals(contextPackage) && DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
- downloadCompleted(context, intent);
- }
- else if (intendedPackage.equals(contextPackage) && DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(action)) {
- notificationClicked(context, intent);
+ downloadCompleted(context, intent);
+ } else if (intendedPackage.equals(contextPackage) && DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(action)) {
+ notificationClicked(context, intent);
}
- }
-
- private void notificationClicked(Context context, Intent intent) {
- Intent i = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
- i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- context.startActivity(i);
- }
-
- private void downloadCompleted(Context context, Intent intent) {
- //Files are ready
- String filename = context.getString(R.string.hs_attachment);
- String filepath = null;
- String mediaType = null;
+ }
+
+ private void notificationClicked(Context context, Intent intent) {
+ Intent i = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
+ i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+ context.startActivity(i);
+ }
+
+ private void downloadCompleted(Context context, Intent intent) {
+ //Files are ready
+ String filename = context.getString(R.string.hs_attachment);
+ String filepath = null;
+ String mediaType = null;
DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
- long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
+ long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
StringBuilder text = new StringBuilder();
- Query query = new Query();
- query.setFilterById(downloadId);
- Cursor c = dm.query(query);
- if (c.moveToFirst()) {
- int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
- filename = c.getString(c.getColumnIndex(DownloadManager.COLUMN_TITLE));
- filepath = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
- mediaType = c.getString(c.getColumnIndex(DownloadManager.COLUMN_MEDIA_TYPE));
- if(status == DownloadManager.STATUS_SUCCESSFUL) {
- text.append(context.getString(R.string.hs_download_complete));
- }
- else {
- text.append(context.getString(R.string.hs_error_during_download));
- }
- }
-
- NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
-
- NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context);
- notificationBuilder.setAutoCancel(true);
- notificationBuilder.setContentText(text.toString());
- notificationBuilder.setContentTitle(filename);
- notificationBuilder.setSmallIcon(R.drawable.hs_download_light);
- notificationBuilder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);
- notificationBuilder.setContentIntent(getPendingIntent(context));
-
- notificationManager.notify(filename, NOTIFICATION_ID, notificationBuilder.build());
- }
+ Query query = new Query();
+ query.setFilterById(downloadId);
+ Cursor c = dm.query(query);
+ if (c.moveToFirst()) {
+ int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
+ filename = c.getString(c.getColumnIndex(DownloadManager.COLUMN_TITLE));
+ filepath = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
+ mediaType = c.getString(c.getColumnIndex(DownloadManager.COLUMN_MEDIA_TYPE));
+ if (status == DownloadManager.STATUS_SUCCESSFUL) {
+ text.append(context.getString(R.string.hs_download_complete));
+ } else {
+ text.append(context.getString(R.string.hs_error_during_download));
+ }
+ }
+
+ NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
+
+ NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context);
+ notificationBuilder.setAutoCancel(true);
+ notificationBuilder.setContentText(text.toString());
+ notificationBuilder.setContentTitle(filename);
+ notificationBuilder.setSmallIcon(R.drawable.hs_download_light);
+ notificationBuilder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);
+ notificationBuilder.setContentIntent(getPendingIntent(context));
+
+ notificationManager.notify(filename, NOTIFICATION_ID, notificationBuilder.build());
+ }
+
+ public PendingIntent getPendingIntent(Context context, String filename, String mediatype) {
+ Intent i = new Intent(Intent.ACTION_VIEW);
+ i.setDataAndType(Uri.parse(filename), mediatype);
+ i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+ PendingIntent pendinIntent = PendingIntent.getActivity(context, PENDING_INTENT_REQUEST_CODE, Intent.createChooser(i, context.getString(R.string.hs_open_with)), PendingIntent.FLAG_UPDATE_CURRENT);
+ return pendinIntent;
+ }
+
+ public PendingIntent getPendingIntent(Context context) {
+ Intent i = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
+ i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+ PendingIntent pendinIntent = PendingIntent.getActivity(context, PENDING_INTENT_REQUEST_CODE, i, PendingIntent.FLAG_UPDATE_CURRENT);
+ return pendinIntent;
+ }
- public PendingIntent getPendingIntent(Context context, String filename, String mediatype) {
- Intent i = new Intent(Intent.ACTION_VIEW);
- i.setDataAndType(Uri.parse(filename), mediatype);
- i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- PendingIntent pendinIntent = PendingIntent.getActivity(context, PENDING_INTENT_REQUEST_CODE, Intent.createChooser(i, context.getString(R.string.hs_open_with)), PendingIntent.FLAG_UPDATE_CURRENT);
- return pendinIntent;
- }
-
- public PendingIntent getPendingIntent(Context context) {
- Intent i = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
- i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- PendingIntent pendinIntent = PendingIntent.getActivity(context, PENDING_INTENT_REQUEST_CODE, i, PendingIntent.FLAG_UPDATE_CURRENT);
- return pendinIntent;
- }
-
}