(Android)How to clear keyboard memory in certain situation(Acer Keyboard) - android

In the first place, Thank everyone for coming in and sorry for my poor English, So I describe this situation directly,
I develop with SONY, When I clicked the clear button in EditText, it's working normally!, even I use others phone, like HTC, Oppo,mi.. All's well!
After that I tried to install it in Acer, the clear button still working,
BUT!!!!!
After I clicked the clear button, Next use keyboard again, the data of my first input still here.
The data of my first input.
So, "MyFirstData" will still appear when I input again like
Second-time input situation
I was really confused because I have no idea how to fix it.
So what can I do, clear keyboard data? How?
many thanks!!!!
Code here:
binding.searchView is my editext
binding.searchView.addTextChangedListener(new TextWatcherAdapter());
binding.searchView.setOnEditorActionListener(getSearchEditListener());
channelDialogHelper = new ChannelDialogHelper(this);
}
private TextView.OnEditorActionListener getSearchEditListener() {
return new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
messageResultAdapter.clearAdapter();
shareFileResultAdapter.clearAdapter();
keyword = MessageFactory.getInstance().parseSourceData(v.getText().toString());
if (StringUtil.isEmpty(keyword)) {
return false;
}
hasMessageResult = false;
hasFileResult = false;
if (binding.searchMessageButton.isSelected()) {
searchMessageListener(binding.searchMessageButton);
} else if (binding.searchFileButton.isSelected()) {
searchFileListener(binding.searchFileButton);
}
return true;
}
return false;
}
};
}
TextWatcherAdapter:
public class TextWatcherAdapter implements TextWatcher {
public TextWatcherAdapter() {
}
public void beforeTextChanged(CharSequence var1, int var2, int var3, int var4) {
}
public void onTextChanged(CharSequence var1, int var2, int var3, int var4) {
}
public void afterTextChanged(Editable var1) {
}
}

One possible solution is to remove the exact word(s) using ContentResolver.delete(). Example:
private int deleteWord(String word) {
if (TextUtils.isEmpty(word)) {
return -1;
}
return getContentResolver().delete(UserDictionary.Words.CONTENT_URI,
UserDictionary.Words.WORD + "=?", new String[] { word });
}
And of course, need
<uses-permission android:name="android.permission.WRITE_USER_DICTIONARY" />
defined in the manifest.
Hope this helps.

Related

Accessing an array inside OnKeyListener inner class

I am studying Mobile Application Developer and I am just a beginner. So, forgive me if the question is silly.
I am creating a simple Quiz App. I have MainActivity which act as a welcoming screen.
public class MainActivity extends AppCompatActivity {
private Button startBt; //the user will enter this button to go the SecondActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startBt = findViewById(R.id.startBt);
startBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, SecondActivity.class);
startActivity(i);
}
});
}
}
Then, I have a SecondActivity which suppose to ask the user a question and get the answer as a String and then increment the score if the answer is correct. There is 10 question. So, I want to use a loop to iterate through all questions. Also, inside the loop there is OnKeyListener which indicate when the user press Enter and compare the user answer to the saved answer.
public class SecondActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
String[] questions = getResources().getStringArray(R.array.questions);
String[] answers = getResources().getStringArray(R.array.answers);
TextView questionTv = findViewById(R.id.questionTv);
final EditText answerEt = findViewById(R.id.answerPt);
TextView scoreTv = findViewById(R.id.scoreTv);
int scoreCounter = 0;
for (int i=0; i<10; i++) {
answerEt.setText("");
scoreTv.setText(scoreCounter);
questionTv.setText(questions[i]);
answerEt.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
if (**answerEt**.getText().toString().equals(**answers[i]**)) {
Toast t = Toast.makeText(getApplicationContext(), "Correct",Toast.LENGTH_LONG);
t.show();
**scoreCounter++;**
return true;
}
else
return false;
} else
return false;
}
});
}
}
}
Now, please check the bold part of the code. I cannot access answerEt, scoreCounter, answer[i] because they are not final. They should be final because I am working with an inner class. Here is the problem, if I will make them final, I will not have the ability to modify them. However, scoreCounter should be incremented to show the user score. Also the i should be incremented to iterate through the answer[]. One will say "make them Global". Sadly, I tried this and my program crashed. So, How I can solve this?
Thanks in advance
pass on responsibility to check for correct answer to a separate function.
private boolean checkAnswer(EditText et, final int questionID) {
if (et.getText().toString().equals(answers[questionID])) {
Toast t = Toast.makeText(getApplicationContext(), "Correct", Toast.LENGTH_LONG);
t.show();
scoreCounter++;
return true; // for correct answer.
}
return false; // for incorrect answer.
}
Modify your loop to use above function like this :
for (int i = 0; i < 10; i++) {
final int currentQuestionID = i;
answerEt.setText("");
scoreTv.setText(scoreCounter);
questionTv.setText(questions[i]);
answerEt.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
return checkAnswer((EditText) (v), currentQuestionID);
}
return false;
}
});
}

