creating a chat activity in android - java

After declaring and creating the textWatcher object, I would like to disable the send button and set it to gray if the chatText (edit text) is empty
I think it's a problem of ranking. Please help.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
list = (ListView)findViewById(R.id.listView);
list.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
chatText = (EditText)findViewById(R.id.editText);
//chatText.setOnKeyListener(this);
me = true;
send = (Button)findViewById(R.id.button);
change = (Button)findViewById(R.id.button2);
list.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
adp = new TheAdapter(getApplicationContext(),R.layout.chat);
list.setAdapter(adp);
chatText.addTextChangedListener(textWatcher);
checkFieldsForEmptyValues();
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
envoyer();
}
});
change.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
me = !me;
if (!me) {
change.setText(R.string.sender2);
} else {
change.setText(R.string.sender);
}
}
});
}
public void envoyer(){
adp.add(new messages(me, chatText.getText().toString()));
chatText.setText("");
}
private void checkFieldsForEmptyValues(){
String s1 = chatText.getText().toString();
if (s1.length() < 0 ) {
send.setEnabled(false);
} else {
send.setEnabled(true);
send.setBackgroundColor(Color.BLUE);
//send.setBackgroundColor((getResources().getColor(R.color.blue)));
}
}

In the onTextChanged is where you would check to see if the text field is empty:
chatText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() > 0) { //enable}
else if (s.length() == 0 { //disable }
In your code, you have if (s1.length() < 0 ) which I don't think will ever be true because the text size will never be less than 0.

// Disable on init
send.setEnabled(false);
// add text changer
chatText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Enable when input is != null and not empty. You can check string lenght too
send.setEnabled(s != null && !s.toString().isEmpty());
}
#Override
public void afterTextChanged(Editable s) {
}
});
disable button before and add textwatch. You can also check if edittext value is not empty or verify string length.
I hope it will help you

Related

How do I write java code, to display the name automatically when after inputting id or number?

based on the image below, I have NIK & NAMA fields. the concept is when I fill in the NIK field then I press the GET button it will display the name(NAMA FIELD)
Picture : Menu add
Database structure example
NIK
NAMA
96296
Farrasta
94878
Alfian
Java class
btnGet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NikKry = etNik.getText().toString();
getNama(); // THE FUNCTION
}
});
private void getNama(){
APIRequestData armNama = RetroMaster.konekRetrofit().create(APIRequestData.class);
Call<ResponseMaster> tampilNama = armNama.ardGetNama(NikKry);
tampilNama.enqueue(new Callback<ResponseMaster>() {
#Override
public void onResponse(Call<ResponseMaster> call, Response<ResponseMaster> response) {
// HOW TO CODE PROPERLY ?
}
#Override
public void onFailure(Call<ResponseMaster> call, Throwable t) {
}
});
}
PHP file
<?php
include ("koneksi.php");
$response = array();
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$NIK = $_POST["NIK"];
$query = "SELECT NAMA FROM MASTER_KRY WHERE NIK = '$NIK'";
$eksekusi = oci_parse($conn, $query);
$cek = oci_execute($eksekusi);
if($cek > 0){
$response["data"] = array();
while($ambil = oci_fetch_object($eksekusi)){
$F["NAMA"] = $ambil->NAMA;
array_push($response["data"], $F);
}
}else{
$response["pesan"] = "Data tidak tersedia";
}
}
else{
$response["pesan"] = "*&*%4668%*%^$%#*&*(()%$!##%";
}
echo json_encode($response);
oci_close($conn);
?>
If you used EditText then this method will be help you to notify when text change in EditText.
editTextObject.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
// here you get text via "s.toString();"
NikKry = s.toString();
getNama();
}
});
If you used AutoCompleteTextView then this method will be help you like:
autoCompleteTextView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
NikKry = yourArrayList.get(position).getText().toString();
getNama();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
This depends on your entity of ResponseMaster. If the entity has field Nama and getter setter exists, you can use below:
if(response.isSuccessful()){
edNama.setText(response.body().getNama());
}else{
// show toast or log error
}

