I retrieve some phones and emails of a contact via JSONarray, for every one of this elements it creates a new EditText (with the phone or email).
I want to know how to update my JSONobject if user change the phone number, or an email, after that I want to add this JSONobject's to a JSONarray to post to my service.
This is the code where I put elements in EditText's:
try {
multiplesArray = new JSONArray(multiples);
//multiplesUpdatedArray = new JSONArray();
System.out.println(multiplesArray.toString(2));
for (int i=0; i<multiplesArray.length(); i++) {
JSONObject contact = new JSONObject();
String type = multiplesArray.getJSONObject(i).getString("tipo");
String data = multiplesArray.getJSONObject(i).getString("texto");
String id = multiplesArray.getJSONObject(i).getString("id");
if (type.equals("phone")) {
final EditText etPhoneItem = new EditText(this);
etPhoneItem.setText(data);
viewPhonesContainer.addView(etPhoneItem);
} else if (type.equals("email")) {
final EditText etEmailItem = new EditText(this);
etEmailItem.setText(data);
viewEmailContainer.addView(etEmailItem);
}
contact.put("tipo", type);
contact.put("id", id);
contact.put("texto", data);
contact.put("cat", "");
contact.put("cat_id", "");
/*multiplesUpdatedArray.put("tipo");
multiplesUpdatedArray.put(type);
multiplesUpdatedArray.put("id");
multiplesUpdatedArray.put(id);
multiplesUpdatedArray.put("texto");
multiplesUpdatedArray.put(data);*/
}
} catch (JSONException e) {
e.printStackTrace();
}
I try some code with "setOnFocusChangeListener" but it didn't work :-(
Thanks in advance!
Use addTextChangeListener .
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence pCode, int start, int before, int count) {
// change your JSONObject
jsobObject.put("key", "value");
}
#Override
public void afterTextChanged(Editable s) {
}
});
You can do it.
etPhoneItem.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) {
if (s.length() != 0) {
try {
contact.put("number", s.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
Simply you can use textView.addTextChangedListener(yourTextWatcherListener) to get the text when user changes the text. But why update that text in json frequetly, because using TextWatcher you will endup updating the json for each and every character you enter. Updating json frequently is very expensive and very bad practice. Instead of using textwatch listener just form the json when you press the post button.
If you are very clear that you are going to update it frequently, then create pojo classes according to the json structure. Updating the variables of the class is not expensive. Convert the pojo class to json using Jackson when editing is done.
JSON to POJO
Related
Is there a way to capture text once # pressed until spacebar is pressed in EditText? Thanks in advance for your help.
First attach addTextChangedListener to your edittext and call a method which will match a particular condition like below:
EditText editText = (EditText)findViewById(R.id.editText);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try {
String capturedString = getText(s);
} catch (Exception e) {
e.printStackTrace();
}
}
});
The above code will try to populate capturedString everytime a new character is added to the edittext field.
Now write another function getText() like below:
public String getText(String s) {
String startChar = "#";
String endChar = " ";
String output = getStringBetweenTwoChars(s, startChar, endChar);
System.out.println(output);
}
This method will match the provided string for # and space. If found, it will return the captured string if not found, it will throw an error (This error will be captured in catch block of the above code)
Now finally, write the below function which will intake a character sequence and two charecters and match the charecter sequence with the provided charecters and return the string between them:
public String getStringBetweenTwoChars(String input, String startChar, String endChar) {
try {
int start = input.indexOf(startChar);
if (start != -1) {
int end = input.indexOf(endChar, start + startChar.length());
if (end != -1) {
return input.substring(start + startChar.length(), end);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return input;
}
Hope this helps :)
I have tried to search place on map by taking input from edit text, I have two edit text; one is for source location and another is for destination, when user input source destination and move to the next (or we can say on focus lost) than "the place entered by user is point out with marker on the map".
But here when I input GUJRAT UNIVERSITY than it takes GUJRAT and UNIVERSITY as Different different VALUE.
et.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) {
// findPlaceWaypoints();
}
#Override
public void afterTextChanged(Editable s) {
findPlaceWaypoints();
}
});
but it search every word i.e. MADHYA PRADES then it search MADHYA and PRADES and every possible words related to MADHYA PRADES. I want to all that text as ONE VALUE which is typed in EDIT TEXT.
This is my findPlaceWaypoints method:
private void findPlaceWaypoints() {
String location = et.getText().toString().toLowerCase();
if (location == null || location.equals("")) {
// Toast.makeText(getBaseContext(), "No Place is entered", Toast.LENGTH_SHORT).show();
return;
}
String url = "https://maps.googleapis.com/maps/api/geocode/json?";
try {
// encoding special characters like space in the user input place
location = URLEncoder.encode(String.valueOf(location), "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String address = "address=" + location;
String sensor = "sensor=true";
// url , from where the geocoding data is fetched
url = url + address + "&" + sensor;
// Instantiating DownloadTask to get places from Google Geocoding service
// in a non-ui thread
DownloadTask downloadTask = new DownloadTask();
// Start downloading the geocoding places
downloadTask.execute(url);
}
try this it may helps you:
edSearch.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) {
String strname = edSearch.getText().toString().toLowerCase();
}
#Override
public void afterTextChanged(Editable s) {
}
});
I don't think it has anything to do with edittext, it has to do with the geocoding api. What it usually sends in response is an array of objects(Places) like the template below.
results[]: {
types[]: string,
formatted_address: string,
address_components[]: {
short_name: string,
long_name: string,
postcode_localities[]: string,
types[]: string
},
partial_match: boolean,
place_id: string,
postcode_localities[]: string,
geometry: {
location: LatLng,
location_type: GeocoderLocationType
viewport: LatLngBounds,
bounds: LatLngBounds
}
}
These objects are all the places that matches the query(i.e. MADHYA PRADES, MADHYA, PRADES).
What you can check for the exact match is the field named "partial_match" in the response object. It is an exact match if partial_match is false, partial match otherwise.
Hope this helps.
I want to develop a dynamic AutoCompleteTextView for Android that populate with JSON data retrieved from MySQL database. Basically it is not a hard task but where I am facing problem? I am inspired by the jQuery Autocomplete option where dynamically fetch data after input letters. But android AutoCompleteTextView is pre-populated with all JSON data.
I am trying to query from millions of data which is really hard to store. Is there any way to search database for the input dynamically?
E.g:
Such as if user input "a" then it will retrieve the best result for "a". Then if user type "ab" it will be refreshed and populated with new results from database.
Thanks
I'll give you just a general overview only for your task Which looks like this,
public List<String> suggest; //List of suggestions
autoComplete.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable editable) {
// TODO Auto-generated method stub
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
String newText = s.toString();
new getJson().execute(newText);
}
});
getJson AsyncTask -> For retrieving new values from server
class getJson extends AsyncTask<String,String,String>{
#Override
protected String doInBackground(String... key) {
String newText = key[0];
newText = newText.trim();
newText = newText.replace(" ", "+");
try{
//Codes to retrieve the data for suggestions
suggest = new ArrayList<String>();
JSONArray jArray = new JSONArray(data);
for(loop the array){
String SuggestKey = //retrieve values by iterating;
suggest.add(SuggestKey);
}
}catch(Exception e){
Log.w("Error", e.getMessage());
}
//Populate suggestions
runOnUiThread(new Runnable(){
public void run(){
aAdapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.item,suggest);
autoComplete.setAdapter(aAdapter);
aAdapter.notifyDataSetChanged();
}
});
return null;
}
See here for the detail info.
I want to use AutoCompleteTextView with Geocoder, but when I start typing suggestions do not pop up.
I do not get why suggestions do not pop up? Is there any solution to this?
Here is my code:
ArrayList<String>addressList = new ArrayList<String>();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1, addressList);
autoComplete.setAdapter(adapter);
autoComplete.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(final CharSequence s, int start, int before, int count) {
getAddressInfo(getActivity(), location, s.toString());
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
private void getAddressInfo(Context context, Location location, String locationName){
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
try {
List<Address> a = geocoder.getFromLocationName(locationName, 5);
for(int i=0;i<a.size();i++){
String city = a.get(0).getLocality();
String country = a.get(0).getCountryName();
String address = a.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
addressList.add(address+", "+city+", "+country);
}
} catch (IOException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
From what I can tell from the code you provided it looks like you may have forgotten to set a threshold on the AutoCompleteTextView that you are using. The threshold determines how many characters a user must type before the suggestions will appear; if you do not set a threshold no results will ever be shown.
Try doing this before setting your adapter:
public void setupAutoCompleteTextView(AutoCompleteTextView autoCompleteTextView) {
ArrayAdapter<String> adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, addressList);
autoCompleteTextView.setThreshold(1);
autoCompleteTextView.setAdapter(adapter);
autoCompleteTextView.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(final CharSequence s, int start, int before, int count) {
getAddressInfo(MainActivity.this, s.toString());
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
private void getAddressInfo(Context context, String locationName){
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
try {
List<Address> a = geocoder.getFromLocationName(locationName, 5);
for(int i=0;i<a.size();i++){
String city = a.get(i).getLocality();
String country = a.get(i).getCountryName();
String address = a.get(i).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
addressList.add(address+", "+city+", "+country);
}
} catch (IOException e) {
e.printStackTrace();
}
}
Hope that helps!
As an user is typing in an AutoCompleteTextView, I want to get some results from an webservice and display them in the box.
For this I declared globally
ArrayAdapter<String> adapter;
autoCompleteText;
ArrayList<String> searchList;
I put this in my onCreate(). searchList is an ArrayList where I will get the results from the web service. Search() is my webservice search. I want it to search after the user typed at least 3 chars so that I used a TextWatcher on the field.
adapter = new ArrayAdapter<String>(MyActivity.this
, android.R.layout.simple_list_item_1, searchList);
autoCompleteText.setAdapter(adapter);
autoCompleteText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
if (s.length() >= 3) {
new Search().execute(null, null, null);
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
Method from Search() - GET request in AsyncTask where I update my searchList
#Override
protected void onPostExecute(final Void unused) {
dlg.dismiss();
if (result != null) {
try {
JSONObject myJson = new JSONObject(result.substring(4));
JSONObject resp = myJson.getJSONObject("response");
for (Iterator<String> iterator = resp.keys(); iterator.hasNext();) {
String key = iterator.next();
System.out.println(key + " = " + resp.getString(key));
if(! searchList.contains(resp.getString(key)))
searchList.add(resp.getString(key));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
I would prefer to use ArrayAdapter and not a CustomAdapter. Any ideas?
Try calling notifyDataSetChanged() in onPostExecute() after changing the list.
This is how I update my AutoCompleteTextView:
String[] data = terms.toArray(new String[terms.size()]);
// terms is a List<String>
ArrayAdapter<?> adapter = new ArrayAdapter<Object>(activity, android.R.layout.simple_dropdown_item_1line, data);
keywordField.setAdapter(adapter); // keywordField is a AutoCompleteTextView
if(terms.size() < 40) keywordField.setThreshold(1);
else keywordField.setThreshold(2);
Now of course, this is static and doesn't deal with an over-the-air suggestions but, I can also suggest you to notify adapter for the changes after you assign it to the AutoCompleteTextView:
adapter.notifyDataSetChanged();