/v3.2/nimbits-android/src/com/nimbits/android/activity/StartActivity.java

http://nimbits-server.googlecode.com/ · Java · 1224 lines · 892 code · 275 blank · 57 comment · 129 complexity · 055a6724faa1350aa70ed276ef77277a MD5 · raw file

  1. package com.nimbits.android.activity;
  2. import android.app.AlertDialog;
  3. import android.app.Dialog;
  4. import android.app.ListActivity;
  5. import android.app.ProgressDialog;
  6. import android.content.ContentValues;
  7. import android.content.Context;
  8. import android.content.DialogInterface;
  9. import android.content.Intent;
  10. import android.database.Cursor;
  11. import android.database.sqlite.SQLiteDatabase;
  12. import android.os.Bundle;
  13. import android.os.Handler;
  14. import android.os.Message;
  15. import android.util.Log;
  16. import android.view.*;
  17. import android.view.GestureDetector.OnGestureListener;
  18. import android.view.View.OnClickListener;
  19. import android.widget.*;
  20. import com.nimbits.android.CustomDialog;
  21. import com.nimbits.android.DisplayType;
  22. import com.nimbits.android.ImageCursorAdapter;
  23. import com.nimbits.android.R;
  24. import com.nimbits.android.account.OwnerAccountFactory;
  25. import com.nimbits.android.dao.LocalDatabaseDaoFactory;
  26. import com.nimbits.android.database.DatabaseHelperFactory;
  27. import com.nimbits.android.json.GsonFactory;
  28. import com.nimbits.client.model.Const;
  29. import com.nimbits.client.model.category.Category;
  30. import com.nimbits.client.model.category.CategoryName;
  31. import com.nimbits.client.model.common.CommonFactoryLocator;
  32. import com.nimbits.client.model.diagram.Diagram;
  33. import com.nimbits.client.model.point.Point;
  34. import com.nimbits.client.model.point.PointModel;
  35. import com.nimbits.client.model.point.PointName;
  36. import com.nimbits.client.model.value.Value;
  37. import org.apache.http.cookie.Cookie;
  38. import java.io.UnsupportedEncodingException;
  39. import java.util.List;
  40. public class StartActivity extends ListActivity implements OnGestureListener {
  41. private static final int LOAD_DIALOG = 0;
  42. private static final int POINT_DIALOG = 1;
  43. private static final int CHANGE_SERVER_DIALOG = 2;
  44. private static final int CHOOSE_SERVER_DIALOG = 3;
  45. private static final int CHECK_SERVER_DIALOG = 4;
  46. private static final int NO_DATA_DIALOG = 5;
  47. private PopulateDatabaseThread populateDatabaseThread;
  48. private LoadPointDataThread loadPointDataThread;
  49. private AuthenticateThread authenticateThread;
  50. private ProgressDialog populateDatabaseDialog;
  51. private ProgressDialog pointDialog;
  52. private ProgressDialog authenticateDialog;
  53. private final Handler timerHandler = new Handler();
  54. private GestureDetector gestureScanner;
  55. private String baseURL;
  56. private Cookie authCookie;
  57. private Cursor listCursor;
  58. private static final int SWIPE_MIN_DISTANCE = 120;
  59. private static final int SWIPE_MAX_OFF_PATH = 250;
  60. private static final int SWIPE_THRESHOLD_VELOCITY = 200;
  61. private static String selectedServer = "";
  62. private String currentCategory = null;
  63. private String buildPointDescription(final Point p, final Value v) {
  64. final StringBuilder b = new StringBuilder();
  65. if (v != null) {
  66. b.append(v.getValue());
  67. if (p.getUnit() != null) {
  68. b.append(p.getUnit());
  69. }
  70. if (v.getNote() != null) {
  71. b.append(" ").append(v.getNote());
  72. }
  73. if (v.getValue() > p.getHighAlarm() && p.isHighAlarmOn()) {
  74. b.append(" " + Const.MESSAGE_HIGH_ALERT_ON);
  75. }
  76. if (v.getValue() < p.getLowAlarm() && p.isLowAlarmOn()) {
  77. b.append(" " + Const.MESSAGE_LOW_ALERT_ON);
  78. }
  79. } else {
  80. b.append(Const.MESSAGE_NO_DATA);
  81. }
  82. return b.toString();
  83. }
  84. private void updatePointValues() {
  85. Cursor c;
  86. String cat;
  87. if (currentCategory == null) {
  88. cat = Const.CONST_HIDDEN_CATEGORY;
  89. } else {
  90. cat = currentCategory;
  91. }
  92. SQLiteDatabase db1;
  93. db1 = DatabaseHelperFactory.getInstance(StartActivity.this).getDB(true);
  94. c = db1.query(Const.ANDROID_TABLE_LEVEL_TWO_DISPLAY, new String[]{"_id", Const.ANDROID_COL_CATEGORY, Const.ANDROID_COL_DESCRIPTION, Const.ANDROID_COL_DISPLAY_TYPE, Const.ANDROID_COL_JSON}, Const.ANDROID_COL_CATEGORY + "='" + cat + "'", null, null, null, null);
  95. c.moveToFirst();
  96. while (!c.isAfterLast()) {
  97. PointName pointName = (PointName) CommonFactoryLocator.getInstance().createPointName(c.getString(c.getColumnIndex(Const.ANDROID_COL_CATEGORY)));
  98. String json = c.getString(c.getColumnIndex(Const.ANDROID_COL_JSON));
  99. Point p = GsonFactory.getInstance().fromJson(json, Point.class);
  100. Value v = OwnerAccountFactory.getInstance().getNimbitsClient(StartActivity.this, baseURL).getCurrentRecordedValue(pointName);
  101. if (v != null) {
  102. ContentValues u = new ContentValues();
  103. u.put(Const.ANDROID_COL_DESCRIPTION, buildPointDescription(p, v));
  104. if (v.getValue() > p.getHighAlarm() && p.isHighAlarmOn()) {
  105. u.put(Const.ANDROID_COL_DISPLAY_TYPE, 3);
  106. } else if (v.getValue() < p.getLowAlarm() && p.isLowAlarmOn()) {
  107. u.put(Const.ANDROID_COL_DISPLAY_TYPE, 4);
  108. } else {
  109. u.put(Const.ANDROID_COL_DISPLAY_TYPE, 2);
  110. }
  111. db1.update(Const.ANDROID_TABLE_LEVEL_TWO_DISPLAY, u, Const.ANDROID_COL_ID + "=?", new String[]{Long.toString(c.getLong(c.getColumnIndex("_id")))});
  112. db1.update(Const.ANDROID_TABLE_LEVEL_ONE_DISPLAY, u, Const.ANDROID_COL_NAME + "=?", new String[]{pointName.getValue()});
  113. }
  114. c.moveToNext();
  115. }
  116. c.close();
  117. db1.close();
  118. if (currentCategory == null) {
  119. loadView();
  120. } else {
  121. loadLevelTwoView(currentCategory);
  122. }
  123. }
  124. @Override
  125. public void onCreate(Bundle savedInstanceState) {
  126. gestureScanner = new GestureDetector(this);
  127. super.onCreate(savedInstanceState);
  128. if (DatabaseHelperFactory.getInstance(StartActivity.this).checkDatabase()) {
  129. setContentView(R.layout.catagorylayout);
  130. showDialog(CHECK_SERVER_DIALOG);
  131. }
  132. }
  133. protected Dialog onCreateDialog(final int id) {
  134. switch (id) {
  135. case LOAD_DIALOG:
  136. return dialogLoadingMain();
  137. case POINT_DIALOG:
  138. return dialogLoadingPoints();
  139. case CHANGE_SERVER_DIALOG:
  140. return dialogAddServer();
  141. case CHOOSE_SERVER_DIALOG:
  142. return dialogChooseServer();
  143. case CHECK_SERVER_DIALOG:
  144. return dialogAuthenticatedResponse();
  145. case NO_DATA_DIALOG:
  146. return dialogNoPoints();
  147. default:
  148. return null;
  149. }
  150. }
  151. private Dialog dialogNoPoints() {
  152. final Dialog dialog = new Dialog(StartActivity.this);
  153. dialog.setContentView(R.layout.welcome_layout);
  154. dialog.setTitle("Welcome To Nimbits");
  155. final TextView text1 = (TextView) dialog.findViewById(R.id.text);
  156. text1.setText("Nimbits is a free, social and open source data logging service built on cloud computing technology." +
  157. " By creating \"Data Points\" you can feed any values that change over time, such as a changing temperature or stock price, " +
  158. "into that point for storage in a global infrastructure. That point can then be visualized, charted, " +
  159. "and shared using many open source software interfaces. You can configure points by logging into the Nimbits Portal: \n www.nimbits.com.\n " +
  160. "This Android interface to Nimbits allows you to create and view points, record values, and view charts. " +
  161. "To get started, click next to create your first data point!");
  162. final Button d1 = (Button) dialog.findViewById(R.id.Button01);
  163. d1.setOnClickListener(new OnClickListener() {
  164. public void onClick(View v) {
  165. dismissDialog(NO_DATA_DIALOG);
  166. removeDialog(NO_DATA_DIALOG);
  167. createPoint();
  168. }
  169. });
  170. return dialog;
  171. }
  172. private Dialog dialogLoadingPoints() {
  173. pointDialog = new ProgressDialog(StartActivity.this);
  174. pointDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  175. pointDialog.setMessage("Loading Current Values...");
  176. loadPointDataThread = new LoadPointDataThread(pointHandler, currentCategory);
  177. loadPointDataThread.start();
  178. return pointDialog;
  179. }
  180. private Dialog dialogLoadingMain() {
  181. populateDatabaseDialog = new ProgressDialog(StartActivity.this);
  182. populateDatabaseDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  183. populateDatabaseDialog.setMessage("Loading...");
  184. populateDatabaseThread = new PopulateDatabaseThread(populateDatabaseHandler, StartActivity.this);
  185. populateDatabaseThread.start();
  186. return populateDatabaseDialog;
  187. }
  188. private Dialog dialogChooseServer() {
  189. final List<String> servers = LocalDatabaseDaoFactory.getInstance().getServers(StartActivity.this);
  190. final CharSequence[] items = servers.toArray(new CharSequence[servers.size()]);
  191. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  192. builder.setTitle("Change Nimbits Server");
  193. builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
  194. public void onClick(DialogInterface dialog, int item) {
  195. selectedServer = (String) items[item];
  196. //Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
  197. // selection = (String) items[item];
  198. }
  199. });
  200. builder.setNeutralButton("New", new DialogInterface.OnClickListener() {
  201. public void onClick(DialogInterface dialog, int which) {
  202. dismissDialog(CHOOSE_SERVER_DIALOG);
  203. removeDialog(CHOOSE_SERVER_DIALOG);
  204. showDialog(CHANGE_SERVER_DIALOG);
  205. }
  206. });
  207. builder.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
  208. public void onClick(DialogInterface dialog, int which) {
  209. if (selectedServer != null) {
  210. SQLiteDatabase db1;
  211. db1 = DatabaseHelperFactory.getInstance(StartActivity.this).getDB(true);
  212. Log.v("delete", selectedServer);
  213. db1.execSQL("delete from Servers where url='" + selectedServer + "'");
  214. db1.close();
  215. dismissDialog(CHOOSE_SERVER_DIALOG);
  216. removeDialog(CHOOSE_SERVER_DIALOG);
  217. showDialog(CHOOSE_SERVER_DIALOG);
  218. }
  219. }
  220. });
  221. builder.setPositiveButton("Switch", new DialogInterface.OnClickListener() {
  222. public void onClick(DialogInterface dialog, int which) {
  223. if (selectedServer != null) {
  224. baseURL = selectedServer;
  225. LocalDatabaseDaoFactory.getInstance().updateSetting(StartActivity.this, Const.PARAM_SERVER, baseURL);
  226. dismissDialog(CHOOSE_SERVER_DIALOG);
  227. removeDialog(CHOOSE_SERVER_DIALOG);
  228. refreshData();
  229. }
  230. }
  231. }
  232. );
  233. return builder.create();
  234. }
  235. private Dialog dialogAddServer() {
  236. final Dialog dialog1 = new Dialog(StartActivity.this);
  237. dialog1.setContentView(R.layout.text_prompt);
  238. dialog1.setTitle("Change Server");
  239. TextView text = (TextView) dialog1.findViewById(R.id.text);
  240. text.setText("You can point your android device to another Nimbits Server URL (i.e yourserver.appspot.com)");
  241. EditText urlText = (EditText) dialog1.findViewById(R.id.new_value);
  242. urlText.setText(baseURL);
  243. Button b = (Button) dialog1.findViewById(R.id.textPromptOKButton);
  244. Button d = (Button) dialog1.findViewById(R.id.textPromptDefaultButton);
  245. b.setOnClickListener(new OnClickListener() {
  246. public void onClick(View v) {
  247. EditText urlText = (EditText) dialog1.findViewById(R.id.new_value);
  248. // String authToken = OwnerAccountImpl.getToken(StartActivity.this);
  249. String u = urlText.getText().toString();
  250. LocalDatabaseDaoFactory.getInstance().addServer(StartActivity.this, u);
  251. dialog1.dismiss();
  252. removeDialog(CHANGE_SERVER_DIALOG);
  253. showDialog(CHOOSE_SERVER_DIALOG);
  254. // try {
  255. // if (Client.getN().isLoggedIn())
  256. // {
  257. // baseURL = u;
  258. //
  259. // refreshData();
  260. //
  261. // }
  262. // else
  263. // {
  264. // Toast.makeText(StartActivity.this, "Could not connect to" + u, Toast.LENGTH_LONG).show();
  265. //
  266. // }
  267. // } catch (IOException e) {
  268. // e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
  269. // }
  270. // //showDialog(CHOOSE_SERVER_DIALOG);
  271. }
  272. });
  273. d.setOnClickListener(new OnClickListener() {
  274. public void onClick(View v) {
  275. EditText urlText = (EditText) dialog1.findViewById(R.id.new_value);
  276. urlText.setText(Const.PATH_NIMBITS_PUBLIC_SERVER);
  277. }
  278. });
  279. dialog1.setOnDismissListener(new DialogInterface.OnDismissListener() {
  280. public void onDismiss(DialogInterface dialog) {
  281. }
  282. });
  283. return dialog1;
  284. }
  285. private Dialog dialogAuthenticatedResponse() {
  286. Log.v("NimbitsV", "Authenticating");
  287. baseURL = LocalDatabaseDaoFactory.getInstance().getSetting(StartActivity.this, Const.PARAM_SERVER);
  288. Log.v("NimbitsV", "Logging into " + baseURL);
  289. authenticateDialog = new ProgressDialog(StartActivity.this);
  290. authenticateDialog = ProgressDialog.show(StartActivity.this, "", "Authenticating to Nimbits Server @ " + baseURL + " using account " + OwnerAccountFactory.getInstance().getEmail(StartActivity.this) + ". Please wait...", true);
  291. authenticateThread = new AuthenticateThread(authenticateThreadHandler, StartActivity.this);
  292. authenticateThread.start();
  293. return authenticateDialog;
  294. }
  295. // Define the Handler that receives messages from the thread and update the progress
  296. private final Handler populateDatabaseHandler = new Handler() {
  297. public void handleMessage(Message msg) {
  298. final int total = msg.getData().getInt(Const.PARAM_TOTAL);
  299. final int pointCount = msg.getData().getInt(Const.PARAM_POINT_COUNT);
  300. if (populateDatabaseDialog != null) {
  301. populateDatabaseDialog.setProgress(total);
  302. Log.v("handler", "" + total);
  303. if (total >= 100) {
  304. populateDatabaseDialog.setProgress(0);
  305. dismissDialog(LOAD_DIALOG);
  306. removeDialog(LOAD_DIALOG);
  307. populateDatabaseThread.setState(PopulateDatabaseThread.STATE_DONE);
  308. populateDatabaseDialog = null;
  309. if (pointCount == 0) {
  310. showDialog(NO_DATA_DIALOG);
  311. } else {
  312. loadView();
  313. }
  314. }
  315. }
  316. }
  317. };
  318. // Define the Handler that receives messages from the thread and update the progress
  319. private final Handler authenticateThreadHandler = new Handler() {
  320. public void handleMessage(Message msg) {
  321. // int total = msg.getData().getInt("total");
  322. final boolean isLoggedIn = msg.getData().getBoolean(Const.PARAM_IS_LOGGED_IN);
  323. Log.v("NimbitsV", "is logged in " + isLoggedIn);
  324. if (authenticateDialog != null) {
  325. dismissDialog(CHECK_SERVER_DIALOG);
  326. removeDialog(CHECK_SERVER_DIALOG);
  327. authenticateThread.setState(AuthenticateThread.STATE_DONE);
  328. authenticateDialog = null;
  329. if (isLoggedIn) {
  330. boolean reload = false;
  331. final Bundle b = getIntent().getExtras();
  332. String category = null;
  333. if (b != null) {
  334. reload = b.getBoolean(Const.PARAM_RELOAD);
  335. category = b.getString(Const.ANDROID_COL_CATEGORY);
  336. }
  337. if (!reload) {
  338. if (category != null) {
  339. currentCategory = category;
  340. showDialog(POINT_DIALOG);
  341. } else {
  342. loadView();
  343. }
  344. } else {
  345. showDialog(LOAD_DIALOG);
  346. }
  347. } else {
  348. Toast.makeText(StartActivity.this, "Nimbits uses google accounts to authenticate. Please add a google.com (gmail.com) account to this device.", Toast.LENGTH_LONG).show();
  349. }
  350. }
  351. }
  352. };
  353. private final Handler pointHandler = new Handler() {
  354. public void handleMessage(Message msg) {
  355. int total = msg.getData().getInt(Const.PARAM_TOTAL);
  356. if (pointDialog != null) {
  357. pointDialog.setProgress(total);
  358. if (total >= 100) {
  359. pointDialog.setProgress(0);
  360. dismissDialog(POINT_DIALOG);
  361. removeDialog(POINT_DIALOG);
  362. loadPointDataThread.setState(LoadPointDataThread.STATE_DONE);
  363. pointDialog = null;
  364. loadLevelTwoView(currentCategory);
  365. }
  366. }
  367. }
  368. };
  369. void loadView() {
  370. currentCategory = null;
  371. if (listCursor != null) {
  372. listCursor.close();
  373. }
  374. ListAdapter adapter = LocalDatabaseDaoFactory.getInstance().mainListCursor(StartActivity.this);
  375. setContentView(R.layout.catagorylayout);
  376. setListAdapter(adapter);
  377. }
  378. private void loadLevelTwoView(final String category) {
  379. this.setTitle(category);
  380. currentCategory = category;
  381. if (listCursor != null) {
  382. listCursor.close();
  383. }
  384. SQLiteDatabase db = DatabaseHelperFactory.getInstance(StartActivity.this).getDB(false);
  385. listCursor = db.query(Const.ANDROID_TABLE_LEVEL_TWO_DISPLAY, new String[]{
  386. Const.ANDROID_COL_ID,
  387. Const.ANDROID_COL_CATEGORY,
  388. Const.ANDROID_COL_DESCRIPTION,
  389. Const.ANDROID_COL_DISPLAY_TYPE,
  390. Const.ANDROID_COL_NAME
  391. },
  392. Const.ANDROID_COL_CATEGORY + "='" + category + "'", null, null, null, Const.ANDROID_COL_DISPLAY_TYPE);
  393. ListAdapter adapter = new ImageCursorAdapter(
  394. this, // Context.
  395. R.layout.main_list, // Specify the row template to use (here, two columns bound to the two retrieved cursor
  396. listCursor, // Pass in the cursor to bind to.
  397. new String[]{Const.ANDROID_COL_NAME, Const.ANDROID_COL_DESCRIPTION}, // Array of cursor columns to bind to.
  398. new int[]{R.id.text1, R.id.text2}); // Parallel array of which template objects to bind to those columns.
  399. // Bind to our new adapter.
  400. setListAdapter(adapter);
  401. }
  402. private void viewMap() {
  403. if (this.currentCategory == null) {
  404. Toast.makeText(StartActivity.this, "Please select a category to or point to view on the map", Toast.LENGTH_LONG).show();
  405. } else {
  406. //SQLiteDatabase db1 = getDB(false);
  407. Cursor c;
  408. SQLiteDatabase db1;
  409. db1 = DatabaseHelperFactory.getInstance(StartActivity.this).getDB(false);
  410. c = db1.query(Const.ANDROID_TABLE_LEVEL_ONE_DISPLAY, new String[]{Const.ANDROID_COL_ID, Const.ANDROID_COL_JSON}, Const.ANDROID_COL_NAME + "='" + currentCategory + "'", null, null, null, null);
  411. c.moveToFirst();
  412. String json = c.getString(c.getColumnIndex(Const.ANDROID_COL_JSON));
  413. c.close();
  414. Bundle b = new Bundle();
  415. Intent intent = new Intent();
  416. b.putString(Const.PARAM_TYPE, Const.ANDROID_COL_CATEGORY);
  417. b.putString(Const.PARAM_CATEGORY, currentCategory);
  418. b.putString(Const.PARAM_JSON, json);
  419. b.putString(Const.PARAM_BASE_URL, baseURL);
  420. intent.putExtras(b);
  421. intent.setClass(StartActivity.this, MapViewActivity.class);
  422. startActivity(intent);
  423. c.close();
  424. db1.close();
  425. finish();
  426. }
  427. }
  428. private void viewChart() {
  429. String cat;
  430. Log.v("action", "view chart");
  431. Log.v("chart", currentCategory);
  432. if (this.currentCategory == null) {
  433. cat = Const.CONST_HIDDEN_CATEGORY;
  434. //Toast.makeText(StartActivity.this,"Please select a catagory to or point to view a chart", Toast.LENGTH_LONG).show();
  435. } else {
  436. cat = currentCategory;
  437. }
  438. Log.v("chart", cat);
  439. //SQLiteDatabase db1 = getDB(false);
  440. Cursor c;
  441. SQLiteDatabase db1;
  442. db1 = DatabaseHelperFactory.getInstance(StartActivity.this).getDB(false);
  443. c = db1.query(Const.ANDROID_TABLE_LEVEL_ONE_DISPLAY, new String[]{Const.ANDROID_COL_ID, Const.ANDROID_COL_JSON}, Const.ANDROID_COL_NAME + "='" + cat + "'", null, null, null, null);
  444. c.moveToFirst();
  445. String json = c.getString(c.getColumnIndex(Const.ANDROID_COL_JSON));
  446. Log.v("chart", json);
  447. c.close();
  448. db1.close();
  449. Bundle b = new Bundle();
  450. Intent intent = new Intent();
  451. b.putString(Const.PARAM_TYPE, Const.PARAM_CATEGORY);
  452. b.putString(Const.PARAM_CATEGORY, cat);
  453. b.putString(Const.PARAM_JSON, json);
  454. b.putString(Const.PARAM_BASE_URL, baseURL);
  455. intent.putExtras(b);
  456. intent.setClass(StartActivity.this, ChartActivity.class);
  457. startActivity(intent);
  458. finish();
  459. }
  460. @Override
  461. public void finish() {
  462. super.finish();
  463. if (timerHandler != null) {
  464. timerHandler.removeCallbacks(mUpdateTimerTask);
  465. }
  466. }
  467. private void createCategory() {
  468. //setContentView(0);
  469. try {
  470. CustomDialog myDialog = new CustomDialog(this, "New Category Name:",
  471. new OnNewCategoryListener());
  472. myDialog.show();
  473. // al.add(myDialog.getEntry());
  474. } catch (Exception e) {
  475. Log.e("Create category", e.getMessage());
  476. }
  477. //dialog.show();
  478. }
  479. private void createPoint() {
  480. try {
  481. CustomDialog myDialog = new CustomDialog(this, "New Point Name:",
  482. new OnCreatePointListener());
  483. myDialog.show();
  484. } catch (Exception e) {
  485. Log.e(Const.TEXT_NEW_CATEGORY, e.getMessage());
  486. }
  487. }
  488. private void refreshData() {
  489. LocalDatabaseDaoFactory.getInstance().deleteAll(StartActivity.this);
  490. showDialog(LOAD_DIALOG);
  491. }
  492. private void changeServer() {
  493. showDialog(CHOOSE_SERVER_DIALOG);
  494. }
  495. //Event Overrides
  496. @Override
  497. public boolean onOptionsItemSelected(MenuItem item) {
  498. switch (item.getItemId()) {
  499. case R.id.New_Point_Catagory:
  500. createCategory();
  501. return true;
  502. case R.id.New_Data_Point:
  503. createPoint();
  504. return true;
  505. case R.id.main_menu:
  506. loadView();
  507. return true;
  508. case R.id.refresh:
  509. refreshData();
  510. return true;
  511. case R.id.view_map:
  512. viewMap();
  513. return true;
  514. case R.id.view_chart:
  515. viewChart();
  516. return true;
  517. case R.id.exit:
  518. this.finish();
  519. return true;
  520. case R.id.Servers:
  521. changeServer();
  522. return true;
  523. default:
  524. return super.onOptionsItemSelected(item);
  525. }
  526. }
  527. @Override
  528. public boolean onCreateOptionsMenu(Menu menu) {
  529. MenuInflater inflater = getMenuInflater();
  530. inflater.inflate(R.menu.mainmenu, menu);
  531. return true;
  532. }
  533. @Override
  534. protected void onListItemClick(final ListView l, final View v, final int position, final long id) {
  535. super.onListItemClick(l, v, position, id);
  536. // Context context = getApplicationContext();
  537. final ImageView icon = (ImageView) v.findViewById(R.id.icon1);
  538. final TextView d = (TextView) v.findViewById(R.id.text1);
  539. if (listCursor != null) {
  540. listCursor.close();
  541. }
  542. if (icon.getTag().toString().equals(Const.PARAM_POINT)) {
  543. final String json = LocalDatabaseDaoFactory.getInstance().getSelectedChildTableJsonByName(StartActivity.this, (String) d.getText());
  544. final Bundle b = new Bundle();
  545. final Intent intent = new Intent();
  546. b.putString(Const.PARAM_CATEGORY, this.currentCategory);
  547. b.putString(Const.PARAM_POINT, (String) d.getText());
  548. b.putString(Const.PARAM_JSON, json);
  549. b.putString(Const.PARAM_BASE_URL, baseURL);
  550. intent.putExtras(b);
  551. intent.setClass(StartActivity.this, PointActivity.class);
  552. finish();
  553. startActivity(intent);
  554. } else if (icon.getTag().toString().equals(Const.PARAM_DIAGRAM)) {
  555. final String json = LocalDatabaseDaoFactory.getInstance().getSelectedChildTableJsonByName(StartActivity.this, (String) d.getText());
  556. final Bundle b = new Bundle();
  557. final Intent intent = new Intent();
  558. // final String jsonCookie = GsonFactory.getInstance().toJson(authCookie);
  559. b.putString(Const.PARAM_CATEGORY, this.currentCategory);
  560. b.putString(Const.PARAM_DIAGRAM, (String) d.getText());
  561. b.putString(Const.PARAM_JSON, json);
  562. b.putString(Const.PARAM_BASE_URL, baseURL);
  563. b.putString(Const.PARAM_COOKIE, authCookie.getName() + "=" + authCookie.getValue() + "; domain=" + authCookie.getDomain());
  564. intent.putExtras(b);
  565. intent.setClass(StartActivity.this, DiagramActivity.class);
  566. finish();
  567. startActivity(intent);
  568. } else if (icon.getTag().toString().equals(Const.PARAM_CATEGORY)) {
  569. currentCategory = (String) d.getText();
  570. showDialog(POINT_DIALOG);
  571. }
  572. }
  573. @Override
  574. public boolean onTouchEvent(MotionEvent event) {
  575. return gestureScanner.onTouchEvent(event);
  576. }
  577. @Override
  578. public boolean onDown(MotionEvent e) {
  579. return false;
  580. }
  581. @Override
  582. public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
  583. Log.v("action", "fling");
  584. try {
  585. if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
  586. return false;
  587. // right to left swipe
  588. if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
  589. Log.v("action", "right");
  590. viewChart();
  591. } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
  592. Log.v("action", "left");
  593. if (currentCategory != null) {
  594. currentCategory = null;
  595. loadView();
  596. }
  597. }
  598. } catch (Exception e) {
  599. // nothing
  600. }
  601. return false;
  602. }
  603. @Override
  604. public void onLongPress(MotionEvent e) {
  605. }
  606. @Override
  607. public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
  608. return false;
  609. }
  610. @Override
  611. public void onShowPress(MotionEvent e) {
  612. }
  613. @Override
  614. public boolean onSingleTapUp(MotionEvent e) {
  615. return false;
  616. }
  617. private class PopulateDatabaseThread extends Thread {
  618. final Handler mHandler;
  619. final static int STATE_DONE = 0;
  620. final static int STATE_RUNNING = 1;
  621. @SuppressWarnings("unused")
  622. int mState;
  623. @SuppressWarnings("unused")
  624. int total;
  625. final Context context;
  626. PopulateDatabaseThread(Handler h, Context c) {
  627. mHandler = h;
  628. context = c;
  629. }
  630. private void update(int c, boolean loggedIn, int count) {
  631. Message msg = mHandler.obtainMessage();
  632. Bundle b = new Bundle();
  633. b.putInt(Const.PARAM_TOTAL, c);
  634. b.putInt(Const.PARAM_POINT_COUNT, count);
  635. b.putBoolean(Const.PARAM_LOGGED_IN, loggedIn);
  636. msg.setData(b);
  637. mHandler.sendMessage(msg);
  638. }
  639. public void run() {
  640. mState = STATE_RUNNING;
  641. total = 0;
  642. boolean loggedIn;
  643. update(7, false, 0);
  644. loggedIn = true;
  645. update(10, loggedIn, 0);
  646. update(20, loggedIn, 0);
  647. int pointCount = 0;
  648. int diagramCount = 0;
  649. if (DatabaseHelperFactory.getInstance(StartActivity.this).isDatabaseEmpty()) {
  650. pointCount = populateEmptyDatabase(loggedIn, pointCount, diagramCount);
  651. } else {
  652. pointCount++;
  653. diagramCount++;
  654. }
  655. //db1.close();
  656. total = 100;
  657. update(100, loggedIn, pointCount);
  658. mState = STATE_DONE;
  659. }
  660. private int populateEmptyDatabase(boolean loggedIn, int totalPointCount, int totalDiagramCount) {
  661. final List<Category> categories = OwnerAccountFactory.getInstance().getNimbitsClient(context, baseURL).getCategories(true, true);
  662. update(25, loggedIn, totalPointCount);
  663. Log.v(Const.N, "Populating empty db from: " + baseURL);
  664. int i = 30;
  665. if (categories != null) {
  666. update(i, loggedIn, totalPointCount);
  667. for (Category category : categories) {
  668. update(i++, loggedIn, totalPointCount);
  669. ContentValues mainTableValues = new ContentValues();
  670. mainTableValues.put(Const.ANDROID_COL_NAME, category.getName().getValue());
  671. mainTableValues.put(Const.ANDROID_COL_DISPLAY_TYPE, DisplayType.Category.getCode());
  672. mainTableValues.put(Const.ANDROID_COL_JSON, category.getJsonPointCollection());
  673. for (final Point p : category.getPoints()) {
  674. totalPointCount++;
  675. addPointToChildrenTable(category, p);
  676. }
  677. for (final Diagram d : category.getDiagrams()) {
  678. totalDiagramCount++;
  679. addDiagramToChildrenTable(category, d);
  680. }
  681. mainTableValues.put(Const.ANDROID_COL_DESCRIPTION, category.getPoints().size() + " points " +
  682. category.getDiagrams().size() + " diagrams");
  683. LocalDatabaseDaoFactory.getInstance().insertMain(StartActivity.this, mainTableValues);
  684. if (category.getName() != null && category.getName().getValue().equals(Const.CONST_HIDDEN_CATEGORY)) {
  685. for (Point p : category.getPoints()) {
  686. totalPointCount++;
  687. addTopLevelPointToDatabase(p);
  688. }
  689. for (Diagram d : category.getDiagrams()) {
  690. totalDiagramCount++;
  691. addTopLevelDiagramToDatabase(d);
  692. }
  693. }
  694. }
  695. }
  696. return totalPointCount;
  697. }
  698. private void addTopLevelPointToDatabase(final Point p) {
  699. final ContentValues pointTableValues = new ContentValues();
  700. final ContentValues mainTableValues = new ContentValues();
  701. final Value v = OwnerAccountFactory.getInstance().getNimbitsClient(StartActivity.this, baseURL).getCurrentRecordedValue(p.getName());
  702. mainTableValues.put(Const.ANDROID_COL_NAME, p.getName().getValue());
  703. int displayType;
  704. if (v != null) {
  705. if (v.getValue() > p.getHighAlarm() && p.isHighAlarmOn()) {
  706. displayType = DisplayType.HighAlarm.getCode();
  707. } else if (v.getValue() < p.getLowAlarm() && p.isLowAlarmOn()) {
  708. displayType = DisplayType.LowAlarm.getCode();
  709. } else {
  710. displayType = DisplayType.Point.getCode();
  711. }
  712. } else {
  713. displayType = DisplayType.Point.getCode();
  714. }
  715. mainTableValues.put(Const.ANDROID_COL_DISPLAY_TYPE, displayType);
  716. mainTableValues.put(Const.ANDROID_COL_DESCRIPTION, buildPointDescription(p, v));
  717. LocalDatabaseDaoFactory.getInstance().insertMain(StartActivity.this, mainTableValues);
  718. pointTableValues.put(Const.ANDROID_COL_CATEGORY, p.getName().getValue());
  719. pointTableValues.put(Const.ANDROID_COL_DESCRIPTION, p.getDescription());
  720. pointTableValues.put(Const.ANDROID_COL_DISPLAY_TYPE, displayType);
  721. pointTableValues.put(Const.ANDROID_COL_JSON, GsonFactory.getInstance().toJson(p));
  722. LocalDatabaseDaoFactory.getInstance().insertPoints(StartActivity.this, pointTableValues);
  723. }
  724. private void addTopLevelDiagramToDatabase(final Diagram diagram) {
  725. final ContentValues pointTableValues = new ContentValues();
  726. final ContentValues mainTableValues = new ContentValues();
  727. mainTableValues.put(Const.ANDROID_COL_NAME, diagram.getName().getValue());
  728. mainTableValues.put(Const.ANDROID_COL_DISPLAY_TYPE, DisplayType.Diagram.getCode());
  729. mainTableValues.put(Const.ANDROID_COL_DESCRIPTION, "");//TODO diagram description
  730. LocalDatabaseDaoFactory.getInstance().insertMain(StartActivity.this, mainTableValues);
  731. pointTableValues.put(Const.ANDROID_COL_CATEGORY, diagram.getName().getValue());
  732. pointTableValues.put(Const.ANDROID_COL_DESCRIPTION, "");//TODO
  733. pointTableValues.put(Const.ANDROID_COL_DISPLAY_TYPE, DisplayType.Diagram.getCode());
  734. pointTableValues.put(Const.ANDROID_COL_JSON, GsonFactory.getInstance().toJson(diagram));
  735. LocalDatabaseDaoFactory.getInstance().insertPoints(StartActivity.this, pointTableValues);
  736. }
  737. private void addPointToChildrenTable(final Category category, final Point p) {
  738. final ContentValues tableValues = new ContentValues();
  739. tableValues.put(Const.ANDROID_COL_CATEGORY, category.getName().getValue());
  740. tableValues.put(Const.ANDROID_COL_NAME, p.getName().getValue());
  741. tableValues.put(Const.ANDROID_COL_DESCRIPTION, "");
  742. tableValues.put(Const.ANDROID_COL_DISPLAY_TYPE, DisplayType.Point.getCode());
  743. tableValues.put(Const.ANDROID_COL_JSON, GsonFactory.getInstance().toJson(p));
  744. LocalDatabaseDaoFactory.getInstance().insertPoints(StartActivity.this, tableValues);
  745. }
  746. private void addDiagramToChildrenTable(final Category category, final Diagram d) {
  747. final ContentValues tableValues = new ContentValues();
  748. tableValues.put(Const.ANDROID_COL_CATEGORY, category.getName().getValue());
  749. tableValues.put(Const.ANDROID_COL_NAME, d.getName().getValue());
  750. tableValues.put(Const.ANDROID_COL_DESCRIPTION, "");
  751. tableValues.put(Const.ANDROID_COL_DISPLAY_TYPE, DisplayType.Diagram.getCode());
  752. tableValues.put(Const.ANDROID_COL_JSON, GsonFactory.getInstance().toJson(d));
  753. LocalDatabaseDaoFactory.getInstance().insertPoints(StartActivity.this, tableValues);
  754. }
  755. /* sets the current state for the thread,
  756. * used to stop the thread */
  757. public void setState(int state) {
  758. mState = state;
  759. }
  760. }
  761. private class LoadPointDataThread extends Thread {
  762. final Handler mHandler;
  763. final static int STATE_DONE = 0;
  764. final static int STATE_RUNNING = 1;
  765. @SuppressWarnings("unused")
  766. int mState;
  767. @SuppressWarnings("unused")
  768. int total;
  769. final String selectedCategory;
  770. LoadPointDataThread(final Handler h, final String categoryName) {
  771. selectedCategory = categoryName;
  772. mHandler = h;
  773. }
  774. /* sets the current state for the thread,
  775. * used to stop the thread */
  776. public void setState(int state) {
  777. mState = state;
  778. }
  779. private void update(int c) {
  780. Message msg = mHandler.obtainMessage();
  781. Bundle b = new Bundle();
  782. b.putInt(Const.PARAM_TOTAL, c);
  783. msg.setData(b);
  784. mHandler.sendMessage(msg);
  785. }
  786. public void run() {
  787. mState = STATE_RUNNING;
  788. Value v;
  789. PointName pointName;
  790. String json;
  791. //SQLiteDatabase db1 = getDB(true);
  792. final SQLiteDatabase db = DatabaseHelperFactory.getInstance(StartActivity.this).getDB(true);
  793. final Cursor c = db.query(Const.ANDROID_TABLE_LEVEL_TWO_DISPLAY, new String[]{
  794. Const.ANDROID_COL_ID,
  795. Const.ANDROID_COL_NAME,
  796. Const.ANDROID_COL_DESCRIPTION,
  797. Const.ANDROID_COL_DISPLAY_TYPE,
  798. Const.ANDROID_COL_JSON},
  799. Const.ANDROID_COL_CATEGORY + "='" + selectedCategory + "'",
  800. null, null, null,
  801. Const.ANDROID_COL_DISPLAY_TYPE);
  802. int count = c.getCount();
  803. update(0);
  804. if (count > 0) {
  805. int d = 100 / count;
  806. int progress = 0;
  807. //update(count);
  808. c.moveToFirst();
  809. while (!c.isAfterLast()) {
  810. pointName = (PointName) CommonFactoryLocator.getInstance().createPointName(c.getString(c.getColumnIndex(Const.ANDROID_COL_NAME)));
  811. json = c.getString(c.getColumnIndex(Const.ANDROID_COL_JSON));
  812. Point p = GsonFactory.getInstance().fromJson(json, PointModel.class);
  813. v = OwnerAccountFactory.getInstance().getNimbitsClient(StartActivity.this, baseURL).getCurrentRecordedValue(pointName);
  814. ContentValues u = new ContentValues();
  815. if (v != null) {
  816. u.put(Const.ANDROID_COL_DESCRIPTION, buildPointDescription(p, v));
  817. if (v.getValue() > p.getHighAlarm() && p.isHighAlarmOn()) {
  818. u.put(Const.ANDROID_COL_DISPLAY_TYPE, 3);
  819. } else if (v.getValue() < p.getLowAlarm() && p.isLowAlarmOn()) {
  820. u.put(Const.ANDROID_COL_DISPLAY_TYPE, 4);
  821. } else {
  822. u.put(Const.ANDROID_COL_DISPLAY_TYPE, 2);
  823. }
  824. } else {
  825. u.put(Const.ANDROID_COL_DESCRIPTION, Const.MESSAGE_NO_DATA);
  826. }
  827. // DatabaseHelperFactory.getInstance(StartActivity.this).updatePointName(u, pointName);
  828. LocalDatabaseDaoFactory.getInstance().updatePointValuesByName(StartActivity.this, u, pointName);
  829. progress += d;
  830. update(progress);
  831. c.moveToNext();
  832. }
  833. c.close();
  834. db.close();
  835. update(100);
  836. } else {
  837. update(100);
  838. }
  839. update(100);
  840. }
  841. }
  842. private class AuthenticateThread extends Thread {
  843. final Handler m;
  844. final static int STATE_DONE = 0;
  845. int mState;
  846. final Context currentContext;
  847. AuthenticateThread(Handler h, Context c) {
  848. m = h;
  849. currentContext = c;
  850. }
  851. /* sets the current state for the thread,
  852. * used to stop the thread */
  853. public void setState(int state) {
  854. mState = state;
  855. }
  856. private void update(boolean isLoggedIn) {
  857. Message msg = m.obtainMessage();
  858. Bundle b = new Bundle();
  859. b.putBoolean(Const.PARAM_IS_LOGGED_IN, isLoggedIn);
  860. msg.setData(b);
  861. m.sendMessage(msg);
  862. }
  863. public void run() {
  864. try {
  865. baseURL = LocalDatabaseDaoFactory.getInstance().getSetting(StartActivity.this, Const.PARAM_SERVER);
  866. // String authToken = OwnerAccountImpl.getToken(currentContext);
  867. //googleAuth.connectClean(baseURL,authToken);
  868. boolean isLoggedIn = OwnerAccountFactory.getInstance().getNimbitsClient(StartActivity.this, baseURL).isLoggedIn();
  869. authCookie = OwnerAccountFactory.getInstance().getNimbitsClient(StartActivity.this, baseURL).getAuthCookie();
  870. update(isLoggedIn);
  871. } catch (Exception e) {
  872. Log.e(Const.N, e.getMessage());
  873. update(false);
  874. }
  875. }
  876. }
  877. private final Runnable mUpdateTimerTask = new Runnable() {
  878. public void run() {
  879. Log.v("category timer", "tick");
  880. // updatePointValues();
  881. // if (mHandler != null)
  882. // {
  883. // mHandler.removeCallbacks(mUpdateTimerTask);
  884. // mHandler.postDelayed(mUpdateTimerTask, refreshRate);
  885. // }
  886. }
  887. };
  888. @Override
  889. public boolean onKeyDown(int keyCode, KeyEvent event) {
  890. if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
  891. if (currentCategory != null) {
  892. currentCategory = null;
  893. loadView();
  894. return true;
  895. }
  896. }
  897. return super.onKeyDown(keyCode, event);
  898. }
  899. private class OnNewCategoryListener implements CustomDialog.ReadyListener {
  900. public void ready(String categoryNameResponse) throws UnsupportedEncodingException {
  901. if (categoryNameResponse != null && categoryNameResponse.trim().length() > 0) {
  902. CategoryName categoryName = CommonFactoryLocator.getInstance().createCategoryName(categoryNameResponse);
  903. OwnerAccountFactory.getInstance().getNimbitsClient(StartActivity.this, baseURL).addCategory(categoryName);
  904. ContentValues values = new ContentValues();
  905. values.put(Const.ANDROID_COL_CATEGORY, categoryName.getValue());
  906. values.put(Const.ANDROID_COL_DISPLAY_TYPE, 1);
  907. values.put(Const.ANDROID_COL_DESCRIPTION, 0 + " points");
  908. LocalDatabaseDaoFactory.getInstance().insertMain(StartActivity.this, values);
  909. //db1.insert(DatabaseHelperImpl.ANDROID_TABLE_LEVEL_ONE_DISPLAY, null,values);
  910. //db1.close();
  911. Toast.makeText(StartActivity.this, "Added Category " + categoryName + ". Click on the category to add Data Points to it", Toast.LENGTH_LONG).show();
  912. loadView();
  913. }
  914. }
  915. }
  916. private class OnCreatePointListener implements CustomDialog.ReadyListener {
  917. public void ready(String pointNameText) {
  918. //SQLiteDatabase db1 = getDB(true);
  919. if (!pointNameText.trim().equals("")) {
  920. PointName pointName = CommonFactoryLocator.getInstance().createPointName(pointNameText);
  921. CategoryName categoryName = CommonFactoryLocator.getInstance().createCategoryName(currentCategory);
  922. Point point = OwnerAccountFactory.getInstance().getNimbitsClient(StartActivity.this, baseURL).addPoint(categoryName, pointName);
  923. ContentValues pValues = new ContentValues();
  924. ContentValues cValues = new ContentValues();
  925. if (currentCategory != null) {
  926. pValues.put(Const.ANDROID_COL_CATEGORY, currentCategory);
  927. } else {
  928. pValues.put(Const.ANDROID_COL_CATEGORY, Const.CONST_HIDDEN_CATEGORY);
  929. cValues.put(Const.ANDROID_COL_CATEGORY, pointName.getValue());
  930. cValues.put(Const.ANDROID_COL_DISPLAY_TYPE, 2);
  931. cValues.put(Const.ANDROID_COL_DESCRIPTION, "");
  932. LocalDatabaseDaoFactory.getInstance().insertMain(StartActivity.this, cValues);
  933. }
  934. pValues.put(Const.ANDROID_COL_CATEGORY, pointName.getValue());
  935. pValues.put(Const.ANDROID_COL_DESCRIPTION, "");
  936. pValues.put(Const.ANDROID_COL_DISPLAY_TYPE, 2);
  937. pValues.put(Const.ANDROID_COL_JSON, GsonFactory.getInstance().toJson(point));
  938. LocalDatabaseDaoFactory.getInstance().insertPoints(StartActivity.this, pValues);
  939. //db1.close();
  940. if (currentCategory != null) {
  941. loadLevelTwoView(currentCategory);
  942. } else {
  943. loadView();
  944. }
  945. Toast.makeText(StartActivity.this, "Added Point " + pointName.getValue() + ". Go to " + baseURL + " to configure advanced properties", Toast.LENGTH_LONG).show();
  946. }
  947. }
  948. }
  949. }