二维码-去掉原始的HistoryManager也就是历史记录
来源:互联网 发布:简单的数据库设计软件 编辑:程序博客网 时间:2024/06/05 05:56
说明
二维码官方给的代码,是一个历史扫描记录的功能. 虽然说这个功能很简单,但是毕竟是官方的例子, 所以, 就通过去掉这个功能,来学习一下是怎么实现的.
界面部分-HistoryActivity
也就是一个ListActivity, 然后设置些数据. 然后通过Settings中一些功能的实现.
最重要的操作部分-HistoryManager
印象很深的一部分:
1. Result封装要来的结果.
2. Histroy封装要显示的数据.
3. 全程对sqlite数据库的封装.
代码部分
HistoryActivity.java
/* * Copyright 2012 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package com.google.zxing.client.android.history;import android.app.Activity;import android.app.AlertDialog;import android.app.ListActivity;import android.content.ActivityNotFoundException;import android.content.DialogInterface;import android.content.Intent;import android.net.Uri;import android.os.Bundle;import android.os.Parcelable;import android.util.Log;import android.view.ContextMenu;import android.view.Menu;import android.view.MenuInflater;import android.view.MenuItem;import android.view.View;import android.widget.AdapterView;import android.widget.ArrayAdapter;import android.widget.ListView;import com.google.zxing.client.android.CaptureActivity;import com.google.zxing.client.android.Intents;import com.sainthigh.qrscandemo.R;/** * The activity for interacting with the scan history. */public final class HistoryActivity extends ListActivity { private static final String TAG = HistoryActivity.class.getSimpleName(); private HistoryManager historyManager; private ArrayAdapter<HistoryItem> adapter; private CharSequence originalTitle; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); this.historyManager = new HistoryManager(this); adapter = new HistoryItemAdapter(this); setListAdapter(adapter); View listview = getListView(); registerForContextMenu(listview); originalTitle = getTitle(); } @Override protected void onResume() { super.onResume(); reloadHistoryItems(); } private void reloadHistoryItems() { Iterable<HistoryItem> items = historyManager.buildHistoryItems(); adapter.clear(); for (HistoryItem item : items) { adapter.add(item); } setTitle(originalTitle + " (" + adapter.getCount() + ')'); if (adapter.isEmpty()) { adapter.add(new HistoryItem(null, null, null)); } } @Override protected void onListItemClick(ListView l, View v, int position, long id) { if (adapter.getItem(position).getResult() != null) { Intent intent = new Intent(this, CaptureActivity.class); intent.putExtra(Intents.History.ITEM_NUMBER, position); setResult(Activity.RESULT_OK, intent); finish(); } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { int position = ((AdapterView.AdapterContextMenuInfo) menuInfo).position; if (position >= adapter.getCount() || adapter.getItem(position).getResult() != null) { menu.add(Menu.NONE, position, position, R.string.history_clear_one_history_text); } // else it's just that dummy "Empty" message } @Override public boolean onContextItemSelected(MenuItem item) { int position = item.getItemId(); historyManager.deleteHistoryItem(position); reloadHistoryItems(); return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { if (historyManager.hasHistoryItems()) { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.history, menu); } return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_history_send: CharSequence history = historyManager.buildHistory(); Parcelable historyFile = HistoryManager.saveHistory(history.toString()); if (historyFile == null) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.msg_unmount_usb); builder.setPositiveButton(R.string.button_ok, null); builder.show(); } else { Intent intent = new Intent(Intent.ACTION_SEND, Uri.parse("mailto:")); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); String subject = getResources().getString(R.string.history_email_title); intent.putExtra(Intent.EXTRA_SUBJECT, subject); intent.putExtra(Intent.EXTRA_TEXT, subject); intent.putExtra(Intent.EXTRA_STREAM, historyFile); intent.setType("text/csv"); try { startActivity(intent); } catch (ActivityNotFoundException anfe) { Log.w(TAG, anfe.toString()); } } break; case R.id.menu_history_clear_text: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.msg_sure); builder.setCancelable(true); builder.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i2) { historyManager.clearHistory(); dialog.dismiss(); finish(); } }); builder.setNegativeButton(R.string.button_cancel, null); builder.show(); break; default: return super.onOptionsItemSelected(item); } return true; }}
HistoryManager.java
/* * Copyright (C) 2009 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package com.google.zxing.client.android.history;import android.database.sqlite.SQLiteException;import com.google.zxing.BarcodeFormat;import com.google.zxing.Result;import com.google.zxing.client.android.Intents;import com.google.zxing.client.android.PreferencesActivity;import com.google.zxing.client.android.result.ResultHandler;import android.app.Activity;import android.content.ContentValues;import android.content.SharedPreferences;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;import android.net.Uri;import android.os.Environment;import android.preference.PreferenceManager;import android.util.Log;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStreamWriter;import java.nio.charset.Charset;import java.text.DateFormat;import java.util.ArrayList;import java.util.Date;import java.util.List;/** * <p>Manages functionality related to scan history.</p> * * @author Sean Owen */public final class HistoryManager { private static final String TAG = HistoryManager.class.getSimpleName(); private static final int MAX_ITEMS = 2000; private static final String[] COLUMNS = { DBHelper.TEXT_COL, DBHelper.DISPLAY_COL, DBHelper.FORMAT_COL, DBHelper.TIMESTAMP_COL, DBHelper.DETAILS_COL, }; private static final String[] COUNT_COLUMN = { "COUNT(1)" }; private static final String[] ID_COL_PROJECTION = { DBHelper.ID_COL }; private static final String[] ID_DETAIL_COL_PROJECTION = { DBHelper.ID_COL, DBHelper.DETAILS_COL }; private final Activity activity; private final boolean enableHistory; public HistoryManager(Activity activity) { this.activity = activity; SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity); enableHistory = prefs.getBoolean(PreferencesActivity.KEY_ENABLE_HISTORY, true); } public boolean hasHistoryItems() { SQLiteOpenHelper helper = new DBHelper(activity); SQLiteDatabase db = null; Cursor cursor = null; try { db = helper.getReadableDatabase(); cursor = db.query(DBHelper.TABLE_NAME, COUNT_COLUMN, null, null, null, null, null); cursor.moveToFirst(); return cursor.getInt(0) > 0; } finally { close(cursor, db); } } public List<HistoryItem> buildHistoryItems() { SQLiteOpenHelper helper = new DBHelper(activity); List<HistoryItem> items = new ArrayList<>(); SQLiteDatabase db = null; Cursor cursor = null; try { db = helper.getReadableDatabase(); cursor = db.query(DBHelper.TABLE_NAME, COLUMNS, null, null, null, null, DBHelper.TIMESTAMP_COL + " DESC"); while (cursor.moveToNext()) { String text = cursor.getString(0); String display = cursor.getString(1); String format = cursor.getString(2); long timestamp = cursor.getLong(3); String details = cursor.getString(4); Result result = new Result(text, null, null, BarcodeFormat.valueOf(format), timestamp); items.add(new HistoryItem(result, display, details)); } } finally { close(cursor, db); } return items; } public HistoryItem buildHistoryItem(int number) { SQLiteOpenHelper helper = new DBHelper(activity); SQLiteDatabase db = null; Cursor cursor = null; try { db = helper.getReadableDatabase(); cursor = db.query(DBHelper.TABLE_NAME, COLUMNS, null, null, null, null, DBHelper.TIMESTAMP_COL + " DESC"); cursor.move(number + 1); String text = cursor.getString(0); String display = cursor.getString(1); String format = cursor.getString(2); long timestamp = cursor.getLong(3); String details = cursor.getString(4); Result result = new Result(text, null, null, BarcodeFormat.valueOf(format), timestamp); return new HistoryItem(result, display, details); } finally { close(cursor, db); } } public void deleteHistoryItem(int number) { SQLiteOpenHelper helper = new DBHelper(activity); SQLiteDatabase db = null; Cursor cursor = null; try { db = helper.getWritableDatabase(); cursor = db.query(DBHelper.TABLE_NAME, ID_COL_PROJECTION, null, null, null, null, DBHelper.TIMESTAMP_COL + " DESC"); cursor.move(number + 1); db.delete(DBHelper.TABLE_NAME, DBHelper.ID_COL + '=' + cursor.getString(0), null); } finally { close(cursor, db); } } public void addHistoryItem(Result result, ResultHandler handler) { // Do not save this item to the history if the preference is turned off, or the contents are // considered secure. if (!activity.getIntent().getBooleanExtra(Intents.Scan.SAVE_HISTORY, true) || handler.areContentsSecure() || !enableHistory) { return; } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity); if (!prefs.getBoolean(PreferencesActivity.KEY_REMEMBER_DUPLICATES, false)) { deletePrevious(result.getText()); } ContentValues values = new ContentValues(); values.put(DBHelper.TEXT_COL, result.getText()); values.put(DBHelper.FORMAT_COL, result.getBarcodeFormat().toString()); values.put(DBHelper.DISPLAY_COL, handler.getDisplayContents().toString()); values.put(DBHelper.TIMESTAMP_COL, System.currentTimeMillis()); SQLiteOpenHelper helper = new DBHelper(activity); SQLiteDatabase db = null; try { db = helper.getWritableDatabase(); // Insert the new entry into the DB. db.insert(DBHelper.TABLE_NAME, DBHelper.TIMESTAMP_COL, values); } finally { close(null, db); } } public void addHistoryItemDetails(String itemID, String itemDetails) { // As we're going to do an update only we don't need need to worry // about the preferences; if the item wasn't saved it won't be udpated SQLiteOpenHelper helper = new DBHelper(activity); SQLiteDatabase db = null; Cursor cursor = null; try { db = helper.getWritableDatabase(); cursor = db.query(DBHelper.TABLE_NAME, ID_DETAIL_COL_PROJECTION, DBHelper.TEXT_COL + "=?", new String[] { itemID }, null, null, DBHelper.TIMESTAMP_COL + " DESC", "1"); String oldID = null; String oldDetails = null; if (cursor.moveToNext()) { oldID = cursor.getString(0); oldDetails = cursor.getString(1); } if (oldID != null) { String newDetails; if (oldDetails == null) { newDetails = itemDetails; } else if (oldDetails.contains(itemDetails)) { newDetails = null; } else { newDetails = oldDetails + " : " + itemDetails; } if (newDetails != null) { ContentValues values = new ContentValues(); values.put(DBHelper.DETAILS_COL, newDetails); db.update(DBHelper.TABLE_NAME, values, DBHelper.ID_COL + "=?", new String[] { oldID }); } } } finally { close(cursor, db); } } private void deletePrevious(String text) { SQLiteOpenHelper helper = new DBHelper(activity); SQLiteDatabase db = null; try { db = helper.getWritableDatabase(); db.delete(DBHelper.TABLE_NAME, DBHelper.TEXT_COL + "=?", new String[] { text }); } finally { close(null, db); } } public void trimHistory() { SQLiteOpenHelper helper = new DBHelper(activity); SQLiteDatabase db = null; Cursor cursor = null; try { db = helper.getWritableDatabase(); cursor = db.query(DBHelper.TABLE_NAME, ID_COL_PROJECTION, null, null, null, null, DBHelper.TIMESTAMP_COL + " DESC"); cursor.move(MAX_ITEMS); while (cursor.moveToNext()) { String id = cursor.getString(0); Log.i(TAG, "Deleting scan history ID " + id); db.delete(DBHelper.TABLE_NAME, DBHelper.ID_COL + '=' + id, null); } } catch (SQLiteException sqle) { // We're seeing an error here when called in CaptureActivity.onCreate() in rare cases // and don't understand it. First theory is that it's transient so can be safely ignored. Log.w(TAG, sqle); // continue } finally { close(cursor, db); } } /** * <p>Builds a text representation of the scanning history. Each scan is encoded on one * line, terminated by a line break (\r\n). The values in each line are comma-separated, * and double-quoted. Double-quotes within values are escaped with a sequence of two * double-quotes. The fields output are:</p> * * <ol> * <li>Raw text</li> * <li>Display text</li> * <li>Format (e.g. QR_CODE)</li> * <li>Unix timestamp (milliseconds since the epoch)</li> * <li>Formatted version of timestamp</li> * <li>Supplemental info (e.g. price info for a product barcode)</li> * </ol> */ CharSequence buildHistory() { SQLiteOpenHelper helper = new DBHelper(activity); SQLiteDatabase db = null; Cursor cursor = null; try { db = helper.getWritableDatabase(); cursor = db.query(DBHelper.TABLE_NAME, COLUMNS, null, null, null, null, DBHelper.TIMESTAMP_COL + " DESC"); DateFormat format = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM); StringBuilder historyText = new StringBuilder(1000); while (cursor.moveToNext()) { historyText.append('"').append(massageHistoryField(cursor.getString(0))).append("\","); historyText.append('"').append(massageHistoryField(cursor.getString(1))).append("\","); historyText.append('"').append(massageHistoryField(cursor.getString(2))).append("\","); historyText.append('"').append(massageHistoryField(cursor.getString(3))).append("\","); // Add timestamp again, formatted long timestamp = cursor.getLong(3); historyText.append('"').append(massageHistoryField( format.format(new Date(timestamp)))).append("\","); // Above we're preserving the old ordering of columns which had formatted data in position 5 historyText.append('"').append(massageHistoryField(cursor.getString(4))).append("\"\r\n"); } return historyText; } finally { close(cursor, db); } } void clearHistory() { SQLiteOpenHelper helper = new DBHelper(activity); SQLiteDatabase db = null; try { db = helper.getWritableDatabase(); db.delete(DBHelper.TABLE_NAME, null, null); } finally { close(null, db); } } static Uri saveHistory(String history) { File bsRoot = new File(Environment.getExternalStorageDirectory(), "BarcodeScanner"); File historyRoot = new File(bsRoot, "History"); if (!historyRoot.exists() && !historyRoot.mkdirs()) { Log.w(TAG, "Couldn't make dir " + historyRoot); return null; } File historyFile = new File(historyRoot, "history-" + System.currentTimeMillis() + ".csv"); OutputStreamWriter out = null; try { out = new OutputStreamWriter(new FileOutputStream(historyFile), Charset.forName("UTF-8")); out.write(history); return Uri.parse("file://" + historyFile.getAbsolutePath()); } catch (IOException ioe) { Log.w(TAG, "Couldn't access file " + historyFile + " due to " + ioe); return null; } finally { if (out != null) { try { out.close(); } catch (IOException ioe) { // do nothing } } } } private static String massageHistoryField(String value) { return value == null ? "" : value.replace("\"","\"\""); } private static void close(Cursor cursor, SQLiteDatabase database) { if (cursor != null) { cursor.close(); } if (database != null) { database.close(); } }}
0 0
- 二维码-去掉原始的HistoryManager也就是历史记录
- 去掉android二维码的边框
- 【转】BrowserManager和HistoryManager的应用
- 去掉开始菜单中的文档历史记录
- textbox html标签 如何去掉历史记录
- 去掉CSDN博客右边讨厌的二维码浮层
- h5的插入历史记录和替换历史记录
- Android Studio去掉应用标题也就是项目名字
- 使用web浏览器的“后退”和“前进”在flex程序中导航。HistoryManager实例
- 命令行的历史记录
- 数据库历史记录的处理。
- 操纵浏览器的历史记录
- 历史记录的搜索
- 读取job的历史记录
- Ubuntu 终端的历史记录
- c# 历史记录的实现
- Flex BrowserManager,HistoryManager解析
- 也就是一些简单的分享
- 微信公众号开发-log4j
- Java 使用 Redis
- ReactNative ListView基础功能
- 字符串转CGfloat
- httpClient(1)
- 二维码-去掉原始的HistoryManager也就是历史记录
- 美图面试c/c++内存分配方式不同
- Ubuntu安装搜狗中文输入法
- 面试中的 Singleton
- 09_组合在一起
- ReactNative ListView + 上拉加载更多
- Mybatis Generator(简称MBG)的最完整配置文件
- socket阻塞与非阻塞,同步与异步、I/O模型
- Jmeter+Ant性能测试报告