Double Tapping on the textView - android

Eg.,
Welcome to Android World.
Now when I double tap on the space between "Welcome" and "to", the String from "to" to "World" should come in the next line.
That is,
Welcome <\n>
to Android World.
Similarly, when I double tap the space between "to" and "Android", it should be,
Welcome <\n>
to <\n>
Android World.
The first time it works, but the next time it force stops.
I don't know where I am going wrong. Probably it is not getting the onTouchListener properly.
Need Help.
linear_layout = (LinearLayout) findViewById(R.id.linearLayout);
mTextView = new TextView[10];
mTextView[i] = new TextView(this);
mTextView[i].setText("Hello Android Text View");
linear_layout.addView(mTextView[i]);
mTextView[i].setOnTouchListener(this);
mGestureDetector = new GestureDetector(new GestureDetector.SimpleOnGestureListener() {
#Override
public void onLongPress(MotionEvent e) {
Log.d(TAG, "Long Press event");
Toast.makeText(getBaseContext(), "Long Press", Toast.LENGTH_LONG).show();
}
#Override
public boolean onDoubleTap(MotionEvent e) {
Log.d(TAG, "Double Tap event");
Toast.makeText(getBaseContext(), "Double Tap", Toast.LENGTH_LONG).show();
Log.i("Tag", "------------------------------ " + e.getX() + " " + e.getY());
Layout layout = ((TextView) view).getLayout();
int x = (int)e.getX();
int y = (int)e.getY();
if (layout!=null){
line = layout.getLineForVertical(y);
characterOffset = layout.getOffsetForHorizontal(line, x);
Log.i("index", ""+characterOffset);
}
String text = mTextView[i].getText().toString();
char[] char_txt = text.toCharArray();
int ascii_val = (int)text.charAt(characterOffset);
String rem_txt = "";
//if(ascii_val == 32) {
int n=characterOffset;
while(n < char_txt.length){
rem_txt += char_txt[n];
n++;
}
//}
i++;
String before_tap_txt = text.subSequence(0, characterOffset).toString();
mTextView[i-1].setText(before_tap_txt);
mTextView[i] = new TextView(GestureDetecterExampleActivity.this);
mTextView[i].setText(rem_txt);
linear_layout.addView(mTextView[i]);
return true;
}
#Override
public boolean onDown(MotionEvent e) {
return true;
}
});
mGestureDetector.setIsLongpressEnabled(true);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
view = v;
return mGestureDetector.onTouchEvent(event);
}

Log.d(TAG, "Double Tap event");
/* Toast.makeText(getBaseContext(), "Double Tap",
Toast.LENGTH_LONG).show();*/
Log.i("Tag",
"------------------------------ " + e.getX()
+ " " + e.getY());
Layout layout = ((TextView) view).getLayout();
int x = (int) e.getX();
int y = (int) e.getY();
if (layout != null) {
line = layout.getLineForVertical(y);
characterOffset = layout.getOffsetForHorizontal(
line, x);
Log.i("index", "" + characterOffset);
}
String text = mTextView[i].getText().toString();
char[] char_txt = text.toCharArray();
int ascii_val = (int) text.charAt(characterOffset);
String rem_txt = "";
if(ascii_val == 32) {
int n = characterOffset;
while (n < char_txt.length) {
rem_txt += char_txt[n];
n++;
}
// }
i++;
String before_tap_txt = text.subSequence(0,
characterOffset).toString();
mTextView[i - 1].setText(before_tap_txt.trim());
mTextView[i] = new TextView(
DoubleTapActivity.this);
mTextView[i].setText(rem_txt.trim());
mTextView[i].setOnTouchListener(DoubleTapActivity.this);
linear_layout.addView(mTextView[i]);
return true;
}
else
{
Toast.makeText(DoubleTapActivity.this, "" + text.charAt(characterOffset), Toast
.LENGTH_SHORT).show();
}
return false;
Place this code in ur double tap method.
comment if you need any help.

Related

Peak between different Peak values