Android lollipop can`t get keyboard input

I have user keyboard input working on all android versions except on Android Lollipop (5.0).
I have used this to open software keyboard:
public static void OpenKeyBoard(){
MainActivity._Instance.runOnUiThread(new Runnable() {
public void run() {
InputMethodManager imm = (InputMethodManager) MainActivity._Instance.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(MainActivity._Instance.getWindow().getDecorView(), 0);
}
});
}
and i get user input by standard event :
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
I have this code working for all pre Lollipop versions of Android. When I use it on Lollipop, the software keyboard appears, but when I try to click on any letter/number, the keyboard disappears and the method "onKeyDown" doesn`t receive any keycode.
Did anyone had this problem? Any opinion how to solve this?
Thank you.
Try updating your google SDK to the latest, I did and this fixed any issues I have with the keyboard dismissing.
I has this problem too. I managed to solve this by overriding the onLayout, onFocusChanged & onCheckIsTextEditor methods inside WebView. Here's the code that made it work (I generate a webview programmatically):
this.webView = new WebView(context)
{
boolean layoutChangedOnce = false;
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b)
{
if (!layoutChangedOnce)
{
super.onLayout(changed, l, t, r, b);
layoutChangedOnce = true;
}
}
#Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect)
{
super.onFocusChanged(true, direction, previouslyFocusedRect);
}
#Override
public boolean onCheckIsTextEditor()
{
return true;
}
};
this.webView.setFocusable(true);
this.webView.setFocusableInTouchMode(true);
this.webView.requestFocus(View.FOCUS_DOWN);
addView(this.webView);
this issue is not limited to just android applications but also occurs when any keyboard related event is accessed using javascript or jquery within a phone browser.
eg. I have my website which asks a user to enter zip code(numeric characters) on a certain page. Now the problem is when up tap on the input box, the numeric keyboard appears but it allows you to paste alpha-numeric characters in it as well.
Reason searched so far,
Try accessing this through your desktop and also a mobile device running android OS 5.0+ and try different possible keystrokes.
Note:
When you enter any alpha-characters using mobile device with above
mentioned configuration it shows up '229' as the keycode.
When you enter any alpha-characters using a desktop it shows up the
appropriate keycode.
This works for me I have a SurfaceView implements SurfaceHolder.Callback with a thread to do drawing
#Override
public boolean onTouchEvent(MotionEvent event)
{
synchronized (this)
{
mouse.useEvent(event);
}
return true;
}
#Override
public InputConnection onCreateInputConnection(EditorInfo editorinfo) {
BaseInputConnection bic = new BaseInputConnection(this, false);
editorinfo.actionLabel = null;
editorinfo.inputType = InputType.TYPE_NULL;
editorinfo.imeOptions = EditorInfo.IME_FLAG_NO_FULLSCREEN;
bic.finishComposingText();
return bic;
}
#Override
public boolean dispatchKeyEvent(KeyEvent event)
{
input.useEvent(event);
return super.dispatchKeyEvent(event);
}
I have solved this using AlertDialog editText programmatically. Eg:
public void KeyboardTextField(int id){
if (id == 0){
final String title = getStringResourceByName("profile_title");
final String createP = getStringResourceByName("profile_confirm");
final String cancel = getStringResourceByName("profile_cancel");
MainActivity._Instance.ActivityWillBeShown = true;
MainActivity._Instance.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity._Instance);
alert.setCancelable(false);
alert.setTitle(title);
// alert.setMessage(""); // message
// Set an EditText view to get user input
final EditText input = new EditText(MainActivity._Instance);
final int maxLength = 12;
input.setFilters(new InputFilter[] {new InputFilter() {
#Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
if (source != null && blockCharacterSet.contains(("" + source))) {
return "";
}
// TODO Auto-generated method stub
return null;
}
} , new InputFilter.LengthFilter(maxLength)});
//input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_CLASS_NUMBER);
input.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); //turn off txt auto complete
input.setInputType(InputType.TYPE_TEXT_VARIATION_POSTAL_ADDRESS); // type only text,numbers and some special char
alert.setView(input);
//input.setText("Player");
alert.setPositiveButton(createP, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText().toString();
// Do something with value!
if (value.isEmpty()){
value = "Player";
}
nativeName(value);
InputMethodManager imm = (InputMethodManager)getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(input.getWindowToken(), 0);
}
});
alert.setNegativeButton(cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
InputMethodManager imm = (InputMethodManager)getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(input.getWindowToken(), 0);
}
});
alert.show();
};
});
}
And Whenever you need keyboard you just call this function. It works on all Android versions (4.x, 5.x, 6.0)