Change button's text in AlertDialog

I need to change positive button's text of an AlertBox from nothing to OK or Add according to the entered text. I have the following code for the AlertBox creation and displaying:
public void show() {
View inputView = LinearLayout.inflate(mContext, R.layout.goal_tag_input, null);
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setView(inputView);
mInput = inputView.findViewById(R.id.goal_tag_input);
mInput.addTextChangedListener(mTagNameTextWatcher);
List<Tag> availableTags = AppDatabase.getInstance(mContext).tagDao().getAll();
mAvailableTagLabels = new ArrayList<>();
for (Tag tag : availableTags) {
mAvailableTagLabels.add(tag.getName());
}
ArrayAdapter<String> inputAdapter = new ArrayAdapter<>(mContext,
android.R.layout.select_dialog_item, mAvailableTagLabels);
mInput.setAdapter(inputAdapter);
builder.setCancelable(true);
builder.setPositiveButton("", mAddTagClickListener);
builder.setNegativeButton(R.string.Cancel, null);
mDialog = builder.create();
mDialog.show();
}
Also I have a TextWatcher implementation:
private TextWatcher mTagNameTextWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
#Override
public void afterTextChanged(Editable s) {
String tagName = mInput.getText().toString();
if (tagName.trim() != "") {
Button buttonPositive = mDialog.getButton(DialogInterface.BUTTON_POSITIVE);
if (mAvailableTagLabels.contains(tagName)) {
buttonPositive.setText(R.string.OK);
} else {
buttonPositive.setText(R.string.Add);
}
}
}
};
During debugging I observed that the text value of the buttonPositive is changed appropriately, but it is not reflected in the interface. Do you have any ideas why is it so? I checked this answer but it didn't help.
Well, it appeared that the problem was in the setting a positive button using the AlertDialog builder here: builder.setPositiveButton("", mAddTagClickListener);. Apparently, a button is not created if you pass an empty string as the first argument. The minute I tried to change it to (at least) one-space-string - everything began to work as expected.Later on I changed the approach to enabling/disabling the button.
Well you can try this
public void show() {
View inputView = LinearLayout.inflate(AppIntroActivity.this, R.layout.goal_tag_input, null);
AlertDialog.Builder builder = new AlertDialog.Builder(AppIntroActivity.this);
builder.setView(inputView);
final EditText mInput =(EditText) inputView.findViewById(R.id.goal_tag_input);
final Button buttonPositive = (Button) inputView.findViewById(R.id.button_id);
mInput.addTextChangedListener( new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
#Override
public void afterTextChanged(Editable s) {
String tagName = mInput.getText().toString();
if (tagName.trim() != "") {
if (mAvailableTagLabels.contains(tagName)) {
buttonPositive.setText(R.string.OK);
} else {
buttonPositive.setText(R.string.Add);
}
}
}
};);
List<Tag> availableTags = AppDatabase.getInstance(mContext).tagDao().getAll();
mAvailableTagLabels = new ArrayList<>();
for (Tag tag : availableTags) {
mAvailableTagLabels.add(tag.getName());
}
ArrayAdapter<String> inputAdapter = new ArrayAdapter<>(mContext,
android.R.layout.select_dialog_item, mAvailableTagLabels);
mInput.setAdapter(inputAdapter);
builder.setCancelable(true);
builder.setPositiveButton("", mAddTagClickListener);
builder.setNegativeButton(R.string.Cancel, null);
mDialog = builder.create();
mDialog.show();
}

Overwrite text in EditText that has only 1 char is not working