Am trying to get these two peaks once I read from my text file. I have defined two string to compare two value in order to find the peak, but I think my if(y_0>MP) statement is not correct one to find the two peak. What should I do please.
//Read data.
Recall = (Button) findViewById(R.id.Recall);
Recall.setOnClickListener(new View.OnClickListener() {
StringBuilder stringBuilder;
#Override
public void onClick(View v) {
//readTextFile(this, R.raw.books);
stringBuilder = new StringBuilder();
String line;
try {
FileInputStream fIn = new FileInputStream(file);
BufferedReader bufferedreader = new BufferedReader(new
InputStreamReader(fIn));
while ((line = bufferedreader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(" ");
stringBuilder.length();
}
bufferedreader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String a;
a = String.valueOf(stringBuilder);
String dataArray[];
int t;
dataArray = a.split(" ");
int MP = 0;
for (t = 1; t < dataArray.length - 1; t++) {
float y_0 = Float.valueOf(dataArray[t]);
float y_1 = Float.valueOf(dataArray[t + 1]);
float y_2 = Float.valueOf(dataArray[t - 1]);
float left = y_0 - y_2;
float right = y_1 - y_0;
if (left > 0 && right < 0) {
if (y_0 > MP) {
MP = (int) y_0;
} else {
MP = (int) y_0;
}
Toast.makeText(getApplicationContext(), "Number of peaks
founds\n: " + MP, Toast.LENGTH_SHORT).show();
}
}
DataAlert alert = new DataAlert();
alert.show(getFragmentManager(), "DataAlert");
}
});
Your suspicions about the if (y_0 > MP) line are correct. If you want to make a toast showing the number of peaks found, then you either need to keep a list of the peaks, or a counter, and add to it every time a peak is found. Then, after the for-loop has finished searching for peaks, you would make a toast saying how many peaks were found.
List<Integer> peaks = new ArrayList<>();
for (t = 1; t < dataArray.length - 1; t++) {
float y_0 = Float.valueOf(dataArray[t]);
float y_1 = Float.valueOf(dataArray[t + 1]);
float y_2 = Float.valueOf(dataArray[t - 1]);
float left = y_0 - y_2;
float right = y_1 - y_0;
if (left > 0 && right < 0)
peaks.add(t);
}
Toast.makeText(getApplicationContext(), "Number of peaks founds\n: " + peaks.size(), Toast.LENGTH_SHORT).show();
for (Integer peak : peaks) {
float value = Float.valueOf(dataArray[peak]);
Toast.makeText(getApplicationContext(), "Peak of height " + value + " found at index " + peak, Toast.LENGTH_SHORT).show();
}
For future reference, this section of code
if (y_0 > MP) {
MP = (int) y_0;
} else {
MP = (int) y_0;
}
Is equivalent to this:
MP = (int) y_0;
You assign MP = (int) y_0 regardless of whether the if statement is true or false.

Android Custom Keyboard stuck When Swapping to/from Another Keyboard

I'm developing a custom keyboard for Android that will store login credentials in a local database (plan is to encrypt the DB after the thing works flawlessly).
The keyboard has a basic layout with a KeyboardView at the bottom and a 'Switch Keyboard' button at the top-right corner.
Everything works fine except that when i click the switch button, things start to fail.
Scenario:
1) My keyboard is active and everything is fine. Keyboard visibility is managed by the system.
2) I click the switch button, my keyboard is closed and previously enabled keyboard is displayed.
3) Now i open the Keyboard Chooser through Notification Tray and re-enable my custom keyboard.
My keyboard is set as default, but there's no keyboard on the screen. when i touch the bottom half of screen area where keyboard appears, the characters are being typed (yes, my keyboard is there but is invisible!).
I press the Back key on my phone and the system doesn't close the keyboard and it's stuck there.
I press the Home key and the keyboard becomes visible for a few milliseconds, is closed by the system and i'm sent to the Home Screen.
I've tried waiting for the keyboard to appear, etc. and also tried the app on 3 other phones from different make. Also, i'm developing the app for Lollipop (API 21 and higher).
Here's the code:
1) InputMethodService:
public class HomlesInputService extends InputMethodService implements KeyboardView.OnKeyboardActionListener {
CustomKeyboardView kv;
Keyboard qwertyKeyboard, symbolKeyboard;
Boolean caps;
private String myPwd, myUid;
SharedPreferences mPrefs;
SharedPreferences.Editor mEdit;
Boolean isPassword, isUid, uidFilled, pwdFilled;
Vibrator vibrator;
View keyboard;
EditorInfo sEditorInfo;
SQLiteDatabase db;
InputMethodManager imm;
IBinder token;
String defImeId;
public static final int SYM_KEYBOARD = -10;
public static final int GO_BUTTON = -4;
public static final double GO_BUTTON_ASPECT_RATIO = 1.88;
public static final double NEXT_BUTTON_ASPECT_RATIO = 1;
public HomlesInputService() {
}
#Override
public void onCreate() {
super.onCreate();
mPrefs = getSharedPreferences(Constants.APP_PREFS, MODE_PRIVATE);
mEdit = mPrefs.edit();
//storing ime id in prefs
String myId = Settings.Secure.getString(getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD);
mEdit.putString(Constants.MY_IME_ID, myId);
mEdit.commit();
imm = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
defImeId = mPrefs.getString(Constants.DEFAULT_KEYBOARD, null); //the id of previous IME stored in preferences (found correct in debugging)
qwertyKeyboard = new Keyboard(this, R.xml.qwerty_keyboard_layout);
symbolKeyboard = new Keyboard(this, R.xml.symbol_keyboard_layout);
db = openOrCreateDatabase(DbConstants.DATABASE_NAME, MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS " + DbConstants.TABLE_NAME + "("
+ DbConstants.APP_ID + "," + DbConstants.UID_VALUE + "," + DbConstants.PWD_VALUE + ")");
vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
}
#Override
public View onCreateInputView() {
keyboard = getLayoutInflater().inflate(R.layout.my_custom_keyboard, null);
ImageView ivRevertKeyboard = (ImageView) keyboard.findViewById(R.id.ivRevertKeyboard); //this button is used to switch to previous IME
token = this.getWindow().getWindow().getAttributes().token;
if (defImeId != null) {
ivRevertKeyboard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
vibrator.vibrate(Constants.VIBRATE_TIME_MEDIUM);
try {
imm.hideSoftInputFromInputMethod(token, 0);
imm.setInputMethod(token, defImeId);
} catch (Throwable t) { // java.lang.NoSuchMethodError if API_level<11
t.printStackTrace();
}
}
});
} else {
ivRevertKeyboard.setVisibility(View.GONE);
}
kv = (CustomKeyboardView) keyboard.findViewById(R.id.keyboard);
kv.setKeyboard(qwertyKeyboard);
kv.setOnKeyboardActionListener(this);
caps = false;
myPwd = "";
myUid = "";
isPassword = false;
return keyboard;
}
#Override
public void onStartInputView(EditorInfo info, boolean restarting) {
sEditorInfo = info;
uidFilled = false;
pwdFilled = false;
if (info.inputType == 129) {
isPassword = true;
} else {
isPassword = false;
}
CharSequence CHARbeforeCursor = getCurrentInputConnection().getTextBeforeCursor(999, 0);
CharSequence CHARafterCursor = getCurrentInputConnection().getTextAfterCursor(999, 0);
if (CHARbeforeCursor != null && CHARafterCursor != null) {
String beforeCursor = CHARbeforeCursor.toString();
String afterCursor = CHARafterCursor.toString();
if (isPassword) {
myPwd = beforeCursor + afterCursor;
} else {
myUid = beforeCursor + afterCursor;
}
}
setGoButton();
}
private void setGoButton() {
List<Keyboard.Key> keys = kv.getKeyboard().getKeys();
Drawable dr;
int rowHeight, goBtWidth = 0, nextBtWidth = 0;
rowHeight = Utils.dpToPx(40, getApplicationContext());
goBtWidth = Integer.parseInt("" + Math.round(rowHeight * GO_BUTTON_ASPECT_RATIO));
nextBtWidth = Integer.parseInt("" + Math.round(rowHeight * NEXT_BUTTON_ASPECT_RATIO));
for (int i = 0; i < keys.size(); i++) {
Keyboard.Key key = keys.get(i);
int code = key.codes[0];
if (code == GO_BUTTON) {
if (isPassword) {
key.width = goBtWidth;
dr = getResources().getDrawable(R.drawable.keyboard_save_and_go, getApplicationContext().getTheme());
} else {
key.width = nextBtWidth;
dr = getResources().getDrawable(R.drawable.keyboard_next, getApplicationContext().getTheme());
}
key.icon = dr;
}
}
}
#Override
public void onPress(int primaryCode) {
vibrator.vibrate(Constants.VIBRATE_TIME_SHORT);
switch (primaryCode) {
case Keyboard.KEYCODE_DELETE:
kv.setPreviewEnabled(false);
break;
case Keyboard.KEYCODE_SHIFT:
kv.setPreviewEnabled(false);
break;
case Keyboard.KEYCODE_DONE:
kv.setPreviewEnabled(false);
break;
case SYM_KEYBOARD:
kv.setPreviewEnabled(false);
break;
case 32:
kv.setPreviewEnabled(false);
break;
default:
kv.setPreviewEnabled(true);
}
}
#Override
public void onRelease(int i) {
}
#Override
public void onKey(int primaryCode, int[] ints) {
InputConnection conn = getCurrentInputConnection();
uidFilled = mPrefs.getBoolean(Constants.UID_FILLED, false);
pwdFilled = mPrefs.getBoolean(Constants.PWD_FILLED, false);
switch (primaryCode) {
case Keyboard.KEYCODE_DELETE:
conn.deleteSurroundingText(1, 0);
if (isPassword) {
if (myPwd.length() > 0) {
String beforeCursor = conn.getTextBeforeCursor(myPwd.length(), 0).toString();
beforeCursor = beforeCursor.substring(0, beforeCursor.length());
String afterCursor = conn.getTextAfterCursor(myPwd.length(), 0).toString();
myPwd = beforeCursor + afterCursor;
if (uidFilled && pwdFilled) {
mEdit.putString(Constants.EDIT_NEW_PWD, myPwd);
} else {
mEdit.putString(Constants.NEW_PWD, myPwd);
}
mEdit.commit();
Log.d("##Pwd saved", "" + mPrefs.getString(Constants.NEW_PWD, ""));
}
} else {
if (myUid.length() > 0) {
String beforeCursor = conn.getTextBeforeCursor(myUid.length(), 0).toString();
beforeCursor = beforeCursor.substring(0, beforeCursor.length());
String afterCursor = conn.getTextAfterCursor(myUid.length(), 0).toString();
myUid = beforeCursor + afterCursor;
if (uidFilled && pwdFilled) {
mEdit.putString(Constants.EDIT_NEW_UID, myUid);
} else {
mEdit.putString(Constants.NEW_UID, myUid);
}
mEdit.commit();
Log.d("##Uid saved", "" + mPrefs.getString(Constants.NEW_UID, ""));
}
}
break;
case Keyboard.KEYCODE_SHIFT:
caps = !caps;
kv.setShifted(caps);
kv.invalidateAllKeys();
break;
case Keyboard.KEYCODE_DONE:
switch (sEditorInfo.imeOptions & (EditorInfo.IME_MASK_ACTION | EditorInfo.IME_FLAG_NO_ENTER_ACTION)) {
case EditorInfo.IME_ACTION_GO:
conn.performEditorAction(EditorInfo.IME_ACTION_GO);
break;
case EditorInfo.IME_ACTION_NEXT:
conn.performEditorAction(EditorInfo.IME_ACTION_NEXT);
break;
case EditorInfo.IME_ACTION_SEARCH:
conn.performEditorAction(EditorInfo.IME_ACTION_SEARCH);
break;
case EditorInfo.IME_ACTION_SEND:
conn.performEditorAction(EditorInfo.IME_ACTION_SEND);
break;
case EditorInfo.IME_ACTION_DONE:
saveCredentialsToDb();
conn.performEditorAction(EditorInfo.IME_ACTION_DONE);
//triggers login
break;
default:
conn.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER));
break;
}
break;
case SYM_KEYBOARD:
Keyboard currentKeyb = kv.getKeyboard();
if (currentKeyb == symbolKeyboard) {
kv.setKeyboard(qwertyKeyboard);
} else {
kv.setKeyboard(symbolKeyboard);
}
setGoButton();
break;
default:
char code = (char) primaryCode;
if (Character.isLetter(code) && caps) {
code = Character.toUpperCase(code);
}
if (isPassword) {
myPwd = myPwd + code;
if (uidFilled && pwdFilled) {
mEdit.putString(Constants.EDIT_NEW_PWD, myPwd);
} else {
mEdit.putString(Constants.NEW_PWD, myPwd);
}
mEdit.commit();
Log.d("##Pwd saved", "" + mPrefs.getString(Constants.NEW_PWD, ""));
} else {
myUid = myUid + code;
if (uidFilled && pwdFilled) {
mEdit.putString(Constants.EDIT_NEW_UID, myUid);
} else {
mEdit.putString(Constants.NEW_UID, myUid);
}
mEdit.commit();
Log.d("##Uid saved", "" + mPrefs.getString(Constants.NEW_UID, ""));
}
conn.commitText(String.valueOf(code), 1);
}
}
private void saveCredentialsToDb() {
db = openOrCreateDatabase(DbConstants.DATABASE_NAME, MODE_PRIVATE, null);
String activityDbId = getCurrentInputEditorInfo().packageName;
if (myUid == null || myUid.length() <= 0) {
Toast.makeText(getApplicationContext(), "Enter the Username", Toast.LENGTH_SHORT).show();
return;
} else if (myPwd == null || myPwd.length() <= 0) {
Toast.makeText(getApplicationContext(), "Enter the Password", Toast.LENGTH_SHORT).show();
return;
} else if (activityDbId == null && activityDbId.length() <= 0) {
Toast.makeText(getApplicationContext(), "Failed to get app ID", Toast.LENGTH_SHORT).show();
return;
}
Log.d("##Activity pkg name", "" + activityDbId);
ContentValues cv = new ContentValues();
cv.put(DbConstants.APP_ID, activityDbId);
cv.put(DbConstants.UID_VALUE, myUid);
cv.put(DbConstants.PWD_VALUE, myPwd);
if (uidFilled && pwdFilled) {
String oldUid = mPrefs.getString(Constants.EDIT_OLD_UID, null);
String oldPwd = mPrefs.getString(Constants.EDIT_OLD_PWD, null);
if (oldUid != null && oldPwd != null) {
if (oldUid.contentEquals(myUid) && oldPwd.contentEquals(myPwd)) {
Toast.makeText(getApplicationContext(), "Unchanged values.", Toast.LENGTH_SHORT).show();
return;
}
db.update(DbConstants.TABLE_NAME, cv, DbConstants.APP_ID + "=?" + " AND " + DbConstants.UID_VALUE + "=?", new String[]{activityDbId, oldUid});
mEdit.remove(Constants.EDIT_OLD_UID);
mEdit.remove(Constants.EDIT_NEW_UID);
mEdit.remove(Constants.EDIT_NEW_PWD);
mEdit.putBoolean(Constants.UID_FILLED, false);
mEdit.putBoolean(Constants.PWD_FILLED, false);
mEdit.commit();
uidFilled = false;
pwdFilled = false;
Toast.makeText(getApplicationContext(), "Credentials edited!", Toast.LENGTH_SHORT).show();
}
} else {
Cursor cr2 = db.query(DbConstants.TABLE_NAME, null, DbConstants.APP_ID + "=?" + " AND " + DbConstants.UID_VALUE + "=?", new String[]{activityDbId, myUid}, null, null, null);
if (cr2.moveToNext()) {
db.update(DbConstants.TABLE_NAME, cv, DbConstants.APP_ID + "=?" + " AND " + DbConstants.UID_VALUE + "=?", new String[]{activityDbId, myUid});
Toast.makeText(getApplicationContext(), "Credentials edited!", Toast.LENGTH_SHORT).show();
} else {
db.insert(DbConstants.TABLE_NAME, null, cv);
Log.d("Stored:" + activityDbId, myUid + "->" + myPwd);
mEdit.remove(Constants.NEW_UID);
mEdit.remove(Constants.NEW_PWD);
mEdit.commit();
Toast.makeText(getApplicationContext(), "Credentials stored!", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onFinishInput() {
super.onFinishInput();
Log.d("onFinishInput", "invoked");
}
#Override
public void onText(CharSequence charSequence) {
}
#Override
public void swipeLeft() {
}
#Override
public void swipeRight() {
}
#Override
public void swipeDown() {
}
#Override
public void swipeUp() {
}
}
2) CustomKeyboardView:
public class CustomKeyboardView extends KeyboardView {
Context mContext;
Boolean caps;
public CustomKeyboardView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
caps = false;
}
#Override
public boolean setShifted(boolean shifted) {
super.setShifted(shifted);
caps = shifted;
invalidateAllKeys();
return shifted;
}
#Override
public void onDraw(Canvas canvas) {
List<Keyboard.Key> keys = getKeyboard().getKeys();
for (Keyboard.Key key : keys) {
Drawable dr = null;
if (key.codes[0] == Keyboard.KEYCODE_DELETE) {
dr = getResources().getDrawable(R.drawable.keyboard_backspace, mContext.getTheme());
dr.setBounds(key.x, key.y, key.x + key.width, key.y + key.height);
dr.draw(canvas);
} else if (key.codes[0] == Keyboard.KEYCODE_SHIFT) {
dr = getResources().getDrawable(R.drawable.keyboard_shift, mContext.getTheme());
dr.setBounds(key.x, key.y, key.x + key.width, key.y + key.height);
dr.draw(canvas);
} else if (key.codes[0] == 32) { //space bar
int tenDp = Utils.dpToPx(10, mContext);
int twoDp = Utils.dpToPx(2, mContext);
dr = new ColorDrawable(Color.LTGRAY);
dr.setBounds(key.x + twoDp, key.y + (tenDp), key.x + key.width - twoDp, key.y + key.height - (tenDp));
dr.draw(canvas);
}
Paint mPaint = new Paint();
mPaint.setTextAlign(Paint.Align.CENTER);
mPaint.setTextSize(Utils.dpToPx(18, mContext));
mPaint.setColor(Color.BLACK);
if (key.label != null) {
String keyLabel = key.label.toString();
if (caps) {
keyLabel = keyLabel.toUpperCase();
}
canvas.drawText(keyLabel, key.x + (key.width / 2),
key.y + (key.height / 2) + Utils.dpToPx(5, mContext), mPaint);
} else if (key.icon != null) {
key.icon.setBounds(key.x, key.y, key.x + key.width, key.y + key.height);
key.icon.draw(canvas);
}
}
}
}
3) R.layout.my_custom_keyboard:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:orientation="vertical"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/blue">
<ImageView
android:id="#+id/ivRevertKeyboard"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_alignParentRight="true"
android:padding="10dp"
android:scaleType="fitEnd"
android:src="#drawable/keyboard_icon" />
</RelativeLayout>
<com.prasad.CustomKeyboardView
android:id="#+id/keyboard"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:layout_marginTop="5dp"
android:keyPreviewHeight="50dp"
android:background="#color/white"
android:keyPreviewLayout="#xml/keyboard_preview"
android:shadowColor="#color/transparent" />
</LinearLayout>
Expected behaviour: The keyboard should be displayed and hidden properly by the system after swapping multiple times with another keyboard.
Please let me know if you need additional details. Any clues will be appreciated.
Regards,
Prasad
how is this?
#Override
public void onClick(View view) {
vibrator.vibrate(Constants.VIBRATE_TIME_MEDIUM);
try {
// imm.hideSoftInputFromInputMethod(token, 0);
// imm.setInputMethod(token, defImeId);
this.switchInputMethod(defImeId);
} catch (Throwable t) { // java.lang.NoSuchMethodError if API_level<11
t.printStackTrace();
}
}