How to Store value for EditText in Session

In Cart Activity, i am allowing user to Edit Quantity of an item, and also getting changes in Total amount as user does change in Quantity, but here i am facing a small problem, whenever i do click on back button, it will reset my quantity, why?
please see below screen shot:
![enter image description here][1]
For an example, in above screen i have edited Quantity for my product Veggie from 1 to 15 and also getting change in Total, but the problem is once i do click on back button, then i will get again value for Quantity 1 not 15, which i have entered earlier
Please tell me how can i control on this ?
CartAdapter.java:
if(cost.getText().length() > 0)
{
try
{
itemamount = Double.parseDouble(cost.getText().toString());
Log.d("ProductInformationActivity", "ItemAmount :: " + itemamount);
}
catch(NumberFormatException e)
{
itemamount=0.00;
Log.d("ProductInformationActivity", "NumberFormatException :: " + e);
}
}
qty.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
if (!qty.getText().toString().equals("")
|| !qty.getText().toString().equals("")) {
// accept quantity by user
itemquantity = Integer.parseInt(qty.getText()
.toString());
total.setText(new DecimalFormat("##.#").format(itemamount*itemquantity));
}
}
#Override
public void afterTextChanged(Editable s) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
});
return vi;
}
}
Why don't you save your values and populate them in your onCreate()? You can use any of three mechanisms to get what you want.
Shared Preferences
SQLite DB
Application
using SQLite DB looks like the best option considering the functionality you require...
If you are already storing the value and just want to control how the back button works you could use this in your cart activity:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
//Your code
return true; // so the super method doesn't get called
}
return super.onKeyDown(keyCode, event);
}

Using native look and feel of the searchView for actionBarSherlock on old Android versions