I have multiple EditText views , each EditText view can contain only 1 char.
I need to make this rule - if I focus on one EditText , and it already has some text inside - then overwrite it . Also - if I press on delete key - I need the text to be cleared inside that view.
Then - I am checking if the EditText views has 1 empty cell - if not - checking if the EditText views has the correct letters.
I could have managed to make the clear button work, but I can not make the overwrite.
I did tried to use the TextWatcher , but it didn't work for me.
The EditText views are created dynamically .
Here is my code :
Answer.java
public class Answer {
String answer;
int answer_length;
int cell_margin=10;
int cell_size=180;
EditText[] EditTextArray;
public Answer(RelativeLayout rLayout1, Context context , String answer) {
this.answer = answer;
answer_length = answer.length();
if (answer_length>6){
cell_margin = 4;
cell_size = 110;
}
EditTextArray = new EditText[answer_length];
AnswerCell EditTextToSeeFirst = new AnswerCell(context,cell_size);
setListener(EditTextToSeeFirst);
EditTextArray[0] = EditTextToSeeFirst;
RelativeLayout.LayoutParams fparams = new RelativeLayout.LayoutParams
(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
fparams.setMargins(cell_margin,0,cell_margin,0);
rLayout1.addView(EditTextToSeeFirst, fparams);
for (int i = 1; i<answer_length ; i++){
RelativeLayout.LayoutParams lparams = new RelativeLayout.LayoutParams
(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lparams.addRule(RelativeLayout.LEFT_OF, EditTextArray[i-1].getId());
lparams.setMargins(cell_margin,0,cell_margin,0);
AnswerCell newEditText = new AnswerCell(context,cell_size);
setListener(newEditText);
EditTextArray[i] = newEditText;
rLayout1.addView(EditTextArray[i], lparams);
}
rLayout1.setGravity(Gravity.CENTER );
}
public void setListener(AnswerCell ac){
ac.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Log.d("test","test");
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
goToNextAvailableCell();
}
});
}
public void goToNextAvailableCell(){
for (int i = 0; i<answer_length ; i++) {
if(EditTextArray[i].getText().toString().matches("")){
EditTextArray[i].requestFocus();
return;
}
}
//Did not found empty cell
checkCorrectAnswer();
}
private void checkCorrectAnswer(){
String tryAnswer = "";
for (int i = 0; i<answer_length ; i++) {
tryAnswer += EditTextArray[i].getText().toString();
}
if (tryAnswer.matches(answer)){
Log.d("Correct !!","Correct Answer");
}
}
}
AnswerCell.java
public class AnswerCell extends EditText{
public AnswerCell(final Context context, int cell_size) {
super(context);
this.setId(View.generateViewId());
this.setBackgroundResource(R.color.answerCellBackground);
this.setHeight(cell_size);
this.setWidth(cell_size);
this.setFilters(new InputFilter[] {new InputFilter.LengthFilter(1)});
this.setCursorVisible(false);
this.setGravity(Gravity.CENTER);
this.setOnFocusChangeListener( new View.OnFocusChangeListener(){
public void onFocusChange( View view, boolean hasfocus){
if(hasfocus){
view.setBackgroundResource( R.drawable.answer_cell_has_focus);
}
else{
view.setBackgroundResource( R.drawable.answer_cell_lost_focus);
}
}
});
this.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
//You can identify which key pressed buy checking keyCode value with KeyEvent.KEYCODE_
if(keyCode == KeyEvent.KEYCODE_DEL) {
((EditText)v).setText("");
return true;
}
return false;
}
});
}
}
thanks !
It will work with this code
TextWatcher watcher = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//YOUR CODE
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//YOUR CODE
}
#Override
public void afterTextChanged(Editable s) {
String outputedText = s.toString();
// mOutputText.setText(outputedText);
}
};
Then add this in oncreate
mInputText.addTextChangedListener(watcher);
e2.addTextChangedListener(watcher);
e3.addTextChangedListener(watcher);
e4.addTextChangedListener(watcher);

How to get int value from one method to another

