1
0
Fork 0

Fixed some bugs and cleaned up codes

* Fixed crash on backspacing from symbol (1 key)
* Hopefully fixed weird crash trying to dismiss view
* Fixed long press not working for SoftKeys
This commit is contained in:
Clam 2013-07-27 18:52:20 +10:00
parent 38df7d4563
commit e226f45c26
13 changed files with 1169 additions and 1092 deletions

View file

@ -1,8 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.nyanya.android.traditionalt9"
android:versionCode="2"
android:versionName="1.2" >
android:versionCode="4"
android:versionName="git" >
<uses-sdk
android:minSdkVersion="8"

View file

@ -21,6 +21,7 @@
<string name="add_word">Add word</string>
<string name="ok">OK</string>
<string name="add_word_blank">Blank word not added.</string>
<string name="add_word_badchar">Cannot add word with unmappable symbol.</string>
<string name="add_word_exist1">Word (</string>
<string name="add_word_exist2">) already in DB.</string>
<string name="cancel">Cancel</string>

View file

@ -8,78 +8,82 @@ import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
public abstract class AbsSymDialog extends Dialog
implements View.OnClickListener {
public abstract class AbsSymDialog extends Dialog implements
View.OnClickListener {
private TraditionalT9 parent;
private View mainview;
private int pagenum = 1;
private int pageoffset = (pagenum-1)*10;
private View mainview;
private int pagenum = 1;
private int pageoffset = (pagenum - 1) * 10;
private int MAX_PAGE;
private String title;
private boolean started;
private int MAX_PAGE;
private String title;
private boolean started;
private static final int[] buttons = {
R.id.text_keyone, R.id.text_keytwo, R.id.text_keythree,
R.id.text_keyfour, R.id.text_keyfive, R.id.text_keysix,
R.id.text_keyseven, R.id.text_keyeight, R.id.text_keynine,
R.id.text_keyzero };
private static final int[] buttons2 = { R.id.text_keystar, R.id.text_keypound };
private static final int[] buttons = {
R.id.text_keyone, R.id.text_keytwo,
R.id.text_keythree, R.id.text_keyfour, R.id.text_keyfive,
R.id.text_keysix, R.id.text_keyseven, R.id.text_keyeight,
R.id.text_keynine, R.id.text_keyzero
};
private static final int[] buttons2 = {
R.id.text_keystar,
R.id.text_keypound
};
public AbsSymDialog(Context c, View mv) {
super(c);
parent = (TraditionalT9) c;
mainview = mv;
started = true;
setContentView(mv);
super(c);
parent = (TraditionalT9) c;
mainview = mv;
started = true;
setContentView(mv);
View button;
for (int x = 0; x < buttons.length; x++){
for (int x = 0; x < buttons.length; x++) {
button = mv.findViewById(buttons[x]);
button.setOnClickListener(this);
}
for (int x = 0; x < buttons2.length; x++){
for (int x = 0; x < buttons2.length; x++) {
button = mv.findViewById(buttons2[x]);
button.setOnClickListener(this);
}
MAX_PAGE = getMaxPage();
title = getTitleText();
}
}
@Override
public void onClick(View v) {
//Log.d("SymbolPopup - onClick", "click happen: " + v);
// Log.d("SymbolPopup - onClick", "click happen: " + v);
switch (v.getId()) {
case R.id.text_keyone:
sendChar(pageoffset+0);
sendChar(pageoffset + 0);
break;
case R.id.text_keytwo:
sendChar(pageoffset+1);
sendChar(pageoffset + 1);
break;
case R.id.text_keythree:
sendChar(pageoffset+2);
sendChar(pageoffset + 2);
break;
case R.id.text_keyfour:
sendChar(pageoffset+3);
sendChar(pageoffset + 3);
break;
case R.id.text_keyfive:
sendChar(pageoffset+4);
sendChar(pageoffset + 4);
break;
case R.id.text_keysix:
sendChar(pageoffset+5);
sendChar(pageoffset + 5);
break;
case R.id.text_keyseven:
sendChar(pageoffset+6);
sendChar(pageoffset + 6);
break;
case R.id.text_keyeight:
sendChar(pageoffset+7);
sendChar(pageoffset + 7);
break;
case R.id.text_keynine:
sendChar(pageoffset+8);
sendChar(pageoffset + 8);
break;
case R.id.text_keyzero:
sendChar(pageoffset+9);
sendChar(pageoffset + 9);
break;
case R.id.text_keypound:
@ -97,58 +101,61 @@ public abstract class AbsSymDialog extends Dialog
protected abstract int getMaxPage();
private void sendChar(int index) {
//Log.d("SymbolDialog - sendChar", "Sending index: " + index);
// Log.d("SymbolDialog - sendChar", "Sending index: " + index);
if (index < getSymbolSize()) {
parent.onText(getSymbol(index));
//then close
// then close
pagenum = 1;
pageoffset = (pagenum-1)*10;
pageoffset = (pagenum - 1) * 10;
this.dismiss();
}
}
private void pageChange(int amt) {
pagenum = pagenum + amt;
if (pagenum > MAX_PAGE ) {
if (pagenum > MAX_PAGE) {
pagenum = 1;
} else if (pagenum < 1) {
pagenum = MAX_PAGE;
}
pageoffset = (pagenum-1)*10;
pageoffset = (pagenum - 1) * 10;
updateButtons();
}
private void updateButtons() {
// set page number text
setTitle("Insert "+ title + "\t\tPage " + pagenum + "/" + MAX_PAGE);
setTitle("Insert " + title + "\t\tPage " + pagenum + "/" + MAX_PAGE);
// update button labels
int symbx = pageoffset;
int stop = symbx + 9;
int nomore = stop;
int symsize = getSymbolSize();
if (nomore >= symsize-1) {
nomore = symsize-1;
if (nomore >= symsize - 1) {
nomore = symsize - 1;
}
for (int buttx = 0; symbx <= stop; symbx++) {
//Log.d("SymbolDialog - updateButtons", "buttx: " + buttx + " symbx: " + symbx);
// Log.d("SymbolDialog - updateButtons", "buttx: " + buttx +
// " symbx: " + symbx);
if (symbx > nomore) {
((TextView)mainview.findViewById(buttons[buttx])).setText("");
((TextView) mainview.findViewById(buttons[buttx])).setText("");
} else {
((TextView)mainview.findViewById(buttons[buttx])).setText(String.valueOf(getSymbol(symbx)));
((TextView) mainview.findViewById(buttons[buttx]))
.setText(String.valueOf(getSymbol(symbx)));
}
buttx++;
}
}
@Override public boolean onKeyDown(int keyCode, KeyEvent event){
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getRepeatCount() != 0) {
return true;
}
if (started) {
started = false;
}
//TODO: remove emulator special keys
// TODO: remove emulator special keys
switch (keyCode) {
case 75:
keyCode = KeyEvent.KEYCODE_POUND;
@ -157,7 +164,7 @@ public abstract class AbsSymDialog extends Dialog
keyCode = KeyEvent.KEYCODE_STAR;
break;
}
//Log.d("AbsSymDialog.onKeyDown", "bootan pres: " + keyCode);
// Log.d("AbsSymDialog.onKeyDown", "bootan pres: " + keyCode);
switch (keyCode) {
case KeyEvent.KEYCODE_0:
@ -178,13 +185,14 @@ public abstract class AbsSymDialog extends Dialog
return super.onKeyDown(keyCode, event);
}
@Override public boolean onKeyUp(int keyCode, KeyEvent event) {
//Log.d("AbsSymDialog.onKeyUp", "Key: " + keyCode);
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
// Log.d("AbsSymDialog.onKeyUp", "Key: " + keyCode);
if (started) {
started = false;
return true;
}
//TODO: remove emulator special keys
// TODO: remove emulator special keys
switch (keyCode) {
case 75:
keyCode = KeyEvent.KEYCODE_POUND;
@ -194,7 +202,7 @@ public abstract class AbsSymDialog extends Dialog
break;
}
switch (keyCode) {
//pass-through
// pass-through
case KeyEvent.KEYCODE_0:
case KeyEvent.KEYCODE_1:
case KeyEvent.KEYCODE_2:
@ -210,46 +218,47 @@ public abstract class AbsSymDialog extends Dialog
onKey(keyCode);
return true;
default:
//KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_KEYBOARD).getNumber(keyCode)
//Log.w("onKeyUp", "Unhandled Key: " + keyCode + "(" + event.toString() + ")");
// KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_KEYBOARD).getNumber(keyCode)
// Log.w("onKeyUp", "Unhandled Key: " + keyCode + "(" +
// event.toString() + ")");
}
return super.onKeyUp(keyCode, event);
}
private void onKey(int keyCode) {
//Log.d("OnKey", "pri: " + keyCode);
//Log.d("onKey", "START Cm: " + mCapsMode);
//HANDLE SPECIAL KEYS
// Log.d("OnKey", "pri: " + keyCode);
// Log.d("onKey", "START Cm: " + mCapsMode);
// HANDLE SPECIAL KEYS
switch (keyCode) {
case KeyEvent.KEYCODE_1:
sendChar(pageoffset+0);
sendChar(pageoffset + 0);
break;
case KeyEvent.KEYCODE_2:
sendChar(pageoffset+1);
sendChar(pageoffset + 1);
break;
case KeyEvent.KEYCODE_3:
sendChar(pageoffset+2);
sendChar(pageoffset + 2);
break;
case KeyEvent.KEYCODE_4:
sendChar(pageoffset+3);
sendChar(pageoffset + 3);
break;
case KeyEvent.KEYCODE_5:
sendChar(pageoffset+4);
sendChar(pageoffset + 4);
break;
case KeyEvent.KEYCODE_6:
sendChar(pageoffset+5);
sendChar(pageoffset + 5);
break;
case KeyEvent.KEYCODE_7:
sendChar(pageoffset+6);
sendChar(pageoffset + 6);
break;
case KeyEvent.KEYCODE_8:
sendChar(pageoffset+7);
sendChar(pageoffset + 7);
break;
case KeyEvent.KEYCODE_9:
sendChar(pageoffset+8);
sendChar(pageoffset + 8);
break;
case KeyEvent.KEYCODE_0:
sendChar(pageoffset+9);
sendChar(pageoffset + 9);
break;
case KeyEvent.KEYCODE_STAR:
pageChange(-1);
@ -261,15 +270,15 @@ public abstract class AbsSymDialog extends Dialog
}
protected void doShow(View v) {
// based on http://stackoverflow.com/a/13962770
// based on http://stackoverflow.com/a/13962770
started = true;
Window win = getWindow();
WindowManager.LayoutParams lp = win.getAttributes();
lp.token = v.getWindowToken();
lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
win.setAttributes(lp);
win.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
updateButtons();
show();
lp.token = v.getWindowToken();
lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
win.setAttributes(lp);
win.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
updateButtons();
show();
}
}

View file

@ -2,6 +2,7 @@ package org.nyanya.android.traditionalt9;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
@ -14,9 +15,9 @@ public class AddWordAct extends Activity {
protected void onCreate(Bundle savedData) {
super.onCreate(savedData);
View v = getLayoutInflater().inflate(R.layout.addwordview, null);
EditText et = (EditText)v.findViewById(R.id.add_word_text);
EditText et = (EditText) v.findViewById(R.id.add_word_text);
String word = getIntent().getStringExtra("org.nyanya.android.traditionalt9.word");
//Log.d("AddWord", "data.get: " + word);
// Log.d("AddWord", "data.get: " + word);
et.setText(word);
et.setSelection(word.length());
setContentView(v);
@ -25,18 +26,23 @@ public class AddWordAct extends Activity {
public void addWordButton(View v) {
EditText et = (EditText) main.findViewById(R.id.add_word_text);
//Log.d("AddWordAct", "adding word: " + et.getText());
TraditionalT9.ghettoaccess.doAddWord(et.getText().toString());
// Log.d("AddWordAct", "adding word: " + et.getText());
if (TraditionalT9.ghettoaccess == null) {
Log.e("AddWordAct.addWordbutton", "ghettoaccess is null? Oh no.");
} else {
TraditionalT9.ghettoaccess.doAddWord(et.getText().toString());
}
this.finish();
}
public void cancelButton(View v) {
//Log.d("AddWordAct", "Cancelled...");
//TraditionalT9.ghettoaccess.addCancel();
// Log.d("AddWordAct", "Cancelled...");
// TraditionalT9.ghettoaccess.addCancel();
this.finish();
}
@Override public void onStop() {
@Override
public void onStop() {
TraditionalT9.ghettoaccess.addCancel();
super.onStop();
}

View file

@ -4,7 +4,6 @@ import java.util.ArrayList;
import java.util.List;
import org.nyanya.android.traditionalt9.R;
import org.nyanya.android.traditionalt9.TraditionalT9;
import android.content.Context;
import android.content.res.Resources;
@ -16,223 +15,211 @@ import android.view.View;
public class CandidateView extends View {
//private TraditionalT9 mService;
private List<String> mSuggestions;
protected int mSelectedIndex;
// private TraditionalT9 mService;
private List<String> mSuggestions;
protected int mSelectedIndex;
private Drawable mSelectionHighlight;
private Drawable mSelectionHighlight;
private Rect mBgPadding;
private Rect mBgPadding;
private static final int MAX_SUGGESTIONS = 32;
private static final int SCROLL_PIXELS = 20;
private static final int MAX_SUGGESTIONS = 32;
private static final int SCROLL_PIXELS = 20;
private int[] mWordWidth = new int[MAX_SUGGESTIONS];
private int[] mWordX = new int[MAX_SUGGESTIONS];
private int[] mWordWidth = new int[MAX_SUGGESTIONS];
private int[] mWordX = new int[MAX_SUGGESTIONS];
private static final int X_GAP = 10;
private static final int X_GAP = 10;
private static final List<String> EMPTY_LIST = new ArrayList<String>();
private static final List<String> EMPTY_LIST = new ArrayList<String>();
private int mColorNormal;
private int mColorRecommended;
private int mColorOther;
private int mVerticalPadding;
private Paint mPaint;
private int mTargetScrollX;
private int mColorNormal;
private int mColorRecommended;
private int mColorOther;
private int mVerticalPadding;
private Paint mPaint;
private int mTargetScrollX;
private int mTotalWidth;
private int mTotalWidth;
Rect mPadding;
Rect mPadding;
/**
* Construct a CandidateView for showing suggested words for completion.
* @param context
* @param attrs
*/
public CandidateView(Context context) {
super(context);
mSelectionHighlight = context.getResources().getDrawable(
android.R.drawable.list_selector_background);
mSelectionHighlight.setState(new int[] {
android.R.attr.state_enabled,
android.R.attr.state_focused,
android.R.attr.state_window_focused,
android.R.attr.state_pressed
});
/**
* Construct a CandidateView for showing suggested words for completion.
*
* @param context
* @param attrs
*/
public CandidateView(Context context) {
super(context);
mSelectionHighlight = context.getResources().getDrawable(
android.R.drawable.list_selector_background);
mSelectionHighlight.setState(new int[] {
android.R.attr.state_enabled, android.R.attr.state_focused,
android.R.attr.state_window_focused, android.R.attr.state_pressed });
Resources r = context.getResources();
Resources r = context.getResources();
setBackgroundColor(r.getColor(R.color.candidate_background));
setBackgroundColor(r.getColor(R.color.candidate_background));
mColorNormal = r.getColor(R.color.candidate_normal);
mColorRecommended = r.getColor(R.color.candidate_recommended);
mColorOther = r.getColor(R.color.candidate_other);
mVerticalPadding = r.getDimensionPixelSize(R.dimen.candidate_vertical_padding);
mColorNormal = r.getColor(R.color.candidate_normal);
mColorRecommended = r.getColor(R.color.candidate_recommended);
mColorOther = r.getColor(R.color.candidate_other);
mVerticalPadding = r.getDimensionPixelSize(R.dimen.candidate_vertical_padding);
mPaint = new Paint();
mPaint.setColor(mColorNormal);
mPaint.setAntiAlias(true);
mPaint.setTextSize(r.getDimensionPixelSize(R.dimen.candidate_font_height));
mPaint.setStrokeWidth(0);
mPaint = new Paint();
mPaint.setColor(mColorNormal);
mPaint.setAntiAlias(true);
mPaint.setTextSize(r.getDimensionPixelSize(R.dimen.candidate_font_height));
mPaint.setStrokeWidth(0);
mPadding = new Rect();
mPadding = new Rect();
setHorizontalFadingEdgeEnabled(true);
setWillNotDraw(false);
setHorizontalScrollBarEnabled(false);
setVerticalScrollBarEnabled(false);
}
setHorizontalFadingEdgeEnabled(true);
setWillNotDraw(false);
setHorizontalScrollBarEnabled(false);
setVerticalScrollBarEnabled(false);
}
/**
* A connection back to the service to communicate with the text field
* @param listener
*/
public void setService(TraditionalT9 listener) {
//mService = listener;
}
@Override
public int computeHorizontalScrollRange() {
return mTotalWidth;
}
@Override
public int computeHorizontalScrollRange() {
return mTotalWidth;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int measuredWidth = resolveSize(50, widthMeasureSpec);
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int measuredWidth = resolveSize(50, widthMeasureSpec);
// Get the desired height of the icon menu view (last row of items does
// not have a divider below)
// Get the desired height of the icon menu view (last row of items does
// not have a divider below)
mSelectionHighlight.getPadding(mPadding);
final int desiredHeight = ((int) mPaint.getTextSize()) + mVerticalPadding + mPadding.top
+ mPadding.bottom;
mSelectionHighlight.getPadding(mPadding);
final int desiredHeight = ((int)mPaint.getTextSize()) + mVerticalPadding
+ mPadding.top + mPadding.bottom;
// Maximum possible width and desired height
setMeasuredDimension(measuredWidth, resolveSize(desiredHeight, heightMeasureSpec));
}
// Maximum possible width and desired height
setMeasuredDimension(measuredWidth,
resolveSize(desiredHeight, heightMeasureSpec));
}
/**
* If the canvas is null, then only touch calculations are performed to pick
* the target candidate.
*/
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
/**
* If the canvas is null, then only touch calculations are performed to pick the target
* candidate.
*/
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mTotalWidth = 0;
if (mSuggestions == null)
return;
mTotalWidth = 0;
if (mSuggestions == null) return;
if (mBgPadding == null) {
mBgPadding = new Rect(0, 0, 0, 0);
if (getBackground() != null) {
getBackground().getPadding(mBgPadding);
}
}
int x = 0;
final int count = mSuggestions.size();
final int height = getHeight();
final Rect bgPadding = mBgPadding;
final Paint paint = mPaint;
final int y = (int) (((height - mPaint.getTextSize()) / 2) - mPaint.ascent());
if (mBgPadding == null) {
mBgPadding = new Rect(0, 0, 0, 0);
if (getBackground() != null) {
getBackground().getPadding(mBgPadding);
}
}
int x = 0;
final int count = mSuggestions.size();
final int height = getHeight();
final Rect bgPadding = mBgPadding;
final Paint paint = mPaint;
final int y = (int) (((height - mPaint.getTextSize()) / 2) - mPaint.ascent());
for (int i = 0; i < count; i++) {
String suggestion = mSuggestions.get(i);
float textWidth = paint.measureText(suggestion);
final int wordWidth = (int) textWidth + X_GAP * 2;
for (int i = 0; i < count; i++) {
String suggestion = mSuggestions.get(i);
float textWidth = paint.measureText(suggestion);
final int wordWidth = (int) textWidth + X_GAP * 2;
mWordX[i] = x;
mWordWidth[i] = wordWidth;
paint.setColor(mColorNormal);
// if (touchX + scrollX >= x && touchX + scrollX < x + wordWidth &&
// !scrolled) {
if (i == mSelectedIndex) {
canvas.translate(x, 0);
mSelectionHighlight.setBounds(0, bgPadding.top, wordWidth, height);
mSelectionHighlight.draw(canvas);
canvas.translate(-x, 0);
paint.setFakeBoldText(true);
paint.setColor(mColorRecommended);
} else {
paint.setColor(mColorOther);
}
mWordX[i] = x;
mWordWidth[i] = wordWidth;
paint.setColor(mColorNormal);
//if (touchX + scrollX >= x && touchX + scrollX < x + wordWidth && !scrolled) {
if (i == mSelectedIndex) {
canvas.translate(x, 0);
mSelectionHighlight.setBounds(0, bgPadding.top, wordWidth, height);
mSelectionHighlight.draw(canvas);
canvas.translate(-x, 0);
paint.setFakeBoldText(true);
paint.setColor(mColorRecommended);
}
else {
paint.setColor(mColorOther);
}
canvas.drawText(suggestion, x + X_GAP, y, paint);
paint.setColor(mColorOther);
canvas.drawLine(x + wordWidth + 0.5f, bgPadding.top, x + wordWidth + 0.5f, height + 1,
paint);
paint.setFakeBoldText(false);
canvas.drawText(suggestion, x + X_GAP, y, paint);
paint.setColor(mColorOther);
canvas.drawLine(x + wordWidth + 0.5f, bgPadding.top,
x + wordWidth + 0.5f, height + 1, paint);
paint.setFakeBoldText(false);
x += wordWidth;
}
mTotalWidth = x;
if (mTargetScrollX != getScrollX()) {
scrollToTarget();
}
}
x += wordWidth;
}
mTotalWidth = x;
if (mTargetScrollX != getScrollX()) {
scrollToTarget();
}
}
private void scrollToTarget() {
int sx = getScrollX();
if (mTargetScrollX > sx) {
sx += SCROLL_PIXELS;
if (sx >= mTargetScrollX) {
sx = mTargetScrollX;
requestLayout();
}
} else {
sx -= SCROLL_PIXELS;
if (sx <= mTargetScrollX) {
sx = mTargetScrollX;
requestLayout();
}
}
scrollTo(sx, getScrollY());
invalidate();
}
private void scrollToTarget() {
int sx = getScrollX();
if (mTargetScrollX > sx) {
sx += SCROLL_PIXELS;
if (sx >= mTargetScrollX) {
sx = mTargetScrollX;
requestLayout();
}
} else {
sx -= SCROLL_PIXELS;
if (sx <= mTargetScrollX) {
sx = mTargetScrollX;
requestLayout();
}
}
scrollTo(sx, getScrollY());
invalidate();
}
public void setSuggestions(List<String> suggestions, int initialSel) {
clear();
if (suggestions != null) {
mSuggestions = suggestions;
mSelectedIndex = initialSel;
}
scrollTo(0, 0);
mTargetScrollX = 0;
// Compute the total width
// onDraw(null);
invalidate();
requestLayout();
}
public void setSuggestions(List<String> suggestions, int initialSel) {
clear();
if (suggestions != null) {
mSuggestions = suggestions;
mSelectedIndex = initialSel;
}
scrollTo(0, 0);
mTargetScrollX = 0;
// Compute the total width
//onDraw(null);
invalidate();
requestLayout();
}
public void clear() {
mSuggestions = EMPTY_LIST;
mSelectedIndex = -1;
invalidate();
}
public void clear() {
mSuggestions = EMPTY_LIST;
mSelectedIndex = -1;
invalidate();
}
protected void scrollSuggestion(int increment) {
if (mSuggestions != null && mSuggestions.size() > 1) {
mSelectedIndex = mSelectedIndex + increment;
if (mSelectedIndex == mSuggestions.size()) {
mSelectedIndex = 0;
} else if (mSelectedIndex < 0) {
mSelectedIndex = mSuggestions.size() - 1;
}
protected void scrollSuggestion(int increment) {
if (mSuggestions != null && mSuggestions.size() > 1) {
mSelectedIndex = mSelectedIndex + increment;
if (mSelectedIndex == mSuggestions.size()) {
mSelectedIndex = 0;
} else if (mSelectedIndex < 0) {
mSelectedIndex = mSuggestions.size()-1;
}
int fullsize = getWidth();
int halfsize = fullsize/2;
mTargetScrollX = mWordX[mSelectedIndex] + (mWordWidth[mSelectedIndex]/2) - halfsize;
int fullsize = getWidth();
int halfsize = fullsize / 2;
mTargetScrollX = mWordX[mSelectedIndex] + (mWordWidth[mSelectedIndex] / 2) - halfsize;
if (mTargetScrollX < 0) {
mTargetScrollX = 0;
} else if (mTargetScrollX > (mTotalWidth - fullsize) ) {
} else if (mTargetScrollX > (mTotalWidth - fullsize)) {
mTargetScrollX = mTotalWidth - fullsize;
}
invalidate();
}
}
invalidate();
}
}
}

View file

@ -8,13 +8,18 @@ import java.util.Map;
import android.util.Log;
public class CharMap {
protected static final Map<Character, Integer> CHARTABLE;
protected static final Map<Character, Integer> CHARTABLE;
static {
Map<Character, Integer> aMap = new HashMap<Character, Integer>();
aMap.put('.', 1); aMap.put(',', 1); aMap.put('!', 1); aMap.put('?', 1);
aMap.put('-', 1); aMap.put('"', 1); aMap.put('\'', 1); aMap.put('@', 1);
aMap.put('#', 1); aMap.put('$', 1); aMap.put('%', 1); aMap.put('&', 1);
aMap.put('*', 1); aMap.put('(', 1); aMap.put(')', 1); aMap.put('1', 1);
aMap.put(':', 1); aMap.put(';', 1); aMap.put('/', 1); aMap.put('\\', 1);
aMap.put('+', 1); aMap.put('=', 1); aMap.put('<', 1); aMap.put('>', 1);
aMap.put('[', 1); aMap.put(']', 1); aMap.put('{', 1); aMap.put('}', 1);
aMap.put('^', 1); aMap.put('|', 1); aMap.put('_', 1); aMap.put('~', 1);
aMap.put('`', 1);
aMap.put('a', 2); aMap.put('\u00e1', 2); aMap.put('\u00e4', 2);
aMap.put('\u00e2', 2); aMap.put('\u00e0', 2); aMap.put('\u00e5', 2);
aMap.put('b', 2); aMap.put('c', 2); aMap.put('\u00e7', 2);
@ -35,46 +40,45 @@ public class CharMap {
aMap.put('9', 9); aMap.put('+', 0); aMap.put('0', 0);
CHARTABLE = Collections.unmodifiableMap(aMap);
}
protected static final char[][] T9TABLE = {
{'0', '+'}, {'.', ',', '!', '?', '-', '"', '\'', '@', '#', '$', '%', '&', '*', '(', ')', '1'},
{'a', 'b', 'c', 'A', 'B', 'C', '2'}, {'d', 'e', 'f', 'D', 'E', 'F', '3'},
{'g', 'h', 'i', 'G', 'H', 'I', '4'}, {'j', 'k', 'l', 'J', 'K', 'L', '5'},
{'m', 'n', 'o', 'M', 'N', 'O', '6'}, {'p', 'q', 'r', 's', 'P', 'Q', 'R', 'S', '7'},
{'t', 'u', 'v', 'T', 'U', 'V', '8'}, {'w', 'x', 'y', 'z', 'W', 'X', 'Y', 'Z', '9'},
{' ', '\n'}
};
protected static final char[][] T9TABLE = { { '0', '+' },
{ '.', ',', '!', '?', '-', '"', '\'', '@', '#', '$', '%', '&', '*', '(', ')', '1' },
{ 'a', 'b', 'c', 'A', 'B', 'C', '2' }, { 'd', 'e', 'f', 'D', 'E', 'F', '3' },
{ 'g', 'h', 'i', 'G', 'H', 'I', '4' }, { 'j', 'k', 'l', 'J', 'K', 'L', '5' },
{ 'm', 'n', 'o', 'M', 'N', 'O', '6' }, { 'p', 'q', 'r', 's', 'P', 'Q', 'R', 'S', '7' },
{ 't', 'u', 'v', 'T', 'U', 'V', '8' }, { 'w', 'x', 'y', 'z', 'W', 'X', 'Y', 'Z', '9' },
{ ' ', '\n' } };
protected static final int[] T9CAPSTART = {
0, 0, 3, 3, 3, 3, 3, 4, 3, 4, 0
};
protected static final int[] T9CAPSTART = { 0, 0, 3, 3, 3, 3, 3, 4, 3, 4, 0 };
protected static int[] getSequence(String word){
protected static int[] getSequence(String word) {
int[] intseq = new int[word.length()];
String tword = word.toLowerCase(Locale.ENGLISH);
for (int i = 0; i < word.length(); i++){
for (int i = 0; i < word.length(); i++) {
char c = tword.charAt(i);
Integer z = CharMap.CHARTABLE.get(c);
if (z == null){
Log.e("getSequence", "ERROR: "+ (int)c + " NOT FOUND (" + Integer.toHexString((int)c) + ")");
throw new NullPointerException();
}
intseq[i] = z;
Integer z = CharMap.CHARTABLE.get(c);
if (z == null) {
Log.e("getSequence",
"ERROR: " + (int) c + " NOT FOUND (" + Integer.toHexString((int) c) + ")");
throw new NullPointerException();
}
intseq[i] = z;
}
return intseq;
}
protected static String getStringSequence(String word){
StringBuilder seq = new StringBuilder();
String tword = word.toLowerCase(Locale.ENGLISH);
for (int i = 0; i < word.length(); i++){
protected static String getStringSequence(String word) {
StringBuilder seq = new StringBuilder();
String tword = word.toLowerCase(Locale.ENGLISH);
for (int i = 0; i < word.length(); i++) {
char c = tword.charAt(i);
Integer z = CharMap.CHARTABLE.get(c);
if (z == null){
Log.e("getStringSequence", "ERROR: "+ (int)c + " NOT FOUND (" + Integer.toHexString((int)c) + ")");
throw new NullPointerException();
}
seq.append(z.toString());
Integer z = CharMap.CHARTABLE.get(c);
if (z == null) {
Log.e("getStringSequence",
"ERROR: " + (int) c + " NOT FOUND (" + Integer.toHexString((int) c) + ")");
throw new NullPointerException();
}
seq.append(z.toString());
}
return seq.toString();
}
return seq.toString();
}
}

View file

@ -25,16 +25,16 @@ public class InterfaceHandler implements View.OnClickListener, View.OnLongClickL
}
protected void clearParent() {
ViewGroup vg = ((ViewGroup)mainview.getParent());
ViewGroup vg = ((ViewGroup) mainview.getParent());
if (vg != null) {
vg.removeView(mainview);
}
}
protected void changeView(View v){
protected void changeView(View v) {
this.mainview = v;
View button;
for (int x = 0; x < buttons.length; x++){
for (int x = 0; x < buttons.length; x++) {
button = v.findViewById(buttons[x]);
button.setOnClickListener(this);
if (!parent.mAddingWord) {
@ -42,9 +42,10 @@ public class InterfaceHandler implements View.OnClickListener, View.OnLongClickL
}
}
}
protected void setPressed(int keyCode, boolean pressed){
protected void setPressed(int keyCode, boolean pressed) {
int id = 0;
switch(keyCode) {
switch (keyCode) {
case KeyEvent.KEYCODE_SOFT_LEFT:
id = R.id.main_left;
break;
@ -60,13 +61,17 @@ public class InterfaceHandler implements View.OnClickListener, View.OnLongClickL
}
}
protected void showNotFound(boolean notfound){
protected void showNotFound(boolean notfound) {
if (notfound) {
((TextView) mainview.findViewById(R.id.left_hold_upper)).setText(R.string.main_left_notfound);
((TextView) mainview.findViewById(R.id.left_hold_lower)).setText(R.string.main_left_insert);
((TextView) mainview.findViewById(R.id.left_hold_upper))
.setText(R.string.main_left_notfound);
((TextView) mainview.findViewById(R.id.left_hold_lower))
.setText(R.string.main_left_insert);
} else {
((TextView) mainview.findViewById(R.id.left_hold_upper)).setText(R.string.main_left_insert);
((TextView) mainview.findViewById(R.id.left_hold_lower)).setText(R.string.main_left_addword);
((TextView) mainview.findViewById(R.id.left_hold_upper))
.setText(R.string.main_left_insert);
((TextView) mainview.findViewById(R.id.left_hold_lower))
.setText(R.string.main_left_addword);
}
}
@ -74,7 +79,7 @@ public class InterfaceHandler implements View.OnClickListener, View.OnLongClickL
((Button) mainview.findViewById(R.id.main_mid)).performClick();
}
protected void midButtonUpdate(boolean composing){
protected void midButtonUpdate(boolean composing) {
if (composing) {
((Button) mainview.findViewById(R.id.main_mid)).setText(R.string.main_mid_commit);
} else {
@ -82,25 +87,26 @@ public class InterfaceHandler implements View.OnClickListener, View.OnLongClickL
}
}
@Override public void onClick(View v) {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.main_left:
if (parent.mAddingWord) {
case R.id.main_left:
if (parent.mAddingWord) {
parent.showSymbolPage();
} else {
if (parent.mWordFound) {
parent.showSymbolPage();
} else {
if (parent.mWordFound) {
parent.showSymbolPage();
} else {
parent.showAddWord();
}
parent.showAddWord();
}
break;
case R.id.main_mid:
parent.handleMidButton();
break;
case R.id.main_right:
parent.nextKeyMode();
break;
}
break;
case R.id.main_mid:
parent.handleMidButton();
break;
case R.id.main_right:
parent.nextKeyMode();
break;
}
}
@ -113,16 +119,18 @@ public class InterfaceHandler implements View.OnClickListener, View.OnLongClickL
}
}
@Override public boolean onLongClick(View v) {
@Override
public boolean onLongClick(View v) {
switch (v.getId()) {
case R.id.main_left:
parent.showAddWord();
break;
case R.id.main_right:
((InputMethodManager) parent.getSystemService (Context.INPUT_METHOD_SERVICE)).showInputMethodPicker();
break;
default:
return false;
case R.id.main_left:
parent.showAddWord();
break;
case R.id.main_right:
((InputMethodManager) parent.getSystemService(Context.INPUT_METHOD_SERVICE))
.showInputMethodPicker();
break;
default:
return false;
}
return true;
}

View file

@ -5,25 +5,21 @@ import android.view.View;
public class SmileyDialog extends AbsSymDialog {
private static final String[] symbols = {
//lol wiki http://en.wikipedia.org/wiki/List_of_emoticons
":-)", ":)", ":o)", ":]", ":3", ":c)", ":>", "=]", "=)", ":}",
":-D", ":D", "8-D", "8D", "X-D", "XD", "=-D", "=D", "B^D",
">:[", ":-(", ":(", ":c", ":-<", ":<", ":-[", ":[", ":{",
":'-(", ":'(", ":'-)", ":')", ":@", "D:<", "D:", "D8", "D;", "D=", "DX",
"v.v", "D-':", ">:O", ":-O", ":O", ":O", "o_O", "o_0", "o.O", "8-0",
":*", ";-)", ";)", ";-]", ";]", ";D",
">:P", ":-P", ":P", "XP", "xp", ":-p", ":p", "=p", ":-b", ":b",
">:\\", ">:/", ":-/", ":-.", ":/", ":\\", "=/", "=\\", ":L", "=L", ":S", ">.<",
":|", ":-|", ":$", ":-X", ":X", ":-#", ":#", "O:-)", "0:-3", "0:3", "0:-)", "0:)",
">:)", ">;)", ">:-)", ">_>", "<_<", "\\o/", "<3", "</3",
"=-3", "=3",
};
private static final String[] symbols = {
// lol wiki http://en.wikipedia.org/wiki/List_of_emoticons
":-)", ":)", ":o)", ":]", ":3", ":c)", ":>", "=]", "=)", ":}", ":-D", ":D", "8-D",
"8D", "X-D", "XD", "=-D", "=D", "B^D", ">:[", ":-(", ":(", ":c", ":-<", ":<", ":-[",
":[", ":{", ":'-(", ":'(", ":'-)", ":')", ":@", "D:<", "D:", "D8", "D;", "D=", "DX",
"v.v", "D-':", ">:O", ":-O", ":O", ":O", "o_O", "o_0", "o.O", "8-0", ":*", ";-)", ";)",
";-]", ";]", ";D", ">:P", ":-P", ":P", "XP", "xp", ":-p", ":p", "=p", ":-b", ":b",
">:\\", ">:/", ":-/", ":-.", ":/", ":\\", "=/", "=\\", ":L", "=L", ":S", ">.<", ":|",
":-|", ":$", ":-X", ":X", ":-#", ":#", "O:-)", "0:-3", "0:3", "0:-)", "0:)", ">:)",
">;)", ">:-)", ">_>", "<_<", "\\o/", "<3", "</3", "=-3", "=3", };
private static final int MAX_PAGE = (int)Math.ceil(symbols.length / 10.0);
private static final int MAX_PAGE = (int) Math.ceil(symbols.length / 10.0);
public SmileyDialog(Context c, View mv) {
super(c, mv);
super(c, mv);
}
@Override

View file

@ -3,18 +3,16 @@ package org.nyanya.android.traditionalt9;
import android.content.Context;
import android.view.View;
public class SymbolDialog extends AbsSymDialog {
private static final char[] symbols = {
'.', ',', '!', '?', '$', '&', '%', '#', '@', '"', '\'', ':', ';', '(', ')', '/', '\\',
'-', '+', '=', '*', '<', '>', '[', ']', '{', '}', '^', '|', '_', '~', '`'
}; //32
private static final int MAX_PAGE = (int)Math.ceil(symbols.length / 10.0);
private static final char[] symbols = {
'.', ',', '!', '?', '$', '&', '%', '#', '@', '"', '\'', ':', ';', '(', ')', '/', '\\',
'-', '+', '=', '*', '<', '>', '[', ']', '{', '}', '^', '|', '_', '~', '`' }; // 32
private static final int MAX_PAGE = (int) Math.ceil(symbols.length / 10.0);
public SymbolDialog(Context c, View mv) {
super(c, mv);
}
super(c, mv);
}
@Override
protected String getSymbol(int index) {
@ -36,6 +34,4 @@ public class SymbolDialog extends AbsSymDialog {
return MAX_PAGE;
}
}

View file

@ -20,7 +20,7 @@ public class T9DB {
protected static final int DATABASE_VERSION = 1;
protected static final String WORD_TABLE_NAME = "word";
protected static final String FREQ_TRIGGER_NAME = "freqtrigger";
//50k, 10k
// 50k, 10k
private static final int FREQ_MAX = 50000;
private static final int FREQ_DIV = 10000;
@ -32,9 +32,9 @@ public class T9DB {
private static final int MAX_RESULTS = 8;
private static final int CAPS_OFF = 0;
private static final int CAPS_SINGLE = 1;
private static final int CAPS_ALL = 2;
private static final int CAPS_OFF = 0;
private static final int CAPS_SINGLE = 1;
private static final int CAPS_ALL = 2;
private DatabaseHelper mOpenHelper;
private SQLiteDatabase db;
@ -42,7 +42,7 @@ public class T9DB {
private Context parent;
public T9DB(Context caller) {
//create db
// create db
parent = caller;
mOpenHelper = new DatabaseHelper(caller);
}
@ -53,7 +53,7 @@ public class T9DB {
public void init() {
db = mOpenHelper.getWritableDatabase();
//mOpenHelper.onUpgrade(db, 0, DATABASE_VERSION);
// mOpenHelper.onUpgrade(db, 0, DATABASE_VERSION);
}
public void close() {
@ -72,41 +72,87 @@ public class T9DB {
if (iword.equals("")) {
throw new DBException(r.getString(R.string.add_word_blank));
}
//get int sequence
String seq = CharMap.getStringSequence(iword);
//add int sequence into num table
// get int sequence
String seq;
try {
seq = CharMap.getStringSequence(iword);
} catch (NullPointerException e) {
throw new DBException(r.getString(R.string.add_word_badchar));
}
// add int sequence into num table
ContentValues values = new ContentValues();
values.put(COLUMN_SEQ, seq);
//add word into word
// add word into word
values.put(COLUMN_WORD, iword);
values.put(COLUMN_FREQUENCY, 1);
try {
db.insertOrThrow(WORD_TABLE_NAME, null, values);
} catch (SQLiteConstraintException e) {
String msg = r.getString(R.string.add_word_exist1) + iword + r.getString(R.string.add_word_exist2);
String msg = r.getString(R.string.add_word_exist1) + iword
+ r.getString(R.string.add_word_exist2);
Log.w("T9DB.addWord", msg);
throw new DBException(msg);
}
}
public void incrementWord(int id) {
db.execSQL("UPDATE " + WORD_TABLE_NAME + " SET " + COLUMN_FREQUENCY + " = " +
COLUMN_FREQUENCY + "+ 1 WHERE " + COLUMN_ID + " = \"" + id + "\"");
// if id's freq is greater than X we should normalise those with the same seq
db.execSQL(
"UPDATE " + WORD_TABLE_NAME +
" SET " + COLUMN_FREQUENCY + " = " + COLUMN_FREQUENCY + "+ 1" +
" WHERE " + COLUMN_ID + " = \"" + id + "\"");
// if id's freq is greater than X we should normalise those with the
// same seq
}
public void updateWords(String is, ArrayList<String> stringList, ArrayList<Integer> intList, int capsMode){
stringList.clear();
intList.clear();
//String[] sa = packInts(stringToInts(is), true);
int islen = is.length();
String q = "SELECT " + COLUMN_ID + ", " + COLUMN_WORD +
" FROM " + WORD_TABLE_NAME +
protected String getWord(String is) {
String result = null;
String q =
"SELECT " + COLUMN_WORD + " FROM " + WORD_TABLE_NAME +
" WHERE " + COLUMN_SEQ + "=?" +
" ORDER BY " + COLUMN_FREQUENCY + " DESC";
Cursor cur = db.rawQuery(q, new String[] {is});
Cursor cur = db.rawQuery(q, new String[] { is });
int hits = 0;
for(cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
if (cur.moveToFirst()) {
result = cur.getString(0);
}
cur.close();
if (result != null) {
return result;
} else {
int islen = is.length();
char c = is.charAt(islen - 1);
c++;
q = "SELECT " + COLUMN_WORD + " FROM " + WORD_TABLE_NAME +
" WHERE " + COLUMN_SEQ + " >= '" + is + "1" + "' AND " + COLUMN_SEQ + " < '"
+ is.substring(0, islen - 1) + c + "'" +
" ORDER BY " + COLUMN_FREQUENCY + " DESC, " + COLUMN_SEQ + " ASC" +
" LIMIT " + (MAX_RESULTS - hits);
cur = db.rawQuery(q, null);
if (cur.moveToFirst()) {
result = cur.getString(1);
}
if (result == null) {
result = "";
}
cur.close();
}
return result;
}
public void updateWords(String is, ArrayList<String> stringList, ArrayList<Integer> intList,
int capsMode) {
stringList.clear();
intList.clear();
// String[] sa = packInts(stringToInts(is), true);
int islen = is.length();
String q =
"SELECT " + COLUMN_ID + ", " + COLUMN_WORD + " FROM " + WORD_TABLE_NAME +
" WHERE " + COLUMN_SEQ + "=?" +
" ORDER BY " + COLUMN_FREQUENCY + " DESC";
Cursor cur = db.rawQuery(q, new String[] { is });
int hits = 0;
for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
intList.add(cur.getInt(0));
stringList.add(cur.getString(1));
if (hits >= 15) {
@ -116,22 +162,24 @@ public class T9DB {
}
cur.close();
if (hits < 4) {
char c = is.charAt(islen-1);
char c = is.charAt(islen - 1);
c++;
// q = "SELECT " + COLUMN_WORD +", " + COLUMN_FREQUENCY +
// " FROM " + WORD_TABLE_NAME +
// " WHERE " + COLUMN_SEQ + " LIKE ?" +
// " ORDER BY " + COLUMN_SEQ + " ASC, " + COLUMN_FREQUENCY + " DESC;";
// c = db.rawQuery(q, new String[] {is + "_%"});
//above is hella slow below is gotta query fast
// q = "SELECT " + COLUMN_WORD +", " + COLUMN_FREQUENCY +
// " FROM " + WORD_TABLE_NAME +
// " WHERE " + COLUMN_SEQ + " LIKE ?" +
// " ORDER BY " + COLUMN_SEQ + " ASC, " + COLUMN_FREQUENCY +
// " DESC;";
// c = db.rawQuery(q, new String[] {is + "_%"});
// above is hella slow below is gotta query fast
q = "SELECT " + COLUMN_ID + ", " + COLUMN_WORD +
" FROM " + WORD_TABLE_NAME +
" WHERE " + COLUMN_SEQ + " >= '" + is + "1" + "' AND " + COLUMN_SEQ + " < '" + is.substring(0, islen-1) + c + "'" +
" ORDER BY " + COLUMN_FREQUENCY + " DESC, " + COLUMN_SEQ + " ASC" +
" WHERE " + COLUMN_SEQ + " >= '" + is + "1" + "' AND " + COLUMN_SEQ + " < '"
+ is.substring(0, islen - 1) + c + "'" +
" ORDER BY " + COLUMN_FREQUENCY + " DESC, " + COLUMN_SEQ + " ASC" +
" LIMIT " + (MAX_RESULTS - hits);
cur = db.rawQuery(q, null);
for(cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
intList.add(cur.getInt(0));
stringList.add(cur.getString(1));
if (hits >= 10) {
@ -141,11 +189,11 @@ public class T9DB {
}
cur.close();
}
//Log.d("T9DB.updateWords", "pre: " + stringList);
// Log.d("T9DB.updateWords", "pre: " + stringList);
if (capsMode == CAPS_OFF) {
return;
}
//Log.d("T9DB.updateWords", "filtering...");
// Log.d("T9DB.updateWords", "filtering...");
// filter list
Iterator<String> iter = stringList.iterator();
String word;
@ -160,8 +208,8 @@ public class T9DB {
if (wordtemp.equals(word)) {
index++;
continue;
} else if (stringList.contains(wordtemp)){
//remove this entry
} else if (stringList.contains(wordtemp)) {
// remove this entry
iter.remove();
removed = true;
} else {
@ -177,8 +225,8 @@ public class T9DB {
if (wordtemp.equals(word)) {
index++;
continue;
} else if (stringList.contains(wordtemp)){
//remove this entry
} else if (stringList.contains(wordtemp)) {
// remove this entry
iter.remove();
removed = true;
} else {
@ -196,21 +244,20 @@ public class T9DB {
return;
}
protected void updateWordsW(String is, ArrayList<String> stringList, ArrayList<Integer> intList,
ArrayList<Integer> freq){
protected void updateWordsW(String is, ArrayList<String> stringList,
ArrayList<Integer> intList, ArrayList<Integer> freq) {
stringList.clear();
intList.clear();
freq.clear();
//String[] sa = packInts(stringToInts(is), true);
// String[] sa = packInts(stringToInts(is), true);
int islen = is.length();
String q = "SELECT " + COLUMN_ID + ", " + COLUMN_WORD + ", " + COLUMN_FREQUENCY +
" FROM " + WORD_TABLE_NAME +
" WHERE " + COLUMN_SEQ + "=?" +
" ORDER BY " + COLUMN_FREQUENCY + " DESC";
Cursor cur = db.rawQuery(q, new String[] {is});
Cursor cur = db.rawQuery(q, new String[] { is });
int hits = 0;
for(cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
intList.add(cur.getInt(0));
stringList.add(cur.getString(1));
freq.add(cur.getInt(2));
@ -221,22 +268,24 @@ public class T9DB {
}
cur.close();
if (hits < 4) {
char c = is.charAt(islen-1);
char c = is.charAt(islen - 1);
c++;
// q = "SELECT " + COLUMN_WORD +", " + COLUMN_FREQUENCY +
// " FROM " + WORD_TABLE_NAME +
// " WHERE " + COLUMN_SEQ + " LIKE ?" +
// " ORDER BY " + COLUMN_SEQ + " ASC, " + COLUMN_FREQUENCY + " DESC;";
// c = db.rawQuery(q, new String[] {is + "_%"});
//above is hella slow
// q = "SELECT " + COLUMN_WORD +", " + COLUMN_FREQUENCY +
// " FROM " + WORD_TABLE_NAME +
// " WHERE " + COLUMN_SEQ + " LIKE ?" +
// " ORDER BY " + COLUMN_SEQ + " ASC, " + COLUMN_FREQUENCY +
// " DESC;";
// c = db.rawQuery(q, new String[] {is + "_%"});
// above is hella slow
q = "SELECT " + COLUMN_ID + ", " + COLUMN_WORD + ", " + COLUMN_FREQUENCY +
" FROM " + WORD_TABLE_NAME +
" WHERE " + COLUMN_SEQ + " >= '" + is + "' AND " + COLUMN_SEQ + " < '" + is.substring(0, islen-1) + c + "'" +
" WHERE " + COLUMN_SEQ + " >= '" + is + "' AND " + COLUMN_SEQ
+ " < '" + is.substring(0, islen - 1) + c + "'" +
" ORDER BY " + COLUMN_FREQUENCY + " DESC, " + COLUMN_SEQ + " ASC" +
" LIMIT " + (MAX_RESULTS - hits);
cur = db.rawQuery(q, null);
for(cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
intList.add(cur.getInt(0));
stringList.add(cur.getString(1));
freq.add(cur.getInt(2));
@ -250,35 +299,6 @@ public class T9DB {
return;
}
protected static int[] stringToInts(String s){
int[] il = new int[s.length()];
for (int x = 0; x < s.length(); x++){
il[x] = s.charAt(x) - 48; //lol hope this is ASCII all the time
}
return il;
}
protected static String[] packInts(int[] intseq, boolean stringArray){
int[] ia = packInts(intseq);
String[] sa = {Integer.toString(ia[0]), Integer.toString(ia[1])};
return sa;
}
protected static int[] packInts(int[] intseq){
int[] ia = {0, 0};
for (int x = 0; x < intseq.length; x++){
if (x < 8){
//packing 8 ints (<10) into 32bit int ... I hope...
ia[0] = ia[0] | (intseq[x] << x*4);
} else {
ia[1] = intseq[x] << (x % 8) * 4;
}
}
return ia;
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
@ -287,27 +307,27 @@ public class T9DB {
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + WORD_TABLE_NAME + " ("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COLUMN_SEQ + " TEXT, "
+ COLUMN_WORD + " TEXT UNIQUE, "
+ COLUMN_FREQUENCY + " INTEGER"
+ ")");
db.execSQL("CREATE TABLE " + WORD_TABLE_NAME + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_SEQ + " TEXT, " +
COLUMN_WORD + " TEXT UNIQUE, " +
COLUMN_FREQUENCY + " INTEGER" + ")");
db.execSQL("CREATE INDEX idx ON " + WORD_TABLE_NAME + "("
//+ COLUMN_NUMHIGH + ", " + COLUMN_NUMLOW + ")");
+ COLUMN_SEQ + " ASC, " + COLUMN_FREQUENCY + " DESC )");
db.execSQL("CREATE TRIGGER " + FREQ_TRIGGER_NAME + " AFTER UPDATE ON " + WORD_TABLE_NAME
+ " WHEN NEW." + COLUMN_FREQUENCY + " > " + FREQ_MAX
+ " BEGIN"
+ " UPDATE " + WORD_TABLE_NAME + " SET " + COLUMN_FREQUENCY
+ " = " + COLUMN_FREQUENCY + " / " + FREQ_DIV + " WHERE " + COLUMN_SEQ + " = NEW." + COLUMN_SEQ + ";"
+ " END;");
+ COLUMN_SEQ + " ASC, " + COLUMN_FREQUENCY + " DESC )");
db.execSQL("CREATE TRIGGER " + FREQ_TRIGGER_NAME +
" AFTER UPDATE ON " + WORD_TABLE_NAME +
" WHEN NEW." + COLUMN_FREQUENCY + " > " + FREQ_MAX +
" BEGIN" +
" UPDATE " + WORD_TABLE_NAME + " SET " + COLUMN_FREQUENCY + " = "
+ COLUMN_FREQUENCY + " / " + FREQ_DIV +
" WHERE " + COLUMN_SEQ + " = NEW." + COLUMN_SEQ + ";" +
" END;");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("T9DB", "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
Log.w("T9DB", "Upgrading database from version " + oldVersion + " to " + newVersion
+ ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + WORD_TABLE_NAME);
db.execSQL("DROP INDEX IF EXISTS idx");
onCreate(db);

File diff suppressed because it is too large Load diff

View file

@ -35,7 +35,7 @@ import android.preference.PreferenceActivity;
import android.util.Log;
public class TraditionalT9Settings extends PreferenceActivity implements
DialogInterface.OnCancelListener {
DialogInterface.OnCancelListener {
ProgressDialog pd = null;
AsyncTask<String, Integer, Reply> task = null;
@ -51,7 +51,7 @@ public class TraditionalT9Settings extends PreferenceActivity implements
public boolean status;
public String message;
protected Reply(){
protected Reply() {
this.status = true;
this.message = "None";
}
@ -72,8 +72,11 @@ public class TraditionalT9Settings extends PreferenceActivity implements
}
private class LoadDictTask extends AsyncTask<String, Integer, Reply> {
/** The system calls this to perform work in a worker thread and
* delivers it the parameters given to AsyncTask.execute() */
/**
* The system calls this to perform work in a worker thread and delivers
* it the parameters given to AsyncTask.execute()
*/
@Override
protected Reply doInBackground(String... mode) {
Reply reply = new Reply();
SQLiteDatabase db;
@ -83,12 +86,12 @@ public class TraditionalT9Settings extends PreferenceActivity implements
long last = 0;
File backupfile = new File(Environment.getExternalStorageDirectory(), backupdir);
if (mode[0].equals("backup")){
//using external backup
if (mode[0].equals("backup")) {
// using external backup
backupfile = new File(backupfile, backupname);
fsize = backupfile.length();
} else {
//using asset:
// using asset:
AssetFileDescriptor descriptor;
try {
descriptor = getAssets().openFd(dictname);
@ -103,7 +106,6 @@ public class TraditionalT9Settings extends PreferenceActivity implements
}
}
db.setLockingEnabled(false);
InsertHelper wordhelp = new InsertHelper(db, T9DB.WORD_TABLE_NAME);
@ -126,18 +128,18 @@ public class TraditionalT9Settings extends PreferenceActivity implements
BufferedReader br;
InputStream dictstream = null;
if (mode[0].equals("backup")){
if (mode[0].equals("backup")) {
try {
dictstream = new FileInputStream(backupfile);
dictstream = new FileInputStream(backupfile);
} catch (FileNotFoundException e) {
reply.status = false;
reply.message = "Backup file not found: " + e.getMessage();
db.close();
closeStream(dictstream, reply); // this is silly but it stops IDE nagging at me.
closeStream(dictstream, reply); // this is silly but it
// stops IDE nagging at me.
return reply;
}
}
else {
} else {
try {
dictstream = getAssets().open(dictname);
} catch (IOException e) {
@ -183,8 +185,8 @@ public class TraditionalT9Settings extends PreferenceActivity implements
try {
while (word != null) {
if (isCancelled()) {
// this is useless because of dumb android bug that doesn't
// call onCancelled after this method finishes.
// this is useless because of dumb android bug that
// doesn't call onCancelled after this method finishes.
reply.status = false;
reply.message = "User cancelled.";
break;
@ -193,7 +195,7 @@ public class TraditionalT9Settings extends PreferenceActivity implements
ws = word.split(" ");
word = ws[0];
try {
freq = Integer.parseInt(ws[1]);
freq = Integer.parseInt(ws[1]);
} catch (NumberFormatException e) {
reply.status = false;
reply.message = "Number error.";
@ -214,7 +216,7 @@ public class TraditionalT9Settings extends PreferenceActivity implements
return reply;
}
pos += wordlen;
try{
try {
seq = CharMap.getStringSequence(word);
} catch (NullPointerException e) {
reply.status = false;
@ -231,11 +233,12 @@ public class TraditionalT9Settings extends PreferenceActivity implements
wordhelp.bind(freqColumn, freq);
wordhelp.execute();
//System.out.println("Progress: " + pos + " Last: " + last + " fsize: " + fsize);
// System.out.println("Progress: " + pos + " Last: " + last
// + " fsize: " + fsize);
if ((pos - last) > 4096) {
// Log.d("doInBackground", "line: " + linecount);
// Log.d("doInBackground", "word: " + word);
publishProgress((int)((float)pos/fsize*10000));
// Log.d("doInBackground", "line: " + linecount);
// Log.d("doInBackground", "word: " + word);
publishProgress((int) ((float) pos / fsize * 10000));
last = pos;
}
try {
@ -257,47 +260,58 @@ public class TraditionalT9Settings extends PreferenceActivity implements
wordhelp.close();
}
endnow = SystemClock.uptimeMillis();
Log.d("TIMING", "Excution time: "+(endnow-startnow)+" ms");
Log.d("TIMING", "Excution time: " + (endnow - startnow) + " ms");
Log.d("doInBackground", "line: " + linecount);
db.close();
closeStream(dictstream, reply);
return reply;
}
@Override
protected void onProgressUpdate(Integer... progress) {
if (pd.isShowing()) {
pd.setProgress(progress[0]);
}
}
}
protected void onCancelled() {
// Pointless callback. Thanks android.
}
@Override
protected void onCancelled() {
// Pointless callback. Thanks android.
}
/** The system calls this to perform work in the UI thread and delivers
* the result from doInBackground() */
/**
* The system calls this to perform work in the UI thread and delivers
* the result from doInBackground()
*/
@Override
protected void onPostExecute(Reply result) {
if (pd == null){
//Log.d("onPostExecute", "pd");
if (pd == null) {
// Log.d("onPostExecute", "pd");
} else {
//Log.d("onPostExecute", "pd");
pd.dismiss();
// Log.d("onPostExecute", "pd");
if (pd.isShowing()) {
pd.dismiss();
}
}
if (result == null){
//bad thing happened
if (result == null) {
// bad thing happened
Log.e("onPostExecute", "Bad things happen?");
} else {
Log.d("onPostExecute", "Result: " + result.status + " " + result.message);
if (!result.status) {
showErrorDialog(caller.getResources().getString(R.string.pref_restore_title), result.message);
showErrorDialog(caller.getResources().getString(R.string.pref_restore_title),
result.message);
}
}
}
}
private class DumpDictTask extends AsyncTask<String, Integer, Reply> {
/** The system calls this to perform work in a worker thread and
* delivers it the parameters given to AsyncTask.execute() */
/**
* The system calls this to perform work in a worker thread and delivers
* it the parameters given to AsyncTask.execute()
*/
@Override
protected Reply doInBackground(String... ignore) {
Reply reply = new Reply();
SQLiteDatabase db;
@ -306,7 +320,8 @@ public class TraditionalT9Settings extends PreferenceActivity implements
int current = 0;
int pos = 0;
int last = 0;
File backupfile = new File(new File(Environment.getExternalStorageDirectory(), backupdir), backupname);
File backupfile = new File(new File(Environment.getExternalStorageDirectory(),
backupdir), backupname);
db.setLockingEnabled(false);
@ -320,7 +335,8 @@ public class TraditionalT9Settings extends PreferenceActivity implements
reply.status = false;
reply.message = "Backup file error: " + e.getMessage();
db.close();
closeStream(dictstream, reply); // this is silly but it stops IDE nagging at me.
closeStream(dictstream, reply); // this is silly but it stops
// IDE nagging at me.
return reply;
}
@ -341,19 +357,19 @@ public class TraditionalT9Settings extends PreferenceActivity implements
Cursor cur = db.rawQuery(q, null);
cur.moveToFirst();
entries = cur.getInt(0);
//pd.setMax((int)entries);
// pd.setMax((int)entries);
cur.close();
while (current < entries) {
q = "SELECT " + T9DB.COLUMN_ID + ", " + T9DB.COLUMN_WORD + ", " + T9DB.COLUMN_FREQUENCY +
" FROM " + T9DB.WORD_TABLE_NAME +
" WHERE " + T9DB.COLUMN_ID + ">" + current +
" ORDER BY " + T9DB.COLUMN_ID +
" LIMIT " + BACKUP_Q_LIMIT;
q = "SELECT " + T9DB.COLUMN_ID + ", " + T9DB.COLUMN_WORD + ", "
+ T9DB.COLUMN_FREQUENCY + " FROM " + T9DB.WORD_TABLE_NAME + " WHERE "
+ T9DB.COLUMN_ID + ">" + current + " ORDER BY " + T9DB.COLUMN_ID + " LIMIT "
+ BACKUP_Q_LIMIT;
cur = db.rawQuery(q, null);
for(cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
if (isCancelled()) {
// this is useless because of dumb android bug that doesn't
// this is useless because of dumb android bug that
// doesn't
// call onCancelled after this method finishes.
reply.status = false;
reply.message = "User cancelled.";
@ -375,7 +391,7 @@ public class TraditionalT9Settings extends PreferenceActivity implements
return reply; // why complain? I closed the stream above
}
if ((pos - last) > 80) {
publishProgress((int)((float)current/entries*10000));
publishProgress((int) ((float) current / entries * 10000));
last = current;
}
}
@ -384,7 +400,7 @@ public class TraditionalT9Settings extends PreferenceActivity implements
publishProgress(100);
endnow = SystemClock.uptimeMillis();
Log.d("TIMING", "Excution time: "+(endnow-startnow)+" ms");
Log.d("TIMING", "Excution time: " + (endnow - startnow) + " ms");
Log.d("doInBackground", "entries: " + entries + " last: " + pos);
db.close();
try {
@ -396,40 +412,49 @@ public class TraditionalT9Settings extends PreferenceActivity implements
return reply;
}
@Override
protected void onProgressUpdate(Integer... progress) {
if (pd.isShowing()) {
pd.setProgress(progress[0]);
}
}
}
protected void onCancelled() {
// Pointless callback. Thanks android.
}
@Override
protected void onCancelled() {
// Pointless callback. Thanks android.
}
/** The system calls this to perform work in the UI thread and delivers
* the result from doInBackground() */
/**
* The system calls this to perform work in the UI thread and delivers
* the result from doInBackground()
*/
@Override
protected void onPostExecute(Reply result) {
if (pd == null){
//Log.d("onPostExecute", "pd");
if (pd == null) {
// Log.d("onPostExecute", "pd");
} else {
//Log.d("onPostExecute", "pd");
// Log.d("onPostExecute", "pd");
pd.dismiss();
}
if (result == null){
//bad thing happened
if (result == null) {
// bad thing happened
Log.e("onPostExecute", "Bad things happen?");
} else {
Log.d("onPostExecute", "Result: " + result.status + " " + result.message);
if (!result.status) {
showErrorDialog(caller.getResources().getString(R.string.pref_backup_title), result.message);
showErrorDialog(caller.getResources().getString(R.string.pref_backup_title),
result.message);
}
}
}
}
private class NukeDictTask extends AsyncTask<String, Integer, Reply> {
/** The system calls this to perform work in a worker thread and
* delivers it the parameters given to AsyncTask.execute() */
/**
* The system calls this to perform work in a worker thread and delivers
* it the parameters given to AsyncTask.execute()
*/
@Override
protected Reply doInBackground(String... ignore) {
Reply reply = new Reply();
Log.d("doInBakground", "Nuking dict...");
@ -439,30 +464,35 @@ public class TraditionalT9Settings extends PreferenceActivity implements
t9db.nuke();
endnow = SystemClock.uptimeMillis();
Log.d("TIMING", "Excution time: "+(endnow-startnow)+" ms");
Log.d("TIMING", "Excution time: " + (endnow - startnow) + " ms");
return reply;
}
protected void onCancelled() {
// Pointless callback. Thanks android.
}
@Override
protected void onCancelled() {
// Pointless callback. Thanks android.
}
/** The system calls this to perform work in the UI thread and delivers
* the result from doInBackground() */
/**
* The system calls this to perform work in the UI thread and delivers
* the result from doInBackground()
*/
@Override
protected void onPostExecute(Reply result) {
if (pd == null){
//Log.d("onPostExecute", "pd");
if (pd == null) {
// Log.d("onPostExecute", "pd");
} else {
//Log.d("onPostExecute", "pd");
// Log.d("onPostExecute", "pd");
pd.dismiss();
}
if (result == null){
//bad thing happened
if (result == null) {
// bad thing happened
Log.e("onPostExecute", "Bad things happen?");
} else {
Log.d("onPostExecute", "Result: " + result.status + " " + result.message);
if (!result.status) {
showErrorDialog(caller.getResources().getString(R.string.pref_nuke_title), result.message);
showErrorDialog(caller.getResources().getString(R.string.pref_nuke_title),
result.message);
}
}
}
@ -472,7 +502,7 @@ public class TraditionalT9Settings extends PreferenceActivity implements
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
Preference button = (Preference)getPreferenceManager().findPreference("loaddict");
Preference button = getPreferenceManager().findPreference("loaddict");
if (button != null) {
button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
@ -482,7 +512,7 @@ public class TraditionalT9Settings extends PreferenceActivity implements
}
});
}
button = (Preference)getPreferenceManager().findPreference("nukedict");
button = getPreferenceManager().findPreference("nukedict");
if (button != null) {
button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
@ -493,7 +523,7 @@ public class TraditionalT9Settings extends PreferenceActivity implements
});
}
button = (Preference)getPreferenceManager().findPreference("backupdict");
button = getPreferenceManager().findPreference("backupdict");
if (button != null) {
button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
@ -504,7 +534,7 @@ public class TraditionalT9Settings extends PreferenceActivity implements
});
}
button = (Preference)getPreferenceManager().findPreference("restoredict");
button = getPreferenceManager().findPreference("restoredict");
if (button != null) {
button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
@ -515,7 +545,7 @@ public class TraditionalT9Settings extends PreferenceActivity implements
});
}
button = (Preference)getPreferenceManager().findPreference("querytest");
button = getPreferenceManager().findPreference("querytest");
if (button != null) {
button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
@ -533,7 +563,7 @@ public class TraditionalT9Settings extends PreferenceActivity implements
preloader(R.string.pref_loadingdict, "");
}
private void preloader(int msgid, String mode){
private void preloader(int msgid, String mode) {
pd = new ProgressDialog(this);
pd.setMessage(getResources().getString(msgid));
pd.setOnCancelListener(this);
@ -548,7 +578,7 @@ public class TraditionalT9Settings extends PreferenceActivity implements
pd = new ProgressDialog(this);
pd.setMessage(getResources().getString(msgid));
pd.setOnCancelListener(this);
//pd.setProgressNumberFormat(null); Why added in API11...
// pd.setProgressNumberFormat(null); Why added in API11...
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setMax(10000);
pd.show();
@ -568,18 +598,18 @@ public class TraditionalT9Settings extends PreferenceActivity implements
private void nukeDict() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.pref_nuke_warn)
.setTitle(R.string.pref_nuke_title)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
prenuke(R.string.pref_nukingdict);
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
builder.setMessage(R.string.pref_nuke_warn).setTitle(R.string.pref_nuke_title)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
prenuke(R.string.pref_nukingdict);
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
@ -590,7 +620,7 @@ public class TraditionalT9Settings extends PreferenceActivity implements
File saveloc = new File(Environment.getExternalStorageDirectory(), backupdir);
saveloc.mkdirs();
if (!saveloc.canWrite()){
if (!saveloc.canWrite()) {
Log.e("backupDict", "can't write : " + saveloc.getAbsolutePath());
showErrorDialogID(builder, R.string.pref_backup_title, R.string.pref_backup_noext);
return;
@ -598,18 +628,18 @@ public class TraditionalT9Settings extends PreferenceActivity implements
saveloc = new File(saveloc, backupname);
if (saveloc.exists()) {
builder.setMessage(R.string.pref_backup_warn)
.setTitle(R.string.pref_backup_title)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
predumper(R.string.pref_savingbackup);
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
builder.setMessage(R.string.pref_backup_warn).setTitle(R.string.pref_backup_title)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
predumper(R.string.pref_savingbackup);
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
} else {
@ -625,52 +655,59 @@ public class TraditionalT9Settings extends PreferenceActivity implements
}
private void showErrorDialog(AlertDialog.Builder builder, String title, String msg) {
builder.setMessage(msg)
.setTitle(title)
.setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
builder.setMessage(msg).setTitle(title)
.setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
private void showErrorDialogID(AlertDialog.Builder builder, int titleid, int msgid) {
builder.setMessage(msgid)
.setTitle(titleid)
.setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
builder.setMessage(msgid).setTitle(titleid)
.setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
private void restoreDict() {
// Environment.MEDIA_MOUNTED_READ_ONLY;
// Environment.MEDIA_MOUNTED;
// Environment.MEDIA_MOUNTED_READ_ONLY;
// Environment.MEDIA_MOUNTED;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(Environment.getExternalStorageState()) ||
Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
if ((new File(new File(Environment.getExternalStorageDirectory(), backupdir), backupname)).exists()) {
Resources res = getResources();
builder.setMessage(res.getString(R.string.pref_restore_warn, res.getString(R.string.pref_nukedict)))
.setTitle(R.string.pref_restore_title)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
preloader(R.string.pref_loadingbackup, "backup");
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(Environment.getExternalStorageState())
|| Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
if ((new File(new File(Environment.getExternalStorageDirectory(), backupdir),
backupname)).exists()) {
Resources res = getResources();
builder
.setMessage(
res.getString(R.string.pref_restore_warn,
res.getString(R.string.pref_nukedict)))
.setTitle(R.string.pref_restore_title)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
preloader(R.string.pref_loadingbackup, "backup");
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
} else {
showErrorDialogID(builder, R.string.pref_restore_title, R.string.pref_restore_nofile);
showErrorDialogID(builder, R.string.pref_restore_title,
R.string.pref_restore_nofile);
}
} else {
showErrorDialogID(builder, R.string.pref_restore_title, R.string.pref_restore_noext);
@ -688,23 +725,23 @@ public class TraditionalT9Settings extends PreferenceActivity implements
T9DB tdb = new T9DB(this);
tdb.init();
Log.d("queryTestDebug", "Testing...");
tdb.updateWords("123", words, ids, 0);
Log.d("queryTestDebug", "123->" + words.toString());
Log.d("queryTestDebug", "269->");
tdb.updateWords("269", words, ids, 0);
Iterator<String> i = words.iterator();
while (i.hasNext()){
Log.d("queryTestDebug", "word: " + i.next());
}
tdb.updateWords("123", words, ids, 0);
Log.d("queryTestDebug", "123->" + words.toString());
Log.d("queryTestDebug", "269->");
tdb.updateWords("269", words, ids, 0);
Iterator<String> i = words.iterator();
while (i.hasNext()) {
Log.d("queryTestDebug", "word: " + i.next());
}
Log.d("queryTestDebug", "228->");
tdb.updateWords("228", words, ids, 0);
i = words.iterator();
while (i.hasNext()){
Log.d("queryTestDebug", "word: " + i.next());
}
Log.d("queryTestDebug", "228->");
tdb.updateWords("228", words, ids, 0);
i = words.iterator();
while (i.hasNext()) {
Log.d("queryTestDebug", "word: " + i.next());
}
endnow = SystemClock.uptimeMillis();
Log.d("TIMING", "Excution time: "+(endnow-startnow)+" ms");
Log.d("TIMING", "Excution time: " + (endnow - startnow) + " ms");
tdb.close();
}
@ -716,16 +753,16 @@ public class TraditionalT9Settings extends PreferenceActivity implements
T9DB tdb = new T9DB(this);
tdb.init();
// tdb.getWords("123").iterator();
// tdb.getWords("269").iterator();
// tdb.getWords("228").iterator();
// tdb.getWords("24371").iterator();
// tdb.getWords("22376284").iterator();
// tdb.getWords("68372667367283").iterator();
// tdb.getWords("22637").iterator();
// tdb.getWords("123").iterator();
// tdb.getWords("269").iterator();
// tdb.getWords("228").iterator();
// tdb.getWords("24371").iterator();
// tdb.getWords("22376284").iterator();
// tdb.getWords("68372667367283").iterator();
// tdb.getWords("22637").iterator();
endnow = SystemClock.uptimeMillis();
Log.d("TIMING", "Excution time: "+(endnow-startnow)+" ms");
Log.d("TIMING", "Excution time: " + (endnow - startnow) + " ms");
tdb.close();
}
@ -747,25 +784,25 @@ public class TraditionalT9Settings extends PreferenceActivity implements
tdb.incrementWord(ids.get(0));
}
for (int x=0; x<size; x++){
for (int x = 0; x < size; x++) {
tdb.incrementWord(ids.get(x));
}
endnow = SystemClock.uptimeMillis();
Log.d("TIMING", "Excution time: "+(endnow-startnow)+" ms");
Log.d("TIMING", "Excution time: " + (endnow - startnow) + " ms");
ArrayList<Integer> freqs = new ArrayList<Integer>(8);
tdb.updateWordsW("222", words, ids, freqs);
Log.d("VALUES", "...");
size = freqs.size();
for (int x = 0; x < size; x++){
Log.d("VALUES", "Word: " + words.get(x) + " id: " + ids.get(x) + " freq: " + freqs.get(x));
for (int x = 0; x < size; x++) {
Log.d("VALUES",
"Word: " + words.get(x) + " id: " + ids.get(x) + " freq: " + freqs.get(x));
}
Log.d("queryTestSingle", "done.");
tdb.close();
}
@Override
public void onCancel(DialogInterface dint) {
task.cancel(false);