I've noticed that there is no working solution that shows how to use filter on a listView items using the actionbar, that works on older Android versions (like 2.3.x).
The only example I've found is in the file "LoaderCursorSupport.java" of the fragments example. However, it only works when the searchView can be created, meaning starting from Android 3.x, as shown in the code:
View searchView=SearchViewCompat.newSearchView(getActivity());
if(searchView!=null)
...
The above bug (or missing feature, whichever way you look at it) still exist even on version 4.2 of actionBarSherlock.
So I've made my own solution, which works great (and I wish the official library could add my fix to it too), but I don't know where to get the "x" button within the editText view that is responsible for clearing the text.
Can anyone please tell me how to get the native look and feel and put it correctly in the code?
Here's a screenshot of what i'm talking about:
For those wish to use this feature, here is my code snippet :
#Override
public boolean onCreateOptionsMenu(final com.actionbarsherlock.view.Menu menu)
{
getSupportMenuInflater().inflate(R.menu.activity_main,menu);
_searchMenuItem=menu.findItem(R.id.menu_item_action_search);
View searchView=SearchViewCompat.newSearchView(this);
if(searchView!=null)
SearchViewCompat.setOnQueryTextListener(searchView,new OnQueryTextListenerCompat()
{
#Override
public boolean onQueryTextChange(final String newText)
{
_listAdapter.getFilter().filter(newText);
return true;
}
#Override
public boolean onQueryTextSubmit(final String query)
{
return super.onQueryTextSubmit(query);
}
});
else
{
searchView=new EditText(this);
searchView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
((EditText)searchView).setHint(R.string.search);
((EditText)searchView).addTextChangedListener(new TextWatcher()
{
String curretTextToFilter =null;
#Override
public void onTextChanged(final CharSequence newText,final int start,final int before,final int count)
{
if(newText==curretTextToFilter)
return;
curretTextToFilter=newText.toString();
_listAdapter.getFilter().filter(curretTextToFilter==null||curretTextToFilter.length()==0 ? null : curretTextToFilter);
}
#Override
public void beforeTextChanged(final CharSequence s,final int start,final int count,final int after)
{}
#Override
public void afterTextChanged(final Editable s)
{}
});
}
final View finalSearchView=searchView;
_searchMenuItem.setOnActionExpandListener(new OnActionExpandListener()
{
#Override
public boolean onMenuItemActionExpand(final MenuItem item)
{
if(finalSearchView instanceof EditText)
{
final InputMethodManager m=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
finalSearchView.requestFocus();
if(m!=null)
m.toggleSoftInput(0,InputMethodManager.SHOW_IMPLICIT);
}
return true;
}
#Override
public boolean onMenuItemActionCollapse(final MenuItem item)
{
if(finalSearchView instanceof EditText)
((EditText)finalSearchView).setText(null);
else _listAdapter.getFilter().filter(null);
return true;
}
});
_searchMenuItem.setActionView(searchView);
//
return true;
}
#Override
public boolean onKeyUp(final int keyCode,final KeyEvent event)
{
if(keyCode==KeyEvent.KEYCODE_SEARCH)
{
_searchMenuItem.expandActionView();
return true;
}
return super.onKeyUp(keyCode,event);
}
Except for the "X" button, I think the rest can be done using a library with a theme, called HoloEverywhere.

How to clear an EditText on click?