I need to carry my int value from one method to another, but I didnt find any solution. One method counts number of objects and the number needs to be "delivered" to another and check, if the count equals to something.
Do you have any idea, how to do it?
Check my codes below:
#Override
protected void onPostExecute(Void result) {
ParseQuery<Animal> query = ParseQuery.getQuery(Animal.class);
query.countInBackground(callcount = new CountCallback(){
public void done(int count, ParseException e) {
if (e == null) {
Log.v("count is" + count, "count is");
//I need to export int count from "done" method to another
} else {
}
}
});
}
And the secont method, which has to recieve that value and use it:
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
//i need to set int count from method above here
int threshold = 1;
int counter = mListView.getCount();
if (scrollState == SCROLL_STATE_IDLE) {
if (mListView.getLastVisiblePosition() >= counter - threshold) {
updateData();
}
}
Whole code:
public class Fragment1 extends Fragment {
static ListView mListView;
static AnimalAdapter mAdapter;
static ProgressBar mProgressBar;
static EditText mEditText;
static LayoutInflater inflater;
CountCallback callcount;
int g_count = 0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.animalsfrag, container, false);
mListView = (ListView)rootView.findViewById(R.id.animal_list);
View header = getActivity().getLayoutInflater().inflate(R.layout.header, null);
header.setPadding(2, 8, 4, 2);
mListView.setVisibility(View.INVISIBLE);
mListView.requestFocus();
mListView.addHeaderView(header);
View footie = getActivity().getLayoutInflater().inflate(R.layout.footer, null);
mListView.addFooterView(footie);
footie.setVisibility(View.INVISIBLE);
mProgressBar = (ProgressBar) rootView.findViewById (R.id.loading_animals);
mProgressBar.setVisibility(View.VISIBLE);
RemoteDataTask task = new RemoteDataTask();
task.execute();
return rootView;
}
public void updateData() {
mListView = (ListView)getView().findViewById(R.id.animal_list);
final ParseQuery<Animal> query = ParseQuery.getQuery(Animal.class);
query.setCachePolicy(CachePolicy.NETWORK_ONLY);
query.orderByAscending("animal");
query.setLimit(mListView.getCount() + 5);
Log.v("updateData", "uploading data from Parse.com");
query.findInBackground(new FindCallback<Animal>() {
#Override
public void done(List<Animal> animals, ParseException error) {
if(animals != null){
mAdapter.clear();
mProgressBar = (ProgressBar) getView().findViewById (R.id.loading_animals);
mProgressBar.setVisibility(View.INVISIBLE);
RelativeLayout footie = (RelativeLayout) getView().findViewById(R.id.footerview);
footie.setVisibility(View.VISIBLE);
mAdapter.clear();
for (int i = 0; i < animals.size(); i++) {
mAdapter.add(animals.get(i));
}
}
}
}); }
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute(); }
#Override
protected Void doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(Void result) {
ParseQuery<Animal> query = ParseQuery.getQuery(Animal.class);
query.countInBackground(callcount = new CountCallback(){
public void done(int count, ParseException e) {
if (e == null) {
Log.v("count is" + count, "count is");
if (mListView.getCount() == count) {
Log.v("all loaded", "executed");
g_count=count;
}
} else {
// The request failed
}
}
});
Log.v("onpostexecute", "executing");
mListView = (ListView) getView().findViewById(R.id.animal_list);
if(mListView.getCount() == 0){
updateData();
}
mEditText = (EditText) getView().findViewById(R.id.search_animal);
mAdapter = new AnimalAdapter(getActivity(), new ArrayList<Animal>());
mListView.setVisibility(View.VISIBLE);
mListView.setTextFilterEnabled(true);
mListView.setAdapter(mAdapter);
mListView.setOnScrollListener(new OnScrollListener() {
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
}
#Override
public void onScrollStateChanged(AbsListView view,
int scrollState) {
int threshold = 1;
int counter = mListView.getCount();
if (scrollState == SCROLL_STATE_IDLE) {
if (mListView.getLastVisiblePosition() >= counter
- threshold){
updateData();
Log.v("count", "count is" + g_count);
}
}
if (SCROLL_STATE_TOUCH_SCROLL == scrollState) {
View currentFocus = getActivity().getCurrentFocus();
if(currentFocus != null) {
currentFocus.clearFocus();
}
}
}
});
mEditText.addTextChangedListener(new TextWatcher(){
#Override
public void afterTextChanged(Editable s) {}
#Override
public void beforeTextChanged(CharSequence s,
int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
System.out.println("Text ["+s+"]");
mAdapter.getFilter().filter(s.toString());
}
});
}
}
}
I'd be glad for any advice.
Thanks in advance.
If you are not calling function from another then you need to create a global variable.
Declare a variable just after your class declaration i.e.
int g_count = 0;
then in
public void done(int count, ParseException e) {
if (e == null) {
Log.v("count is" + count, "count is");
g_count=count;
}
Then in second fucntion
public void onScrollStateChanged(AbsListView view, int scrollState) {
int count=g_count; \\you dont really need to declare this, just use g_count
int threshold = 1;
int counter = mListView.getCount();
if (scrollState == SCROLL_STATE_IDLE) {
if (mListView.getLastVisiblePosition() >= counter - threshold) {
updateData();
}
}

Android: how to enforce minimum values in form

I have a form in an Android application used for setting up matches for a particular sport. I am able to successfully validate the inputs to exclude stuff (using TextWatcher), but not to enforce minimum input.
Although there is a means within XML to have minimum input in a certain field, I would prefer to do this programatically. Moreover, someone could still just ignore the fields altogether and just press the button to start the match (will result in application crashing).
If anyone has any suggestions I would really appreciate it - there doesn't seem to be a great deal of information about this available online (or I've been looking the wrong way).
I've excluded all but two fields in the form (teamA name and matchlength) for the sake of simplicity (Strings and ints are the only input "types").
public class MatchConfig extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_match_config);
// Show the Up button in the action bar.
setupActionBar();
final Context context = getApplicationContext();
final EditText teamA = (EditText) findViewById(R.id.teamA_editText); //Team A input
teamA.addTextChangedListener(new TextWatcher(){
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{}
#Override
public void beforeTextChanged(CharSequence s,int start,int count,int after)
{}
#Override
public void afterTextChanged(Editable s) //Team A validation
{
String filtered_str = s.toString();
if (filtered_str.matches(".*[^A-Za-z^0-9].*")) { //if not alphanumeric
filtered_str = filtered_str.replaceAll("[^A-Za-z^0-9]", "");
s.clear();
s.append(filtered_str);
// s.insert(0, filtered_str);
Toast.makeText(context, //warning Toast
"Only letters and numbers are allowed!",
Toast.LENGTH_SHORT).show();
}
}
});
final EditText matchlength = (EditText) findViewById(R.id.stones_editText); //matchlength input
matchlength.addTextChangedListener(new TextWatcher(){
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{}
#Override
public void beforeTextChanged(CharSequence s,int start,int count,int after)
{}
#Override
public void afterTextChanged(Editable s) //matchlength validation
{
int no=Integer.parseInt(s.toString());
if(no>999)
{
s.replace(0,s.length(), "999");
Toast.makeText(context,
"999 minutes is max length!",
Toast.LENGTH_SHORT).show();
}
}
});
final EditText location = (EditText) findViewById(R.id.location_editText);
Button start = (Button) findViewById(R.id.start_button);
start.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent theIntent = new Intent(MatchConfig.this, MatchTimer.class);
theIntent.putExtra("teamAvar", teamA.getText().toString());
theIntent.putExtra("matchlengthVar", Integer.parseInt(matchlength.getText().toString()));
startActivity(theIntent);
//this finish() will close the MatchConfig Activity when start button will be pressed
finish();
}
});
Check the lengths when you click the start button:
if(teamA.getText().length() < 5){ //5 char min
//Show error
}
else{
//Do match
}

Categories