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();
}
}
Related
06-28 17:05:23.694 13262-13262/io.hypertrack.sendeta.debug
E/AndroidRuntime: FATAL EXCEPTION: main
Process: io.hypertrack.sendeta.debug, PID: 13262
java.lang.RuntimeException: Unable to start activity ComponentInfo{io.hypertrack.sendeta.debug/io.hypertrack.sendeta.activities.MainActivity}:
android.view.InflateException: Binary XML file line #4: Error
inflating class java.lang.reflect.Constructor
io.hypertrack.sendeta.activities.MainActivity.onCreate(MainActivity.java:109)
public class MainActivity extends AppCompatActivity implements LocationListener {
protected static final int MY_PERMISSIONS_ACCESS_FINE_LOCATION = 1;
// Time in milliseconds; only reload weather if last update is longer ago than this value
private static final int NO_UPDATE_REQUIRED_THRESHOLD = 300000;
private static Map<String, Integer> speedUnits = new HashMap<>(3);
private static Map<String, Integer> pressUnits = new HashMap<>(3);
private static boolean mappingsInitialised = false;
Typeface weatherFont;
Weather todayWeather = new Weather();
TextView todayTemperature;
TextView todayDescription;
TextView todayWind;
TextView todayPressure;
TextView todayHumidity;
TextView todaySunrise;
TextView todaySunset;
TextView lastUpdate;
TextView todayIcon;
ViewPager viewPager;
TabLayout tabLayout;
View appView;
LocationManager locationManager;
ProgressDialog progressDialog;
int theme;
boolean destroyed = false;
private List<Weather> longTermWeather = new ArrayList<>();
private List<Weather> longTermTodayWeather = new ArrayList<>();
private List<Weather> longTermTomorrowWeather = new ArrayList<>();
public String recentCity = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
// Initialize the associated SharedPreferences file with default values
PreferenceManager.setDefaultValues(this, R.xml.prefs, false);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
setTheme(theme = getTheme(prefs.getString("theme", "fresh")));
boolean darkTheme = theme == R.style.AppTheme_NoActionBar_Dark ||
theme == R.style.AppTheme_NoActionBar_Classic_Dark;
boolean blackTheme = theme == R.style.AppTheme_NoActionBar_Black ||
theme == R.style.AppTheme_NoActionBar_Classic_Black;
// Initiate activity
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scrolling);
appView = findViewById(R.id.viewApp);
progressDialog = new ProgressDialog(MainActivity.this);
// Load toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (darkTheme) {
toolbar.setPopupTheme(R.style.AppTheme_PopupOverlay_Dark);
} else if (blackTheme) {
toolbar.setPopupTheme(R.style.AppTheme_PopupOverlay_Black);
}
// Initialize textboxes
todayTemperature = (TextView) findViewById(R.id.todayTemperature);
todayDescription = (TextView) findViewById(R.id.todayDescription);
todayWind = (TextView) findViewById(R.id.todayWind);
todayPressure = (TextView) findViewById(R.id.todayPressure);
todayHumidity = (TextView) findViewById(R.id.todayHumidity);
todaySunrise = (TextView) findViewById(R.id.todaySunrise);
todaySunset = (TextView) findViewById(R.id.todaySunset);
lastUpdate = (TextView) findViewById(R.id.lastUpdate);
todayIcon = (TextView) findViewById(R.id.todayIcon);
weatherFont = Typeface.createFromAsset(this.getAssets(), "fonts/weather.ttf");
todayIcon.setTypeface(weatherFont);
// Initialize viewPager
viewPager = (ViewPager) findViewById(R.id.viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
destroyed = false;
initMappings();
// Preload data from cache
preloadWeather();
updateLastUpdateTime();
// Set autoupdater
AlarmReceiver.setRecurringAlarm(this);
}
public WeatherRecyclerAdapter getAdapter(int id) {
WeatherRecyclerAdapter weatherRecyclerAdapter;
if (id == 0) {
weatherRecyclerAdapter = new WeatherRecyclerAdapter(this, longTermTodayWeather);
} else if (id == 1) {
weatherRecyclerAdapter = new WeatherRecyclerAdapter(this, longTermTomorrowWeather);
} else {
weatherRecyclerAdapter = new WeatherRecyclerAdapter(this, longTermWeather);
}
return weatherRecyclerAdapter;
}
#Override
public void onStart() {
super.onStart();
updateTodayWeatherUI();
updateLongTermWeatherUI();
}
#Override
public void onResume() {
super.onResume();
if (getTheme(PreferenceManager.getDefaultSharedPreferences(this).getString("theme", "fresh")) != theme) {
// Restart activity to apply theme
overridePendingTransition(0, 0);
finish();
overridePendingTransition(0, 0);
startActivity(getIntent());
} else if (shouldUpdate() && isNetworkAvailable()) {
getTodayWeather();
getLongTermWeather();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
destroyed = true;
if (locationManager != null) {
try {
locationManager.removeUpdates(MainActivity.this);
} catch (SecurityException e) {
e.printStackTrace();
}
}
}
private void preloadWeather() {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
String lastToday = sp.getString("lastToday", "");
if (!lastToday.isEmpty()) {
new TodayWeatherTask(this, this, progressDialog).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "cachedResponse", lastToday);
}
String lastLongterm = sp.getString("lastLongterm", "");
if (!lastLongterm.isEmpty()) {
new LongTermWeatherTask(this, this, progressDialog).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "cachedResponse", lastLongterm);
}
}
private void getTodayWeather() {
new TodayWeatherTask(this, this, progressDialog).execute();
}
private void getLongTermWeather() {
new LongTermWeatherTask(this, this, progressDialog).execute();
}
private void searchCities() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle(this.getString(R.string.search_title));
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
input.setMaxLines(1);
input.setSingleLine(true);
alert.setView(input, 32, 0, 32, 0);
alert.setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String result = input.getText().toString();
if (!result.isEmpty()) {
saveLocation(result);
}
}
});
alert.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Cancelled
}
});
alert.show();
}
private void saveLocation(String result) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
recentCity = preferences.getString("city", Constants.DEFAULT_CITY);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("city", result);
editor.commit();
if (!recentCity.equals(result)) {
// New location, update weather
getTodayWeather();
getLongTermWeather();
}
}
private void aboutDialog() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Forecastie");
final WebView webView = new WebView(this);
String about = "<p>1.6.1</p>" +
"<p>A lightweight, opensource weather app.</p>" +
"<p>Developed by <a href='mailto:t.martykan#gmail.com'>Tomas Martykan</a></p>" +
"<p>Data provided by <a href='https://openweathermap.org/'>OpenWeatherMap</a>, under the <a href='http://creativecommons.org/licenses/by-sa/2.0/'>Creative Commons license</a>" +
"<p>Icons are <a href='https://erikflowers.github.io/weather-icons/'>Weather Icons</a>, by <a href='http://www.twitter.com/artill'>Lukas Bischoff</a> and <a href='http://www.twitter.com/Erik_UX'>Erik Flowers</a>, under the <a href='http://scripts.sil.org/OFL'>SIL OFL 1.1</a> licence.";
TypedArray ta = obtainStyledAttributes(new int[]{android.R.attr.textColorPrimary, R.attr.colorAccent});
String textColor = String.format("#%06X", (0xFFFFFF & ta.getColor(0, Color.BLACK)));
String accentColor = String.format("#%06X", (0xFFFFFF & ta.getColor(1, Color.BLUE)));
ta.recycle();
about = "<style media=\"screen\" type=\"text/css\">" +
"body {\n" +
" color:" + textColor + ";\n" +
"}\n" +
"a:link {color:" + accentColor + "}\n" +
"</style>" +
about;
webView.setBackgroundColor(Color.TRANSPARENT);
webView.loadData(about, "text/html", "UTF-8");
alert.setView(webView, 32, 0, 32, 0);
alert.setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alert.show();
}
private String setWeatherIcon(int actualId, int hourOfDay) {
int id = actualId / 100;
String icon = "";
if (actualId == 800) {
if (hourOfDay >= 7 && hourOfDay < 20) {
icon = this.getString(R.string.weather_sunny);
} else {
icon = this.getString(R.string.weather_clear_night);
}
} else {
switch (id) {
case 2:
icon = this.getString(R.string.weather_thunder);
break;
case 3:
icon = this.getString(R.string.weather_drizzle);
break;
case 7:
icon = this.getString(R.string.weather_foggy);
break;
case 8:
icon = this.getString(R.string.weather_cloudy);
break;
case 6:
icon = this.getString(R.string.weather_snowy);
break;
case 5:
icon = this.getString(R.string.weather_rainy);
break;
}
}
return icon;
}
public static String getRainString(JSONObject rainObj) {
String rain = "0";
if (rainObj != null) {
rain = rainObj.optString("3h", "fail");
if ("fail".equals(rain)) {
rain = rainObj.optString("1h", "0");
}
}
return rain;
}
private ParseResult parseTodayJson(String result) {
try {
JSONObject reader = new JSONObject(result);
final String code = reader.optString("cod");
if ("404".equals(code)) {
return ParseResult.CITY_NOT_FOUND;
}
String city = reader.getString("name");
String country = "";
JSONObject countryObj = reader.optJSONObject("sys");
if (countryObj != null) {
country = countryObj.getString("country");
todayWeather.setSunrise(countryObj.getString("sunrise"));
todayWeather.setSunset(countryObj.getString("sunset"));
}
todayWeather.setCity(city);
todayWeather.setCountry(country);
JSONObject coordinates = reader.getJSONObject("coord");
if (coordinates != null) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
sp.edit().putFloat("latitude", (float) coordinates.getDouble("lon")).putFloat("longitude", (float) coordinates.getDouble("lat")).commit();
}
JSONObject main = reader.getJSONObject("main");
todayWeather.setTemperature(main.getString("temp"));
todayWeather.setDescription(reader.getJSONArray("weather").getJSONObject(0).getString("description"));
JSONObject windObj = reader.getJSONObject("wind");
todayWeather.setWind(windObj.getString("speed"));
if (windObj.has("deg")) {
todayWeather.setWindDirectionDegree(windObj.getDouble("deg"));
} else {
Log.e("parseTodayJson", "No wind direction available");
todayWeather.setWindDirectionDegree(null);
}
todayWeather.setPressure(main.getString("pressure"));
todayWeather.setHumidity(main.getString("humidity"));
JSONObject rainObj = reader.optJSONObject("rain");
String rain;
if (rainObj != null) {
rain = getRainString(rainObj);
} else {
JSONObject snowObj = reader.optJSONObject("snow");
if (snowObj != null) {
rain = getRainString(snowObj);
} else {
rain = "0";
}
}
todayWeather.setRain(rain);
final String idString = reader.getJSONArray("weather").getJSONObject(0).getString("id");
todayWeather.setId(idString);
todayWeather.setIcon(setWeatherIcon(Integer.parseInt(idString), Calendar.getInstance().get(Calendar.HOUR_OF_DAY)));
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainActivity.this).edit();
editor.putString("lastToday", result);
editor.commit();
} catch (JSONException e) {
Log.e("JSONException Data", result);
e.printStackTrace();
return ParseResult.JSON_EXCEPTION;
}
return ParseResult.OK;
}
private void updateTodayWeatherUI() {
try {
if (todayWeather.getCountry().isEmpty()) {
preloadWeather();
return;
}
} catch (Exception e) {
preloadWeather();
return;
}
String city = todayWeather.getCity();
String country = todayWeather.getCountry();
DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(getApplicationContext());
getSupportActionBar().setTitle(city + (country.isEmpty() ? "" : ", " + country));
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
// Temperature
float temperature = UnitConvertor.convertTemperature(Float.parseFloat(todayWeather.getTemperature()), sp);
if (sp.getBoolean("temperatureInteger", false)) {
temperature = Math.round(temperature);
}
// Rain
double rain = Double.parseDouble(todayWeather.getRain());
String rainString = UnitConvertor.getRainString(rain, sp);
// Wind
double wind;
try {
wind = Double.parseDouble(todayWeather.getWind());
} catch (Exception e) {
e.printStackTrace();
wind = 0;
}
wind = UnitConvertor.convertWind(wind, sp);
// Pressure
double pressure = UnitConvertor.convertPressure((float) Double.parseDouble(todayWeather.getPressure()), sp);
todayTemperature.setText(new DecimalFormat("0.#").format(temperature) + " " + sp.getString("unit", "°C"));
todayDescription.setText(todayWeather.getDescription().substring(0, 1).toUpperCase() +
todayWeather.getDescription().substring(1) + rainString);
if (sp.getString("speedUnit", "m/s").equals("bft")) {
todayWind.setText(getString(R.string.wind) + ": " +
UnitConvertor.getBeaufortName((int) wind) +
(todayWeather.isWindDirectionAvailable() ? " " + getWindDirectionString(sp, this, todayWeather) : ""));
} else {
todayWind.setText(getString(R.string.wind) + ": " + new DecimalFormat("0.0").format(wind) + " " +
localize(sp, "speedUnit", "m/s") +
(todayWeather.isWindDirectionAvailable() ? " " + getWindDirectionString(sp, this, todayWeather) : ""));
}
todayPressure.setText(getString(R.string.pressure) + ": " + new DecimalFormat("0.0").format(pressure) + " " +
localize(sp, "pressureUnit", "hPa"));
todayHumidity.setText(getString(R.string.humidity) + ": " + todayWeather.getHumidity() + " %");
todaySunrise.setText(getString(R.string.sunrise) + ": " + timeFormat.format(todayWeather.getSunrise()));
todaySunset.setText(getString(R.string.sunset) + ": " + timeFormat.format(todayWeather.getSunset()));
todayIcon.setText(todayWeather.getIcon());
}
public ParseResult parseLongTermJson(String result) {
int i;
try {
JSONObject reader = new JSONObject(result);
final String code = reader.optString("cod");
if ("404".equals(code)) {
if (longTermWeather == null) {
longTermWeather = new ArrayList<>();
longTermTodayWeather = new ArrayList<>();
longTermTomorrowWeather = new ArrayList<>();
}
return ParseResult.CITY_NOT_FOUND;
}
longTermWeather = new ArrayList<>();
longTermTodayWeather = new ArrayList<>();
longTermTomorrowWeather = new ArrayList<>();
JSONArray list = reader.getJSONArray("list");
for (i = 0; i < list.length(); i++) {
Weather weather = new Weather();
JSONObject listItem = list.getJSONObject(i);
JSONObject main = listItem.getJSONObject("main");
weather.setDate(listItem.getString("dt"));
weather.setTemperature(main.getString("temp"));
weather.setDescription(listItem.optJSONArray("weather").getJSONObject(0).getString("description"));
JSONObject windObj = listItem.optJSONObject("wind");
if (windObj != null) {
weather.setWind(windObj.getString("speed"));
weather.setWindDirectionDegree(windObj.getDouble("deg"));
}
weather.setPressure(main.getString("pressure"));
weather.setHumidity(main.getString("humidity"));
JSONObject rainObj = listItem.optJSONObject("rain");
String rain = "";
if (rainObj != null) {
rain = getRainString(rainObj);
} else {
JSONObject snowObj = listItem.optJSONObject("snow");
if (snowObj != null) {
rain = getRainString(snowObj);
} else {
rain = "0";
}
}
weather.setRain(rain);
final String idString = listItem.optJSONArray("weather").getJSONObject(0).getString("id");
weather.setId(idString);
final String dateMsString = listItem.getString("dt") + "000";
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(Long.parseLong(dateMsString));
weather.setIcon(setWeatherIcon(Integer.parseInt(idString), cal.get(Calendar.HOUR_OF_DAY)));
Calendar today = Calendar.getInstance();
if (cal.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR)) {
longTermTodayWeather.add(weather);
} else if (cal.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR) + 1) {
longTermTomorrowWeather.add(weather);
} else {
longTermWeather.add(weather);
}
}
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainActivity.this).edit();
editor.putString("lastLongterm", result);
editor.commit();
} catch (JSONException e) {
Log.e("JSONException Data", result);
e.printStackTrace();
return ParseResult.JSON_EXCEPTION;
}
return ParseResult.OK;
}
private void updateLongTermWeatherUI() {
if (destroyed) {
return;
}
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
Bundle bundleToday = new Bundle();
bundleToday.putInt("day", 0);
RecyclerViewFragment recyclerViewFragmentToday = new RecyclerViewFragment();
recyclerViewFragmentToday.setArguments(bundleToday);
viewPagerAdapter.addFragment(recyclerViewFragmentToday, getString(R.string.today));
Bundle bundleTomorrow = new Bundle();
bundleTomorrow.putInt("day", 1);
RecyclerViewFragment recyclerViewFragmentTomorrow = new RecyclerViewFragment();
recyclerViewFragmentTomorrow.setArguments(bundleTomorrow);
viewPagerAdapter.addFragment(recyclerViewFragmentTomorrow, getString(R.string.tomorrow));
Bundle bundle = new Bundle();
bundle.putInt("day", 2);
RecyclerViewFragment recyclerViewFragment = new RecyclerViewFragment();
recyclerViewFragment.setArguments(bundle);
viewPagerAdapter.addFragment(recyclerViewFragment, getString(R.string.later));
int currentPage = viewPager.getCurrentItem();
viewPagerAdapter.notifyDataSetChanged();
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
if (currentPage == 0 && longTermTodayWeather.isEmpty()) {
currentPage = 1;
}
viewPager.setCurrentItem(currentPage, false);
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
private boolean shouldUpdate() {
long lastUpdate = PreferenceManager.getDefaultSharedPreferences(this).getLong("lastUpdate", -1);
boolean cityChanged = PreferenceManager.getDefaultSharedPreferences(this).getBoolean("cityChanged", false);
// Update if never checked or last update is longer ago than specified threshold
return cityChanged || lastUpdate < 0 || (Calendar.getInstance().getTimeInMillis() - lastUpdate) > NO_UPDATE_REQUIRED_THRESHOLD;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
I'm in a dire situation of finding a solution for speeding up loading data into the RecyclerView. Data load from the server database and populate the row. Each row has a few EditTexts where user enters some values. Within the OnBindViewHolder, each value entered by the user is captured using a text watcher, and then totals are calculated and displayed real-time in the footer of the parent view.(outside the RecyclerView) Also, inside the OnBindViewHolder, a method is called to update a table in the DB, with the values just entered and captured.
So, basically, when each row gets bound, both the DB and the UI get updated. When the data load is huge, loading of the recyclerView is really slow. What I have tried are moving the DB update to a separate thread, using async task to update the DB. But nothing worked. What should I do here?
Adapter's OnBindViewHolder code is displayed below.
public void onBindViewHolder(final MyViewHolder holder, #SuppressLint("RecyclerView") final int position, List<Object> payload) {
//onBindViewHolder(holder,position);
holder.ref = position;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
onBind = true;
// data passed from getAllData method aka all from TempInvoice
SalesInvoiceModel siModel = salesInvoice.get(position);
holder.code.setText(siModel.getCode());
holder.product.setText(siModel.getProduct());
holder.batchNum.setText(siModel.getBatchNumber());
try {
Date date = simpleDateFormat.parse(siModel.getExpiryDate());
holder.expiry.setText(date.toString());
} catch (Exception ex) {
holder.expiry.setText("Error");
}
holder.expiry.setText(siModel.getExpiryDate());
if (siModel.getDiscountRate() > 0) {
holder.unitprice.setText(siModel.getRetailPrice() + "");
} else {
holder.unitprice.setText(siModel.getUnitPrice() + "");
}
holder.stock.setText(siModel.getStock() + "");
holder.lineval.setText(siModel.getLineValue() + "");
if (payload == null || payload.size() == 0) {
holder.shelf.setText(siModel.getShelf() + "");
holder.request.setText(siModel.getRequest() + "");
holder.order.setText(siModel.getOrder() + "");
holder.free.setText(siModel.getFree() + "");
holder.discount.setText(siModel.getDiscountRate() + "");
} else {
for (Object editText : payload) {
//String val = (String)payload.get(0);
String val = (String) editText;
switch (val) {
case SHELF:
if (lostFocus) {
holder.shelf.setText(salesInvoice.get(position).getShelf() + "");
}
break;
case REQUEST:
if (lostFocus) {
holder.request.setText(salesInvoice.get(position).getRequest() + "");
}
break;
case ORDER:
if (lostFocus) {
holder.order.setText(salesInvoice.get(position).getOrder() + "");
}
break;
case FREE:
if (lostFocus) {
holder.free.setText(salesInvoice.get(position).getFree() + "");
}
break;
case DISCOUNT:
if (lostFocus) {
holder.discount.setText(salesInvoice.get(position).getDiscountRate() + "");
}
break;
case LINEVAL:
holder.lineval.setText(salesInvoice.get(position).getLineValue() + "");
break;
default:
onBindViewHolder(holder, position);
break;
}
}
}
//ADD TEXT WATCHERS
holder.shelf.setOnFocusChangeListener(new FocusChangeListener());
holder.shelf.addTextChangedListener(new GenericTextWatcher() {
#Override
public void afterTextChanged(String s) {
int pos = holder.ref;
if (!onBind) {
if (!s.equals("")) {
notifyItemChanged(pos, SHELF);
Log.d(TAG, "inside text change typed shelf_" + s);
salesInvoice.get(pos).setShelf(Integer.parseInt(s + ""));
} else {
salesInvoice.get(pos).setShelf(0);
}
lastUpdatedRow = pos;
}
}
});
holder.request.setOnFocusChangeListener(new FocusChangeListener());
holder.request.addTextChangedListener(new GenericTextWatcher() {
#Override
public void afterTextChanged(String s) {
boolean valHasChanged = false;
boolean freeHasChanged = false;
int pos = holder.ref;
if (!onBind) {
if (!(s.equals(""))) {
int val = Integer.parseInt((s));
int stock = salesInvoice.get(pos).getStock();
// if stock does not have the particular product
if (val > stock) {
val = stock;
valHasChanged = true;
}
salesInvoice.get(pos).setRequest(val);
if (!refresh) salesInvoice.get(pos).setOrder(val);
if (salesInvoice.get(pos).getFree() + salesInvoice.get(pos).getOrder() > salesInvoice.get(pos).getStock()) {
salesInvoice.get(pos).setFree(0);
freeHasChanged = true;
}
} else {
salesInvoice.get(pos).setRequest(0);
}
notifyItemChanged(pos, ORDER);
if (valHasChanged) {
notifyItemChanged(pos, REQUEST);
}
if (freeHasChanged) {
notifyItemChanged(pos, FREE);
}
lastUpdatedRow = pos;
}
}
});
holder.order.setOnFocusChangeListener(new FocusChangeListener());
holder.order.addTextChangedListener(new GenericTextWatcher() {
#Override
public void afterTextChanged(String s) {
boolean valHasChanged = false;
boolean freeHasChanged = false;
int pos = holder.ref;
if (!onBind) {
if (!(s.equals(""))) {
int val = Integer.parseInt(s);
int stock = salesInvoice.get(pos).getStock();
if (val > stock) {
val = stock;
valHasChanged = true;
}
salesInvoice.get(pos).setOrder(val);//make sure we set returnQty before
//checking the total of returnQty and free against stock
if (salesInvoice.get(pos).getOrder() + salesInvoice.get(pos).getFree() > salesInvoice.get(pos).getStock()) {
salesInvoice.get(pos).setFree(0);
freeHasChanged = true;
}
} else {
salesInvoice.get(pos).setOrder(0);
}
if (valHasChanged) {
notifyItemChanged(pos, ORDER);//notify the adapter that value changed and refresh the view mentioned by the string
}
if (freeHasChanged) notifyItemChanged(pos, FREE);
notifyItemChanged(pos, LINEVAL);
lastUpdatedRow = pos;
}
}
});
holder.free.setOnFocusChangeListener(new FocusChangeListener());
holder.free.addTextChangedListener(new GenericTextWatcher() {
#Override
public void afterTextChanged(String s) {
boolean valChanged = false;
int pos = holder.ref;
if (!onBind) {
if ((!s.equals("")) && (!(s.equals("0")))) {
int val = Integer.parseInt(s);
salesInvoice.get(pos).setFree(val);
holder.discount.setEnabled(false);
if (salesInvoice.get(pos).getOrder() + salesInvoice.get(pos).getFree() > salesInvoice.get(pos).getStock()) {
salesInvoice.get(pos).setFree(0);
valChanged = true;
holder.discount.setEnabled(true);
}
} else {
salesInvoice.get(pos).setFree(0);
holder.discount.setEnabled(true);
}
notifyItemChanged(pos, LINEVAL);
if (valChanged) notifyItemChanged(pos, FREE);
holder.setCursor(FREE);
lastUpdatedRow = pos;
}
}
});
holder.discount.setOnFocusChangeListener(new FocusChangeListener());
holder.discount.addTextChangedListener(new GenericTextWatcher() {
#Override
public void afterTextChanged(String s) {
int pos = holder.ref;
if (!(s.equals(salesInvoice.get(pos).getDiscountRate() + ""))) {
if ((!s.equals("")) && (!(s.equals("0"))) && (!(s.equals("0.0"))) && (!(s.equals("0.")))) {
Double rate = Double.parseDouble(s.toString().trim());
Log.i(" RAte ", rate + "");
salesInvoice.get(pos).setDiscountRate(rate);
holder.free.setEnabled(false);
} else {
salesInvoice.get(pos).setDiscountRate(0.0);
holder.free.setEnabled(true);
}
if (!onBind) {
notifyItemChanged(pos, LINEVAL);
lastUpdatedRow = pos;
}
}
}
});
if (position % 2 == 0) {
holder.setColor(Color.LTGRAY);
} else {
holder.setColor(Color.GRAY);
}
onBind = false;
notifyUpdate(); //calling to update the UI
Log.d("ASY", "before db call");
DBAdapterAsync dbAdapter = new DBAdapterAsync(getContextForAdapter);
dbAdapter.execute(salesInvoice.get(holder.ref));
Log.d("ASY", "after db call");
}
//async task class for DB Update
#SuppressLint("StaticFieldLeak")
private class DBAdapterAsync extends AsyncTask<SalesInvoiceModel, Void, String> {
private SQLiteDatabase db;
private DBHelper dbHelper;
DBAdapterAsync(Context context) {
this.dbHelper = new DBHelper(context);
Log.d("ASY", "inside constructor");
}
#Override
protected void onPreExecute() {
try {
db = dbHelper.getWritableDatabase();
} catch (Exception ex) {
ex.printStackTrace();
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
dbHelper.close();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(SalesInvoiceModel... models) {
SalesInvoiceModel model = models[0];
Log.d(TAG, "inside updateInvoiceData_");
Log.d(TAG, "shelf_" + model.getShelf());
Log.d(TAG, "order_" + model.getOrder());
Log.d(TAG, "free_" + model.getFree());
String sql = "UPDATE temp_invoice SET" +
" Shelf=" + model.getShelf() + " , Request=" + model.getRequest()
+ " , OrderQty=" + model.getOrder() + " , Free=" + model.getFree()
+ " , Disc=" + model.getDiscountRate() + " , LineVal=" + model.getLineValue()
+ ", RetailPriceLineVal=" + model.getRetailLineVal()
+ " WHERE _id=" + model.getId();
db.execSQL(sql);
Log.d(TAG, "DB method finished,");
Log.d("ASY", "after do in background");
return null;
}
}
I try to inject some keys in a text field with a InputMethodService.
In my Manifest everything seems alright.
Everytime when I call getCurrentInputConnection() I get null.
My class extends InputMethodService and I start the service.
Can anyone help me? Is there something else I need to do to get the currentInputConnection??
Here is the code:
Its from an open source project called WifiKeyboard
And I try to inject code with the function setText(String text)
package com.example.twolibs;
/**
* WiFi Keyboard - Remote Keyboard for Android.
* Copyright (C) 2011 Ivan Volosyuk
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import java.util.HashSet;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.hardware.input.InputManager;
import android.inputmethodservice.InputMethodService;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.RemoteException;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.ExtractedText;
import android.view.inputmethod.ExtractedTextRequest;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputMethod;
public class WiFiInputMethod extends InputMethodService {
public static final int KEY_HOME = -1000;
public static final int KEY_END = -1001;
public static final int KEY_CONTROL = -1002;
public static final int KEY_DEL = -1003;
#Override
public void onStartInput(EditorInfo attribute, boolean restarting) {
super.onStartInput(attribute, restarting);
// boolean multiline = (attribute.inputType & InputType.TYPE_TEXT_FLAG_MULTI_LINE) != 0;
// Log.d("ivan", "onStartInput "
// + "actionId=" + attribute.actionId + " "
// + "id=" + attribute.fieldId + " "
// + "name=" + attribute.fieldName + " "
// + "opt=" + Integer.toHexString(attribute.imeOptions) + " "
// + "inputType=" + Integer.toHexString(attribute.inputType) + " "
// + "priv=" + attribute.privateImeOptions
// + "multiline=" + multiline);
try {
String text = getText();
} catch (NullPointerException e) {
}
}
ServiceConnection serviceConnection;
#Override
public void onDestroy() {
// Debug.d("WiFiInputMethod onDestroy()");
if (serviceConnection != null)
unbindService(serviceConnection);
serviceConnection = null;
super.onDestroy();
}
PowerManager.WakeLock wakeLock;
HashSet<Integer> pressedKeys = new HashSet<Integer>();
#Override
public void onCreate() {
super.onCreate();
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(
PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "wifikeyboard");
// Debug.d("WiFiInputMethod started");
serviceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName name, IBinder service) {
// Debug.d("WiFiInputMethod connected to HttpService.");
}
//#Override
public void onServiceDisconnected(ComponentName name) {
// Debug.d("WiFiInputMethod disconnected from HttpService.");
}
};
}
#Override
public boolean onEvaluateFullscreenMode() {
return false;
}
void receivedChar(int code) {
wakeLock.acquire();
wakeLock.release();
InputConnection conn = getCurrentInputConnection();
if (conn == null) {
// Debug.d("connection closed");
return;
}
if (pressedKeys.contains(KEY_CONTROL)) {
switch (code) {
case 'a':case 'A': selectAll(conn); return;
case 'x':case 'X': cut(conn); return;
case 'c':case 'C': copy(conn); return;
case 'v':case 'V': paste(conn); return;
}
}
String text = null;
if (code >= 0 && code <= 65535) {
text = new String(new char[] { (char) code } );
} else {
int HI_SURROGATE_START = 0xD800;
int LO_SURROGATE_START = 0xDC00;
int hi = ((code >> 10) & 0x3FF) - 0x040 | HI_SURROGATE_START;
int lo = LO_SURROGATE_START | (code & 0x3FF);
text = new String(new char[] { (char) hi, (char) lo } );
}
conn.commitText(text, 1);
}
#SuppressWarnings("unused")
void receivedKey(int code, boolean pressed) {
if (false) {
for (int key : pressedKeys) {
sendKey(key, false, false);
}
pressedKeys.clear();
resetModifiers();
return;
}
if (pressedKeys.contains(code) == pressed) {
if (pressed == false) return;
// ignore autorepeat on following keys
switch (code) {
case KeyEvent.KEYCODE_ALT_LEFT:
case KeyEvent.KEYCODE_SHIFT_LEFT:
case KeyEvent.KEYCODE_HOME:
case KeyEvent.KEYCODE_MENU: return;
}
}
if (pressed) {
pressedKeys.add(code);
System.out.println("one");
sendKey(code, pressed, false);
} else {
pressedKeys.remove(code);
sendKey(code, pressed, pressedKeys.isEmpty());
}
}
void resetModifiers() {
InputConnection conn = getCurrentInputConnection();
if (conn == null) {
return;
}
conn.clearMetaKeyStates(
KeyEvent.META_ALT_ON | KeyEvent.META_SHIFT_ON | KeyEvent.META_SYM_ON);
}
private long lastWake;
void sendKey(int code, boolean down, boolean resetModifiers) {
System.out.println("two");
/*
long time = System.currentTimeMillis();
if (time - lastWake > 5000) {
wakeLock.acquire();
wakeLock.release();
lastWake = time;
}
*/
InputConnection conn = getCurrentInputConnection();
System.out.println("three");
if (conn == null) {
System.out.println("kacke");
// Debug.d("connection closed");
return;
}
if (code < 0) {
if (down == false) return;
switch (code) {
case KEY_HOME: keyHome(conn); break;
case KEY_END: keyEnd(conn); break;
case KEY_DEL: keyDel(conn); break;
}
return;
}
if (pressedKeys.contains(KEY_CONTROL)) {
switch (code) {
case KeyEvent.KEYCODE_DPAD_LEFT:
if (!down) return;
wordLeft(conn);
return;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (!down) return;
wordRight(conn);
return;
case KeyEvent.KEYCODE_DEL:
if (!down) return;
deleteWordLeft(conn);
return;
case KeyEvent.KEYCODE_FORWARD_DEL:
deleteWordRight(conn);
return;
case KeyEvent.KEYCODE_DPAD_CENTER:
if (!down) return;
copy(conn);
return;
}
}
if (pressedKeys.contains(KeyEvent.KEYCODE_SHIFT_LEFT)) {
switch (code) {
case KeyEvent.KEYCODE_DPAD_CENTER:
if (!down) return;
paste(conn);
return;
}
}
if (code == KeyEvent.KEYCODE_ENTER) {
if (shouldSend()) {
if (!down) return;
Log.d("ivan", "sending submit action");
conn.performEditorAction(EditorInfo.IME_ACTION_SEND);
return;
}
}
// if (pressedKeys.contains(KEY_CONTROL)) {
// if (down == false) return;
// switch (code) {
// case KeyEvent.KEYCODE_A: selectAll(conn); break;
// case KeyEvent.KEYCODE_X: cut(conn); break;
// case KeyEvent.KEYCODE_C: copy(conn); break;
// case KeyEvent.KEYCODE_V: paste(conn); break;
// }
// return;
// }
System.out.println("four");
conn.sendKeyEvent(new KeyEvent(
android.os.SystemClock.uptimeMillis(),
android.os.SystemClock.uptimeMillis(),
down ? KeyEvent.ACTION_DOWN : KeyEvent.ACTION_UP,
code,
0,
(pressedKeys.contains(KeyEvent.KEYCODE_SHIFT_LEFT)
? KeyEvent.META_SHIFT_LEFT_ON : 0) +
(pressedKeys.contains(KEY_CONTROL)? KeyEvent.META_CTRL_ON : 0) +
(pressedKeys.contains(KeyEvent.KEYCODE_ALT_LEFT)
? KeyEvent.META_ALT_LEFT_ON : 0)
));
if (resetModifiers) {
conn.clearMetaKeyStates(
KeyEvent.META_ALT_ON | KeyEvent.META_SHIFT_ON | KeyEvent.META_SYM_ON);
}
}
private boolean shouldSend() {
if (pressedKeys.contains(KEY_CONTROL)) {
// Log.d("ivan", "Control pressed");
return true;
}
EditorInfo editorInfo = getCurrentInputEditorInfo();
if (editorInfo == null) {
// Log.d("ivan", "No editor info");
return false;
}
if ((editorInfo.inputType & InputType.TYPE_CLASS_TEXT) == 0) {
// Log.d("ivan", "Not text, sending enter");
return false;
}
if ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_MULTI_LINE) != 0) {
// Log.d("ivan", "Multi-line, sending ordinary enter");
return false;
}
int action = editorInfo.imeOptions & EditorInfo.IME_MASK_ACTION;
if (action == EditorInfo.IME_ACTION_NONE || action == EditorInfo.IME_ACTION_DONE) {
// Log.d("ivan", "No useful action, sending enter");
return false;
}
// Log.d("ivan", "Useful action to be performed");
return true;
}
private void keyDel(InputConnection conn) {
// if control key used -- delete word right
if (pressedKeys.contains(KEY_CONTROL)) {
deleteWordRight(conn);
return;
}
if (pressedKeys.contains(KeyEvent.KEYCODE_SHIFT_LEFT)) {
cut(conn);
return;
}
conn.deleteSurroundingText(0, 1);
conn.commitText("", 0);
}
private void paste(InputConnection conn) {
conn.performContextMenuAction(android.R.id.paste);
}
private void copy(InputConnection conn) {
conn.performContextMenuAction(android.R.id.copy);
}
private void cut(InputConnection conn) {
conn.performContextMenuAction(android.R.id.cut);
}
public void selectAll(InputConnection conn) {
ExtractedText text = conn.getExtractedText(req, 0);
try {
conn.setSelection(0, text.text.length());
} catch (NullPointerException e) {
// Potentially, text or text.text can be null
}
}
ExtractedTextRequest req = new ExtractedTextRequest();
{
req.hintMaxChars = 100000;
req.hintMaxLines = 10000;
}
private void deleteWordRight(InputConnection conn) {
ExtractedText text = conn.getExtractedText(req, 0);
if (text == null) return;
int end = text.selectionEnd;
String str = text.text.toString();
int len = str.length();
for (; end < len; end++) {
if (!Character.isSpace(str.charAt(end))) break;
}
for (; end < len; end++) {
if (Character.isSpace(str.charAt(end))) break;
}
conn.deleteSurroundingText(0, end - text.selectionEnd);
}
private void deleteWordLeft(InputConnection conn) {
// TODO: what is the correct word deleting policy?
// delete until next space? until next different character type?
ExtractedText text = conn.getExtractedText(req, 0);
if (text == null) return;
int end = text.selectionEnd - 1;
String str = text.text.toString();
for (; end >= 0; end--) {
if (!Character.isSpace(str.charAt(end))) break;
}
for (; end >= 0; end--) {
if (Character.isSpace(str.charAt(end))) break;
}
end++;
conn.deleteSurroundingText(text.selectionEnd - end, 0);
}
private void wordRight(InputConnection conn) {
boolean shift = pressedKeys.contains(KeyEvent.KEYCODE_SHIFT_LEFT);
ExtractedText text = conn.getExtractedText(req, 0);
if (text == null) return;
int end = text.selectionEnd;
String str = text.text.toString();
int len = str.length();
for (; end < len; end++) {
if (!Character.isSpace(str.charAt(end))) break;
}
for (; end < len; end++) {
if (Character.isSpace(str.charAt(end))) break;
}
int start = shift ? text.selectionStart : end;
Log.d("wifikeyboard", "start = " + start + " end = " + end);
conn.setSelection(start, end);
}
private void wordLeft(InputConnection conn) {
boolean shift = pressedKeys.contains(KeyEvent.KEYCODE_SHIFT_LEFT);
ExtractedText text = conn.getExtractedText(req, 0);
if (text == null) return;
int end = text.selectionEnd - 1;
String str = text.text.toString();
for (; end >= 0; end--) {
if (!Character.isSpace(str.charAt(end))) break;
}
for (; end >= 0; end--) {
if (Character.isSpace(str.charAt(end))) break;
}
end++;
int start = shift ? text.selectionStart : end;
Log.d("wifikeyboard", "start = " + start + " end = " + end);
conn.setSelection(start, end);
}
private void keyEnd(InputConnection conn) {
boolean control = pressedKeys.contains(KEY_CONTROL);
boolean shift = pressedKeys.contains(KeyEvent.KEYCODE_SHIFT_LEFT);
ExtractedText text = conn.getExtractedText(req, 0);
if (text == null) return;
int end;
if (control) {
end = text.text.length();
} else {
end = text.text.toString().indexOf('\n', text.selectionEnd);
if (end == -1) end = text.text.length();
}
int start = shift ? text.selectionStart : end;
Log.d("wifikeyboard", "start = " + start + " end = " + end);
conn.setSelection(start, end);
}
private void keyHome(InputConnection conn) {
boolean control = pressedKeys.contains(KEY_CONTROL);
boolean shift = pressedKeys.contains(KeyEvent.KEYCODE_SHIFT_LEFT);
ExtractedText text = conn.getExtractedText(req, 0);
if (text == null) return;
int end;
if (control) {
end = 0;
} else {
end = text.text.toString().lastIndexOf('\n', text.selectionEnd - 1);
end++;
}
int start = shift ? text.selectionStart : end;
Log.d("wifikeyboard", "start = " + start + " end = " + end);
conn.setSelection(start, end);
}
boolean setText(String text) {
// FIXME: need feedback if the input was lost
InputConnection conn = getCurrentInputConnection();
if (conn == null) {
// Debug.d("connection closed");
return false;
}
conn.commitText(text, text.length());
conn.beginBatchEdit();
// FIXME: hack
conn.deleteSurroundingText(100000, 100000);
conn.commitText(text, text.length());
conn.endBatchEdit();
return true;
}
String getText() {
String text = "";
try {
InputConnection conn = getCurrentInputConnection();
ExtractedTextRequest req = new ExtractedTextRequest();
req.hintMaxChars = 1000000;
req.hintMaxLines = 10000;
req.flags = 0;
req.token = 1;
text = conn.getExtractedText(req, 0).text.toString();
} catch (Throwable t) {
}
return text;
}
}
Thank you
I want to swipe between questions with viewpager
1) I'm able to use custom pages like ("text1", "text2", "text3, "text4") with this code:
in pageadapter:
protected static final String[] CONTENT = new String[] { "text1", "text2", "text3, "text4", };
1) But I couldnt get data from database to String like:
new String[] { "myquestion1", "myquestion2", ....... "my lastquestion", }
in my quiz activity:
/**
*
*/
public void initView() {
this.manageView(true);
}
/**
* updates the user interface
*
* #param start whether this is the start of the quiz
*/
#SuppressWarnings("boxing")
public void manageView(final boolean start) {
if (QuizActivity.ll.getChildCount() > 0) {
QuizActivity.ll.removeAllViews();
QuizActivity.ll.addView(QuizActivity.questionText);
}
QuizActivity.warning.setVisibility(View.INVISIBLE);
QuizActivity.warningIcon.setVisibility(View.INVISIBLE);
if (this.q.isReviewing()) {
QuizActivity.warning.setVisibility(View.VISIBLE);
QuizActivity.warningIcon.setVisibility(View.VISIBLE);
if (this.q.getCurrentQuestion().isAnsweredCorrect()) {
QuizActivity.warning.setText(R.string.correct);
QuizActivity.warning.setTextColor(Statics.goodColor);
QuizActivity.warningIcon.setImageResource(R.drawable.correct);
} else {
QuizActivity.warning.setText(R.string.wrong);
QuizActivity.warning.setTextColor(Statics.badColor);
QuizActivity.warningIcon.setImageResource(R.drawable.wrong);
}
}
QuizActivity.back.setEnabled((!start || this.q.isBackAllowed())
&& (!this.q.isFirstQuestion()));
if (this.q.isLastQuestion()) {
QuizActivity.next.setText(R.string.finish);
QuizActivity.next.setCompoundDrawablesWithIntrinsicBounds(null, null,
this.getResources().getDrawable(R.drawable.finish_quiz), null);
} else {
QuizActivity.next.setText(R.string.next);
QuizActivity.next.setCompoundDrawablesWithIntrinsicBounds(null, null,
this.getResources().getDrawable(R.drawable.arrow_right), null);
}
QuizActivity.review.setChecked(this.q.getCurrentQuestion().isMarkedForReview());
if (this.q.isReviewing()) {
QuizActivity.review.setVisibility(View.GONE);
if ((null != this.q.getCurrentQuestion().getExplanation())
&& (this.q.getCurrentQuestion().getExplanation().length() > 0)) {
QuizActivity.explain.setVisibility(View.VISIBLE);
} else {
QuizActivity.explain.setVisibility(View.GONE);
}
}
QuizActivity.progress.setText(this.getString(R.string.q_) + " "
+ this.q.getCurrentQuestionNumber() + "/"
+ this.q.getQuestionCount());
QuizActivity.title.setText(this.q.getCategory().getParentCategoryTitle() + " - "
+ this.q.getCategory().getCategoryTitle());
QuizActivity.questionText.setText(this.q.getCurrentQuestion().getQuestionText());
if (this.q.isShowAmountAnswers()) {
QuizActivity.questionText.append(" (" + this.getString(R.string.select) +
" " + this.q.getCurrentQuestion().getAmountCorrectAnswers() + ")");
}
this.userAnswers = this.q.getCurrentQuestion().getUserAnswers();
this.answers = new LinkedList<CompoundButton>();
if (!this.q.isShowAmountAnswers()
|| (this.q.getCurrentQuestion().getAmountCorrectAnswers() > 1)) {
for (final Answer ans : this.q.getCurrentQuestion().getAnswers()) {
this.answers.add(new CheckBox(this));
this.answers.getLast().setText(ans.getAnswerText());
this.answers.getLast().setId(ans.getAnswerId());
this.answers.getLast().setChecked(this.userAnswers.get(ans.getAnswerId()));
if (this.q.isReviewing()) {
this.answers.getLast().setEnabled(false);
if (ans.isAnswerCorrect()) {
this.answers.getLast().setTextColor(Statics
.goodColor);
} else {
this.answers.getLast().setTextColor(Statics
.badColor);
}
}
QuizActivity.ll.addView(this.answers.getLast());
}
} else {
final RadioGroup rg = new RadioGroup(this);
for (final Answer ans : this.q.getCurrentQuestion().getAnswers()) {
this.answers.add(new RadioButton(this));
this.answers.getLast().setText(ans.getAnswerText());
this.answers.getLast().setId(ans.getAnswerId());
this.answers.getLast().setChecked(this.userAnswers.get(ans.getAnswerId()));
if (this.q.isReviewing()) {
this.answers.getLast().setEnabled(false);
if (ans.isAnswerCorrect()) {
this.answers.getLast().setTextColor(Statics
.goodColor);
} else {
this.answers.getLast().setTextColor(Statics
.badColor);
}
}
this.answers.getLast()
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#SuppressWarnings("synthetic-access")
#Override
public void onCheckedChanged(final CompoundButton buttonView,
final boolean isChecked) {
for (final View rb : QuizActivity.this.answers)
{
((CompoundButton) rb).setChecked(false);
}
buttonView.setChecked(isChecked);
}
});
rg.addView(this.answers.getLast());
}
QuizActivity.ll.addView(rg);
}
QuizActivity.next.setOnClickListener(this);
QuizActivity.back.setOnClickListener(this);
QuizActivity.explain.setOnClickListener(this);
}
so how can I apply my question list to " new String[] {...,...,... } "
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
});