NullPointerException when retrieving data from sqlite database

ive stored some image names in a sqlite database.My code is supposed to retrieve all the imagenames and store it in a array and then assign the first image to an imageview based on its name.Im using UIL to set the images to the image view.
MY CODE
public class Locker extends Activity {
int index = 0, limit, tolerance = 40, state = 1;
String[] bgimg;
String[] ranimg;
int[] ActXCod;
int[] ActYCod;
ImageView image;
ImageLoader imageloader;
File Path;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.locker);
image = (ImageView) findViewById(R.id.imageView1);
SharedPreferences getprefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
String temp = getprefs.getString("ImageSeqNo", "4");
limit = Integer.parseInt(temp);
Path = getExternalFilesDir(null);
Constants cons = new Constants();
ranimg = cons.getImagePath(Path.toString());
imageloader = ImageLoader.getInstance();
try {
new Thread(new getData()).start();
imageloader.displayImage("file://" + Path.toString() + "/"
+ bgimg[index], image);
} catch (Exception e) {
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("ERROR");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
}
}
public boolean onTouchEvent(MotionEvent event) {
// MotionEvent object holds X-Y values
if (event.getAction() == MotionEvent.ACTION_DOWN) {
int XCood = (int) event.getX();
int YCood = (int) event.getY();
int XMin = ActXCod[index] - tolerance, XMax = ActXCod[index]
+ tolerance, YMin = ActYCod[index] - tolerance, YMax = ActYCod[index]
+ tolerance;
/*
* String text = "You clicked at x = " + XCood + " and y = " +
* YCood; final Toast toast = Toast.makeText(this, text,
* Toast.LENGTH_SHORT); toast.show(); Handler handler = new
* Handler(); handler.postDelayed(new Runnable() {
*
* #Override public void run() { toast.cancel(); } }, 750);
*/
if (index < (limit - 1)) // loop to check number of images
{
// loop to check status
if ((state == 1)
&& (((XCood > XMin) && (XCood < XMax)) && ((YCood > YMin) && (YCood < YMax)))) {
index++;
imageloader.displayImage("file://" + Path.toString() + "/"
+ bgimg[index], image);
} else {
index++;
Random r = new Random();
int ran = r.nextInt(10 - 0);
imageloader.displayImage("file://" + ranimg[ran], image);
state = 0;
}
} else {
if (state == 1) {
Intent i = new Intent(Locker.this, Compare_Pattern.class);
startActivity(i);
finish();
} else {
new AlertDialog.Builder(this)
.setTitle("Failed Login Attempt")
.setMessage(
"Your previous login attempt has failed.Would you like to try again?")
.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
// continue with delete
Intent intent = getIntent();
startActivity(intent);
finish();
}
})
.setNegativeButton(android.R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
// do nothing
finish();
}
}).show();
}
}
}
return super.onTouchEvent(event);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
class getData implements Runnable {
#Override
public void run() {
// TODO Auto-generated method stub
DataBaseHandler handler = new DataBaseHandler(
getApplicationContext());
handler.open();
ActXCod = handler.getXcod();
ActYCod = handler.getYcod();
bgimg = handler.getImg();
handler.close();
}
}
}
i tried debugging the code and its giving me a Java.lang.NullPointerException for bgimg[index] at the line imageloader.displayImage("file://" + Path.toString() + "/" + bgimg[index], image);. i cannot figure out why. Any help is gratefully accepted.
new Thread(new getData()).start();
imageloader.displayImage("file://" + Path.toString() + "/"
+ bgimg[index], image);
bgimg is not initialized yet. Even if you start your thread, it does not run and compelete initialization of bgimg immediately.
Move the code that requires the result of the thread code into the thread itself. You can use Activity.runOnUiThread() to move the execution back to UI thread from a background thread.