In Android how can I make an EditText clear when it's clicked?
E.g., if I have an EditText with some characters in, such as 'Enter Name', when the user clicks on it these characters disappear.
I'm not sure if you are after this, but try this XML:
android:hint="Enter Name"
It displays that text when the input field is empty, selected or unselected.
Or if you want it to do exactly as you described, assign a onClickListener on the editText and set it empty with setText().
Are you looking for behavior similar to the x that shows up on the right side of text fields on an iphone that clears the text when tapped? It's called clearButtonMode there. Here is how to create that same functionality in an Android EditText view:
String value = "";//any text you are pre-filling in the EditText
final EditText et = new EditText(this);
et.setText(value);
final Drawable x = getResources().getDrawable(R.drawable.presence_offline);//your x image, this one from standard android images looks pretty good actually
x.setBounds(0, 0, x.getIntrinsicWidth(), x.getIntrinsicHeight());
et.setCompoundDrawables(null, null, value.equals("") ? null : x, null);
et.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (et.getCompoundDrawables()[2] == null) {
return false;
}
if (event.getAction() != MotionEvent.ACTION_UP) {
return false;
}
if (event.getX() > et.getWidth() - et.getPaddingRight() - x.getIntrinsicWidth()) {
et.setText("");
et.setCompoundDrawables(null, null, null, null);
}
return false;
}
});
et.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
et.setCompoundDrawables(null, null, et.getText().toString().equals("") ? null : x, null);
}
#Override
public void afterTextChanged(Editable arg0) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
});
after onclick of any action do below step
((EditText) findViewById(R.id.yoursXmlId)).setText("");
or
write this in XML file
<EditText
---------- other stuffs ------
android:hint="Enter Name" />
its works fine for me. Hope to you all.
that is called hint in android
use
android:hint="Enter Name"
#Harris's answer is great, I've implemented it as a separate subclass of EditText, which can make it easier to use if your code already adds TextChangedListeners.
Also, I've tweaked it so that, if you already use any Compound Drawables, it leaves them intact.
Code is here, for anyone who needs it:
package com.companyname.your
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
public class ClearableEditText extends EditText {
public String defaultValue = "";
final Drawable imgX = getResources().getDrawable(android.R.drawable.presence_offline ); // X image
public ClearableEditText(Context context) {
super(context);
init();
}
public ClearableEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public ClearableEditText(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
void init() {
// Set bounds of our X button
imgX.setBounds(0, 0, imgX.getIntrinsicWidth(), imgX.getIntrinsicHeight());
// There may be initial text in the field, so we may need to display the button
manageClearButton();
this.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
ClearableEditText et = ClearableEditText.this;
// Is there an X showing?
if (et.getCompoundDrawables()[2] == null) return false;
// Only do this for up touches
if (event.getAction() != MotionEvent.ACTION_UP) return false;
// Is touch on our clear button?
if (event.getX() > et.getWidth() - et.getPaddingRight() - imgX.getIntrinsicWidth()) {
et.setText("");
ClearableEditText.this.removeClearButton();
}
return false;
}
});
this.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
ClearableEditText.this.manageClearButton();
}
#Override
public void afterTextChanged(Editable arg0) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
});
}
void manageClearButton() {
if (this.getText().toString().equals("") )
removeClearButton();
else
addClearButton();
}
void addClearButton() {
this.setCompoundDrawables(this.getCompoundDrawables()[0],
this.getCompoundDrawables()[1],
imgX,
this.getCompoundDrawables()[3]);
}
void removeClearButton() {
this.setCompoundDrawables(this.getCompoundDrawables()[0],
this.getCompoundDrawables()[1],
null,
this.getCompoundDrawables()[3]);
}
}
If you want to have text in the edit text and remove it like you say, try:
final EditText text_box = (EditText) findViewById(R.id.input_box);
text_box.setOnFocusChangeListener(new OnFocusChangeListener()
{
#Override
public void onFocusChange(View v, boolean hasFocus)
{
if (hasFocus==true)
{
if (text_box.getText().toString().compareTo("Enter Text")==0)
{
text_box.setText("");
}
}
}
});
Be careful when setting text with an onClick listener on the field you are setting the text. I was doing this and setting the text to an empty string. This was causing the pointer to come up to indicate where my cursor was, which will normally go away after a few seconds. When I did not wait for it to go away before leaving my page causing finish() to be called, it would cause a memory leak and crash my app. Took me a while to figure out what was causing the crash on this one..
Anyway, I would recommend using selectAll() in your on click listener rather than setText() if you can. This way, once the text is selected, the user can start typing and all of the previous text will be cleared.
pic of the suspect pointer: http://i.stack.imgur.com/juJnt.png
//To clear When Clear Button is Clicked
firstName = (EditText) findViewById(R.id.firstName);
clear = (Button) findViewById(R.id.clearsearchSubmit);
clear.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.clearsearchSubmit);
firstName.setText("");
}
});
This will help to clear the wrong keywords that you have typed in so instead of pressing backspace again and again you can simply click the button to clear everything.It Worked For me. Hope It Helps
Code for clearing up the text field when clicked
<EditText android:onClick="TextFieldClicked"/>
public void TextFieldClicked(View view){
if(view.getId()==R.id.editText1);
text.setText("");
}
For me the easiest way...
Create an public EditText, for Example "myEditText1"
public EditText myEditText1;
Then, connect it with the EditText which should get cleared
myEditText1 = (EditText) findViewById(R.id.numberfield);
After that, create an void which reacts to an click to the EditText an let it clear the Text inside it when its Focused, for Example
#OnClick(R.id.numberfield)
void textGone(){
if (myEditText1.isFocused()){
myEditText1.setText("");
}
}
Hope i could help you, Have a nice Day everyone
((EditText) findViewById(R.id.User)).setText("");
((EditText) findViewById(R.id.Password)).setText("");
For kotlin's friends:
edtxt1.onFocusChangeListener = OnFocusChangeListener { _, hasFocus ->
if (hasFocus) {
edtxt1.text = ""
}
}

Categories

Resources