Android: clear the listview data on button click

In my app I have a listview where it is loading data based on the search keyword, now I want to clear the loaded data on button click.
#Override
protected void onPreExecute() {
SearchUtils searchUtils = null;
List<Place> searchResult = null;
String searchType = null;
Log.d(TAG, "onPreExecute start=");
// show your dialog
super.onPreExecute();
Log.d(TAG, "LoadMenuSearch isOldDataToLoad : " + isOldDataToLoad);
if(!this.isOldDataToLoad){
this.dialog.setCanceledOnTouchOutside(false);
this.dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
this.dialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface arg0) {
}
});
Button morerecords = (Button) activity.findViewById(R.id.morerecords);
morerecords.setVisibility(View.GONE);
morerecords.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "Do Nothing........................");
}
});
//morerecords.setVisibility(View.VISIBLE);
final Button closesearch = (Button) activity.findViewById(R.id.closesearch);
closesearch.setVisibility(View.VISIBLE);
closesearch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ListView menuSearchListView = (ListView) activity
.findViewById(R.id.menusearchlist);
searchAdapter.clear();
searchAdapter.notifyDataSetChanged();
closesearch.setVisibility(View.GONE);
}
});
Here in the preexecute I have a button, now when I click the button loaded data should be clear and the listview should get refreshed.
my search adaptor
public SearchAdapter(Activity activity, int viewResourceId, int renderer,
double latitute, double longitute, String menuId,
ArrayList<Neighborhood> nhdDetails,
ArrayList<AttractionData> items, boolean isAddressBook,
boolean isRecommended) {
super(activity, viewResourceId, items);
streetView = new StreetViewUtils(activity);
streetView.loadHtml();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) (getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE));
view = inflater.inflate(renderer, null);
}
attractionData = items.get(position);
Log.d(TAG, "attractionData " + attractionData + " for position "
+ position);
TextView textName = (TextView) view.findViewById(R.id.textName);
TextView textAddress = (TextView) view.findViewById(R.id.textAddress);
TextView textPhone = (TextView) view.findViewById(R.id.textPhone);
addFavorite = (ImageView) view.findViewById(R.id.pinsave);
LinearLayout itemlayer = (LinearLayout) view
.findViewById(R.id.itemlayer);
itemlayer.setTag(attractionData);
textName.setText(attractionData.getfName());
if (!isRecommended) {
TextView mapidDisplay = (TextView) view.findViewById(R.id.mapid);
mapidDisplay.setTextSize(Constants.defaultFontSize + 2);
if (isAddressBook) {
mapidDisplay.setBackgroundColor(Color.YELLOW);
mapidDisplay.setTextColor(Color.BLACK);
} else {
mapidDisplay.setBackgroundColor(Color.RED);
mapidDisplay.setTextColor(Color.WHITE);
}
mapidDisplay.setTag(attractionData);
mapidDisplay.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
focusLication(v, event);
return true;
}
});
Log.d(TAG,
"attractionData.getLatitude() ----->"
+ attractionData.getLatitude()
+ " attractionData.getLongitude()---> "
+ attractionData.getLongitude());
if (attractionData.getLatitude() != 0
&& attractionData.getLongitude() != 0) {
mapidDisplay.setText(" " + abbrMapId + (position + 1) + " ");
mapidDisplay.setVisibility(View.VISIBLE);
} else {
mapidDisplay.setVisibility(View.GONE);
}
} else {
ImageView acceptRecommend = (ImageView) view
.findViewById(R.id.acceptRecommend);
ImageView rejectRecommend = (ImageView) view
.findViewById(R.id.rejectRecommend);
acceptRecommend.setVisibility(View.VISIBLE);
rejectRecommend.setVisibility(View.VISIBLE);
acceptRecommend.setTag(attractionData);
rejectRecommend.setTag(attractionData);
acceptRecommend.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
AttractionData data = (AttractionData) ((ImageView) v).getTag();
((CityPreferences) activity.getApplication()).updateRecommended(data);
items.remove(position);
notifyDataSetChanged();
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
});
rejectRecommend.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
AttractionData data = (AttractionData) ((ImageView) v).getTag();
long id = data.getId();
((CityPreferences) activity.getApplication()).deleteSavedAttractions(data);
data.setStatus("unselect");
items.remove(position);
notifyDataSetChanged();
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
});
}
textAddress.setText(attractionData.getAddress());
TextView distance = (TextView) view.findViewById(R.id.distance);
ImageView distanceDir = (ImageView) view
.findViewById(R.id.distancedirection);
Bitmap bitmap = BitmapFactory.decodeResource(activity.getResources(),
R.drawable.navigationdir);
float newRot = new Float(attractionData.getNavigationAngle());
Matrix matrix = new Matrix();
matrix.postRotate(newRot);
// Log.d(TAG, "Roating the Navigation Image : 01" +
// Constants.mOrientation[0]);
if (Constants.mOrientation != null && Constants.mOrientation.length > 0) {
double bearingToTarget = newRot + Constants.mOrientation[0];
double drawingAngle = Math.toRadians(bearingToTarget)
- (Math.PI / 2);
float cos = (float) Math.cos(drawingAngle);
float sin = (float) Math.sin(drawingAngle);
matrix.setSinCos(sin, cos);
Bitmap redrawnBitmap = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), matrix, true);
distanceDir.setImageBitmap(redrawnBitmap);
// distanceDir.setRotation(90);
} else {
Bitmap redrawnBitmap = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), matrix, true);
distanceDir.setImageBitmap(redrawnBitmap);
}
if (attractionData.getDistance() != null
&& !attractionData.getDistance().equals("")) {
distance.setText(attractionData.getDistance());
} else {
distance.setText("");
}
if (attractionData.getLatitude() != 0.00
&& attractionData.getLongitude() != 0.00) {
distanceDir.setVisibility(View.VISIBLE);
distance.setVisibility(View.VISIBLE);
} else {
distanceDir.setVisibility(View.GONE);
distance.setVisibility(View.GONE);
}
// Log.d(TAG, "end to search distance -->");
LinearLayout llReviews = (LinearLayout) view
.findViewById(R.id.reviewsrating);
llReviews.setVisibility(View.VISIBLE);
GridView gridview = (GridView) view.findViewById(R.id.ratingView);
TextView textRating = (TextView) view.findViewById(R.id.rating);
TextView textReviews = (TextView) view.findViewById(R.id.reviews);
textRating.setText("(" + attractionData.getRating() + ")");
gridview.setAdapter(new ImageAdapter(getContext(), attractionData
.getRating()));
// code for review
if (attractionData.getReview() != null
&& (attractionData.getReview().equals("1") || attractionData
.getReview().equals("0"))) {
textReviews.setText(attractionData.getReview() + " review");
} else if (attractionData.getReview() != null) {
textReviews.setText(attractionData.getReview() + " reviews");
} else {
textReviews.setText("0 review");
}
textReviews.setTag(attractionData.getReviewUrl());
textReviews.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String webURL = (String) v.getTag();
utils.openWebURL(v.getContext(), webURL);
}
});
if (Constants.isDefineNeighbourHood) {
addFavorite.setVisibility(View.GONE);
} else {
if (attractionData.getId() > 0) {
if (menuId != null && menuId.equalsIgnoreCase(Constants.menuFavouritePlaceId)) {
addFavorite.setImageResource(R.drawable.favorite_active);
addFavorite.setVisibility(View.GONE);
attractionData.setStatus("select");
EditAttraction editAttraction = new EditAttraction(activity, false);
itemlayer.setOnLongClickListener(editAttraction);
if (!Constants.isEysonly) {
Loginmyplaces loginmyplaces = new Loginmyplaces(activity);
itemlayer.setOnClickListener(loginmyplaces);
}
} else {
addFavorite.setImageResource(R.drawable.favorite_active);
addFavorite.setVisibility(View.VISIBLE);
attractionData.setStatus("select");
EditAttraction editAttraction = new EditAttraction(activity, true);
itemlayer.setOnLongClickListener(editAttraction);
}
} else {
addFavorite.setVisibility(View.VISIBLE);
addFavorite.setImageResource(R.drawable.favorite);
attractionData.setStatus("unselect");
EditAttraction editAttraction = new EditAttraction(activity,
true);
itemlayer.setOnLongClickListener(editAttraction);
}
}
// Log.d(TAG, "Constants.totalFavorite : status : " +
// attractionData.getStatus() + " for " + attractionData.getName());
addFavorite.setTag(attractionData);
addFavorite.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
AttractionData data = (AttractionData) ((ImageView) v)
.getTag();
ImageView currentpinsave = (ImageView) v
.findViewById(R.id.pinsave);
Log.d(TAG,
"Constants.totalFavorite : status : "
+ data.getStatus());
Log.d(TAG, "Constants.totalFavorite : Resource : "
+ currentpinsave);
if (data.getStatus() != null
&& data.getStatus().equalsIgnoreCase("select")) {
Log.d(TAG, "data.status " + data.getStatus());
currentpinsave.setImageResource(R.drawable.favorite);
currentpinsave.setTag(data);
long id = data.getId();
((CityPreferences) activity.getApplication())
.deleteSavedAttractions(data);
data.setStatus("unselect");
currentpinsave.setImageResource(R.drawable.favorite);
new DeleteFromConstance().execute(id);
} else {
Log.d(TAG, "data.status " + data.getStatus());
currentpinsave
.setImageResource(R.drawable.favorite_active);
currentpinsave.setTag(data);
data.setMenuId(menuId);
streetView.checkPhotoView(data);
((CityPreferences) activity.getApplication())
.saveMyAttractions(data, true);
data.setStatus("select");
utils.checkFavoriteCity(activity, data);
}
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
});
if (!isRecommended) {
if (attractionData.getImages() != null) {
Log.d(TAG, "ImageUtils --> inside blob saved");
ImageView placeImage = (ImageView) view
.findViewById(R.id.placeimage);
placeImage.setVisibility(View.VISIBLE);
placeImage.setImageBitmap(attractionData.getImages());
} else {
Log.d(TAG, "ImageUtils --> inside blob not saved");
ImageView placeImage = (ImageView) view
.findViewById(R.id.placeimage);
placeImage.setVisibility(View.GONE);
}
}
ImageView navigationImage = (ImageView) view
.findViewById(R.id.navigationImage);
ImageView streetViewImage = (ImageView) view
.findViewById(R.id.streetview);
if (attractionData.getLatitude() != 0
&& attractionData.getLongitude() != 0) {
navigationImage.setImageResource(R.drawable.navigation);
navigationImage.setTag(attractionData);
navigationImage.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (utils.isConnectionAvailable(v.getContext())) {
Intent intent = new Intent(v.getContext(), Navigator.class);
AttractionData data = (AttractionData) ((ImageView) v).getTag();
Bundle bundle = new Bundle();
// add data to bundle
bundle.putString("startlatitude", latitute + "");
bundle.putString("startlongitude", longitute + "");
bundle.putString("latitude", data.getLatitude() + "");
bundle.putString("longitude", data.getLongitude() + "");
intent.putExtras(bundle);
v.getContext().startActivity(new Intent(intent).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK));
} else {
Toast.makeText(v.getContext(), v.getContext().getResources().getString(R.string.noconnection), Toast.LENGTH_LONG).show();
}
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
});
streetViewImage.setTag(attractionData);
streetViewImage.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
AttractionData data = (AttractionData) v.getTag();
Location location = new Location("");
location.setLatitude(data.getLatitude());
location.setLongitude(data.getLongitude());
streetView.checkStreetView(location);
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}});
streetViewImage.setVisibility(View.VISIBLE);
navigationImage.setVisibility(View.VISIBLE);
} else {
streetViewImage.setVisibility(View.GONE);
navigationImage.setVisibility(View.GONE);
}
LinearLayout commentLayout = (LinearLayout) view
.findViewById(R.id.commentLayout);
if (attractionData.getComments() != null
&& !attractionData.getComments().trim().equals("")) {
commentLayout.setVisibility(View.VISIBLE);
TextView comment = (TextView) view.findViewById(R.id.comment);
comment.setText(attractionData.getComments());
} else {
commentLayout.setVisibility(View.GONE);
}
ImageView phImage = (ImageView) view.findViewById(R.id.phoneImage);
String phoneNo = attractionData.getPhoneNo();
if (attractionData.getMobileNo() != null
&& !attractionData.getMobileNo().equals("")
&& !attractionData.getMobileNo().equalsIgnoreCase("null")) {
if (phoneNo != null && !phoneNo.equals("")
&& !phoneNo.equalsIgnoreCase("null")) {
phoneNo = phoneNo + ",\n" + attractionData.getMobileNo();
} else {
phoneNo = attractionData.getMobileNo();
}
}
Log.d(TAG, "------------------> phoneNo " + phoneNo);
if (phoneNo != null && !phoneNo.equals("") && !phoneNo.equalsIgnoreCase("null")) {
textPhone.setText(phoneNo);
textPhone.setVisibility(View.VISIBLE);
phImage.setVisibility(View.VISIBLE);
phImage.setImageResource(R.drawable.phone);
phImage.setTag(phoneNo);
phImage.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
String phone = (String) ((ImageView) v).getTag();
Log.d(TAG, "onTouch phone--" + phone);
utils.dailPhone(v.getContext(), phone);
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
});
} else {
phImage.setVisibility(View.GONE);
textPhone.setVisibility(View.GONE);
}
LinearLayout htmllayout = (LinearLayout) view
.findViewById(R.id.htmllayout);
if (attractionData.getHtmlAttributions() != null
&& !attractionData.getHtmlAttributions().equals("")
&& !attractionData.getHtmlAttributions().equalsIgnoreCase(
"null")) {
htmllayout.setVisibility(View.VISIBLE);
TextView htmlAttributions = (TextView) view
.findViewById(R.id.htmlAttributions);
TextView htmlAttributionsLink = (TextView) view
.findViewById(R.id.htmlAttributionsLink);
htmlAttributions.setText(attractionData.getHtmlAttributions());
htmlAttributionsLink.setText(attractionData
.getHtmlAttributionsLink());
htmlAttributionsLink.setTag(attractionData);
htmlAttributionsLink.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
AttractionData data = (AttractionData) ((TextView) v)
.getTag();
utils.openWebURL(v.getContext(),
data.getHtmlAttributionsUrl());
new Intent(Intent.ACTION_VIEW);
return true;
}
});
} else {
htmllayout.setVisibility(View.GONE);
}
// ********************************************* changing for showing
// the zagat review and price level
String priceTag = attractionData.getPriceTag();
String zagatReview = attractionData.getZagatReview();
Log.d(TAG, "Extra Parameter Setup : " + attractionData.getfName()
+ " URL : " + attractionData.getReviewUrl());
Log.d(TAG, "Extra Parameter Setup : priceTag : " + priceTag
+ " zagatReview : " + zagatReview);
if (priceTag != null && !priceTag.equals("")) {
((TextView) view.findViewById(R.id.pricelevelvalue))
.setText(priceTag);
} else {
view.findViewById(R.id.pricelevelvalue).setVisibility(View.GONE);
}
if (zagatReview != null && !zagatReview.equals("")) {
view.findViewById(R.id.moredetail_review).setVisibility(
View.VISIBLE);
((TextView) view.findViewById(R.id.zagatreviewvalue))
.setText(zagatReview);
} else {
view.findViewById(R.id.moredetail_review).setVisibility(View.GONE);
}
Reservation reservation = attractionData.getReservation();
List<PlaceMenu> menus = attractionData.getMenu();
if ((reservation != null) || (menus != null && !menus.isEmpty())) {
view.findViewById(R.id.moredetail_menu_reservation).setVisibility(
View.VISIBLE);
TextView reservationTextView = (TextView) view
.findViewById(R.id.reservationvalues);
if (reservation != null && reservation.getName() != null
&& !reservation.getName().equals("")) {
Log.d(TAG,
"Extra Parameter Setup : reservation "
+ reservation.getName() + " URL : "
+ reservation.getUrl());
view.findViewById(R.id.reservation).setVisibility(View.VISIBLE);
reservationTextView.setVisibility(View.VISIBLE);
reservationTextView.setText(reservation.getName());
reservationTextView.setTag(reservation.getUrl());
reservationTextView.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
utils.openWebURL(v.getContext(),
(String) ((TextView) v).getTag());
new Intent(Intent.ACTION_VIEW);
return true;
}
});
} else {
view.findViewById(R.id.reservation).setVisibility(View.GONE);
reservationTextView.setVisibility(View.GONE);
}
TextView placemenuTextView = (TextView) view
.findViewById(R.id.placemenu);
if (menus != null && !menus.isEmpty()) {
Log.d(TAG,
"Extra Parameter Setup : Menu Size : " + menus.size());
placemenuTextView.setVisibility(View.VISIBLE);
placemenuTextView.setTag(menus);
placemenuTextView.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
List<PlaceMenu> placeMenu = (List<PlaceMenu>) ((TextView) v).getTag();
ArrayList<DialogData> data = new ArrayList<DialogData>();
for (int i = 0; i < placeMenu.size(); i++) {
DialogData dialogData = new DialogData();
dialogData.setName(placeMenu.get(i).getName());
dialogData.setValue(placeMenu.get(i).getUrl());
dialogData.setType("url");
data.add(dialogData);
}
utils.showPopupDailog(v.getContext(), data, "Menu");
new Intent(Intent.ACTION_VIEW);
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
});
} else {
placemenuTextView.setVisibility(View.GONE);
}
} else {
view.findViewById(R.id.moredetail_menu_reservation).setVisibility(
View.GONE);
}
if (attractionData.getHotelReview() != null) {
PlaceHotelReview hotelReview = null;
TextView textView = null;
textView = (TextView) view.findViewById(R.id.hotelreviewtext);
if (menuId != null && menuId.equals(Constants.menuHotelId)) {
textView.setText(R.string.hotelPricing);
} else {
textView.setText(R.string.hotelreview);
}
Log.d(TAG, "Hotel Review Step 02 : ");
LinearLayout rl = (LinearLayout) view
.findViewById(R.id.hotelreview);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
view.findViewById(R.id.hotelreview).setVisibility(View.VISIBLE);
rl.removeAllViews();
rl.addView(textView, lp);
for (int i = 0; i < attractionData.getHotelReview().size(); i++) {
hotelReview = attractionData.getHotelReview().get(i);
Log.d(TAG, "Hotel Review Step 03 : " + hotelReview);
textView = new TextView(activity);
Log.d(TAG, "Hotel Review Step 04 : " + hotelReview.getName());
Log.d(TAG, "Hotel Review Step 05 : " + hotelReview.getReviews());
textView.setText(hotelReview.getName().replaceAll("\"", ""));
if (i == attractionData.getHotelReview().size() - 1) {
textView.setPadding(5, 5, 0, 5);
} else if (i == attractionData.getHotelReview().size() - 1) {
textView.setPadding(5, 0, 0, 5);
} else {
textView.setPadding(5, 5, 0, 0);
}
textView.setTextColor(Color.parseColor("#0000ff"));
textView.setTag(hotelReview);
Log.d(TAG, "Hotel Review Step 05 : ");
textView.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
PlaceHotelReview hotelReview = (PlaceHotelReview) v.getTag();
utils.openWebURL(v.getContext(), hotelReview.getUrl().replaceAll("\"", ""));
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
});
rl.addView(textView, lp);
}
} else {
view.findViewById(R.id.hotelreview).setVisibility(View.GONE);
}
TextView openCloseTime = (TextView) view
.findViewById(R.id.openclosedesc);
if (attractionData.getOpenCloseDesc() != null
&& !attractionData.getOpenCloseDesc().equals("")
&& !attractionData.getOpenCloseDesc().equalsIgnoreCase("null")) {
openCloseTime.setText(attractionData.getOpenCloseDesc());
} else {
openCloseTime.setVisibility(View.GONE);
}
itemlayer.setOnTouchListener(new DetectMotion(activity, isAddressBook));
if (position % 2 == 0)
view.setBackgroundResource(R.drawable.listshape);
else
view.setBackgroundResource(R.drawable.favoritebody);
return view;
}
private void focusLication(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
AttractionData ad = (AttractionData) v.getTag();
Constants.isMaptobeLoaded = true;
if (ad.getLatitude() != 0 && ad.getLongitude() != 0) {
if (Constants.isDefineNeighbourHood) {
if (Constants.focusLocationNH == null) {
Constants.focusLocationNH = new Location("");
}
Constants.focusLocationNH.setLatitude(ad.getLatitude());
Constants.focusLocationNH.setLongitude(ad.getLongitude());
if (Constants.myNeighborHoodLocation == null) {
Constants.myNeighborHoodLocation = new Location("");
}
Constants.myNeighborHoodLocation.setLatitude(ad
.getLatitude());
Constants.myNeighborHoodLocation.setLongitude(ad
.getLongitude());
} else {
if (Constants.focusLocation == null) {
Constants.focusLocation = new Location("");
}
Constants.focusLocation.setLatitude(ad.getLatitude());
Constants.focusLocation.setLongitude(ad.getLongitude());
}
activity.finish();
if (isAddressBook) {
Constants.isPABImportant = true;
activity.overridePendingTransition(R.anim.slide_in_left,
R.anim.slide_out_left);
} else {
Constants.isPABImportant = false;
activity.overridePendingTransition(R.anim.slide_out_right,
R.anim.slide_in_right);
}
}
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
}
}
Any help is appreciated.
Try like this way
list.clear();
adpater.notifyDataSetChanged();
/// remove item from list.
adapter.clear();
adpater.notifyDataSetChanged();
Not all Adapters have a clear() method. ArrayAdapter does, but ListAdapter or SimpleAdapter doesn't
Just notify the listview after clearing the data of adapter i guess searchAdapter is your adapter . SearchAdapter is a custom adapter where you need to clear data based on type of adapter then call notifyDataSetChanged.
This is the code for clearing listview data on button click
Button yourbutton; // init it
yourButon.setOnClickListener(new OnClickListener(){
yourList.clear(); // this list which you hava passed in Adapter for your listview
yourAdapter.notifyDataSetChanged(); // notify to listview for refresh
});

Android strange action "program"

The program draws two digits, and the sign. IF statement checks to see if it has been drawn + / -. If it draws + add, if - is subtraction.
Draw works.
Then the user is given the result of the task. And here is the problem.
If you give a result which is in the "result". Function if something does. If you entered an incorrect answer is displayed Toast: Try Again.
The problem is that sometimes as to give a good result is is displayed Try Again.
How to eliminate this problem? Might different check?
Code:
private String sign;
private int numberOne, numberTwo, result = 0;
private int charsEntered = 0;
private EditText et;
private Button ok;
String[] CHAR = { "+", "-" };
Random intGen = new Random();
CaptchaInterface.OnCorrectListener mCorrectListener;
public void setOnCorrectListener(CaptchaInterface.OnCorrectListener listener) {
mCorrectListener = listener;
}
public EasyMathCaptcha(Context context) {
super(context);
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
}
public static int randomOne() {
Random generator = new Random();
int x = generator.nextInt(10);
return x;
}
public static int randomTwo() {
Random generator = new Random();
int x = generator.nextInt(10);
return x;
}
public void onCreate(Bundle icicle) {
setContentView(R.layout.all_math_captcha);
sign = (CHAR[Math.abs(intGen.nextInt() % 2)]);
numberOne = randomOne();
numberTwo = randomTwo();
TextView display = (TextView) findViewById(R.id.tvRandomTask);
display.setText(numberOne + " " + sign + " " + numberTwo);
if ((CHAR[Math.abs(intGen.nextInt() % 2)]).equals("+")) {
result = (numberOne + numberTwo);
} else if ((CHAR[Math.abs(intGen.nextInt() % 2)]).equals("-")) {
result = (numberOne - numberTwo);
}
et = (EditText) findViewById(R.id.etTask);
ok = (Button) findViewById(R.id.btAgree);
ok.setOnClickListener(this);
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
try {
charsEntered = Integer.parseInt(et.getText().toString());
} catch (NumberFormatException nfe) {
Toast.makeText(et.getContext(), "That's not a number!",
Toast.LENGTH_SHORT).show();
}
if (charsEntered == result) {
if (mCorrectListener != null)
mCorrectListener.onCorrect();
dismiss();
} else if (charsEntered != result) {
Toast.makeText(et.getContext(), "Try again!", Toast.LENGTH_SHORT)
.show();
}
}
}
The error is in the following code:
if ((CHAR[Math.abs(intGen.nextInt() % 2)]).equals("+")) {
result = (numberOne + numberTwo);
} else if ((CHAR[Math.abs(intGen.nextInt() % 2)]).equals("-")) {
result = (numberOne - numberTwo);
}
You are using the random number generator which can give you results different than what it gave the first time.
Change it to:
if (sign.equals("+")) {
result = (numberOne + numberTwo);
} else if (sign.equals("-")) {
result = (numberOne - numberTwo);
}

Categories

Resources