How to get string text from AutoCompleteTextView? - android

public class FareActivity extends Activity {
int fareid;
String Source;
String Dest;
AutoCompleteTextView source;
AutoCompleteTextView dest;
static final String[] SOURCE = new String[] {
"Delhi", "Mumbai", "Agra", "Jaipur};
static final String[] DEST = new String[] {
"Delhi", "Mumbai", "Agra", "Jaipur};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fare);
dest = (AutoCompleteTextView) findViewById(R.id.acdest);
ArrayAdapter<String> dadapter = new ArrayAdapter<String>(this, R.layout.list_item, DEST);
dest.setAdapter(dadapter);
source = (AutoCompleteTextView) findViewById(R.id.acsource);
ArrayAdapter<String> sadapter = new ArrayAdapter<String>(this, R.layout.list_item, SOURCE);
dest.setAdapter(sadapter);
// Fare id calculation
if(Source=="Delhi" && Dest=="Jaipur")
{
fareid=1;
}
else if(Source=="Delhi" && Dest=="Agra")
{
fareid=2;
}
else if(Source=="Delhi" && Dest=="Mumbai")
{
fareid=3;
}
}
I just want to store autocompletetextview 'source' and autocompletetextview 'dest' values to String variable 'Source' and String Variable 'Dest'. I will use both string variables for further processing in my project, so please help me out.

Just use the AutoCompleteTextView method getText() and call toString() on it.
// Fare id calculation
Source = source.getText().toString();
Dest = dest.getText().toString();
if (Source.equals("Delhi") && Dest.equals("Jaipur")) {
fareid=1;
}
else if (Source.equals("Delhi") && Dest.equals("Agra")) {
fareid=2;
}
else if (Source.equals("Delhi") && Dest.equals("Mumbai")) {
fareid=3;
}
You should keep in mind that users can enter everything they want into your AutoCompleteTextView. If you want to perform an action when the user chooses one of the suggested items, add an OnItemSelectedListener with dest.setOnItemSelectedListener().
There is also an error in your code you call dest.setAdapter(sadapter) instead of source.setAdapter(sadapter).

AutoCompleteTextView source = (AutoCompleteTextView) findViewById(R.id.acsource);
String Source = source.getText().toString();

Related

Listview not updating based on value on Array Adapter

I call the method below to update my listview
ListView list = (ListView) listView.findViewById(R.id.plan_list);
itemsList = sortAndAddSections(getItems_search(name));
ListAdapter adapter = new ListAdapter(getActivity(), itemsList);
list.setAdapter(adapter);
but that code is associated with a value that changes and also this is the other code
private ArrayList<plan_model> getItems_search(String param_cusname) {
Cursor data = myDb.get_search_plan(pattern_email, param_name);
int i = 0;
while (data.moveToNext()) {
String date = data.getString(3);
String remarks = data.getString(4);
items.add(new plan_model(cusname, remarks);
}
return items;
}
and this is my sorter
private ArrayList sortAndAddSections(ArrayList<plan_model> itemList) {
Collections.sort(itemList);
plan_model sectionCell;
tempList.clear();
tmpHeaderPositions.clear();
String header = "";
int addedRow = 0;
int bgColor = R.color.alt_gray;
for (int i = 0; i < itemList.size(); i++) {
String remarks = itemList.get(i).getRemarks();
String date = itemList.get(i).getDate();
if (!(header.equals(itemList.get(i).getDate()))) {
sectionCell = new plan_model(remarks, date);
sectionCell.setToSectionHeader();
tmpHeaderPositions.add(i + addedRow);
addedRow++;
tempList.add(sectionCell);
header = itemList.get(i).getDate();
bgColor = R.color.alt_gray;
}
sectionCell = itemList.get(i);
sectionCell.setBgColor(bgColor);
tempList.add(sectionCell);
if (bgColor == R.color.alt_gray) bgColor = R.color.alt_white;
else bgColor = R.color.alt_gray;
}
tmpHeaderPositions.add(tempList.size());
for (int i = 0; i < tmpHeaderPositions.size() - 1; i++) {
sectionCell = tempList.get(tmpHeaderPositions.get(i));
sectionCell.setDate(sectionCell.getDate() + " (" +
(tmpHeaderPositions.get(i + 1) - tmpHeaderPositions.get(i) - 1) + ")");
}
return tempList;
}
my question is the value name changes but my listview is not how can I update my listview? because i need to update it based on search parameter
If your itemList is being updated properly, you don't need to create another instance of the adapter, just use notifyDataSetChanged():
private void createList() {
ListView list = (ListView) listView.findViewById(R.id.plan_list);
itemsList = sortAndAddSections(getItems_search(name));
adapter = new ListAdapter(getActivity(), itemsList);
list.setAdapter(adapter);
}
private void updateList() {
sortAndAddSections(getItems_search(name)); // Update itemList without re-assign its value, otherwise the adapter will loose reference
adapter.notifyDataSetChanged()
}
In getItems_search() add this line at the beginning:
items.clear();
Every time the value of name changes you have to do the following:
itemsList.clear();
itemsList = sortAndAddSections(getItems_search(name));
list.setAdapter(new ListAdapter(getActivity(), itemsList));

Listview of backendless directories

I'm using backendless and I'm trying to display my directories in a listview. I'm using Android Studio.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Backendless.setUrl(Defaults.SERVER_URL);
Backendless.initApp(this, Defaults.APPLICATION_ID, Defaults.SECRET_KEY, Defaults.VERSION);
Backendless.Files.listing("/Uploads", "*docs", true, new AsyncCallback<BackendlessCollection<FileInfo>>() {
#Override
public void handleResponse(BackendlessCollection<FileInfo> fileInfoBackendlessCollection) {
Iterator<FileInfo> filesIterator = fileInfoBackendlessCollection.getCurrentPage().iterator();
while (filesIterator.hasNext()) {
FileInfo file = filesIterator.next();
String URL = file.getURL();
String publicURL = file.getPublicUrl();
Date createdOn = new Date(file.getCreatedOn());
String name = file.getName();
String[] info = {URL, publicURL, name};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getListView().getContext(), android.R.layout.simple_list_item_1, info);
getListView().setAdapter(adapter);
}
}
#Override
public void handleFault(BackendlessFault backendlessFault) {
}
});
}
}
It has no error but the app doesn't open. Can anyone help me what to do?
Here is the start for fixing your problem:
#Override
public void handleResponse(BackendlessCollection<FileInfo> fileInfoBackendlessCollection) {
// create a list for your data
List<String> infoList = new ArrayList<>();
Iterator<FileInfo> filesIterator = fileInfoBackendlessCollection.getCurrentPage().iterator();
while (filesIterator.hasNext()) {
FileInfo file = filesIterator.next();
String URL = file.getURL();
String publicURL = file.getPublicUrl();
Date createdOn = new Date(file.getCreatedOn());
String name = file.getName();
// put everything into one string temporarily
// String[] info = {URL, publicURL, name};
String info = URL + " " + publicURL + " " + name;
infoList.add(info);
}
// loop through ALL your data before creating/assigning adapter
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getListView().getContext(), android.R.layout.simple_list_item_1, infoList);
getListView().setAdapter(adapter);
}
Now your adapter is going to get a little more complicated, because you will not want to have everything on one line. You will need to create a layout for your list item. Then you need to use either SimpleAdapter or create a custom class extending BaseAdapter and use that to display your data.

Make Spinner click disabled if it contains only 1 item

String options[] = new String[3];
// options[0] = "Select IVC Option";
int i =0;
IDataObject emailobject = inMemoryCache_getDataObject("EMAIL_CONTACT");
IDataObject smsobject = inMemoryCache_getDataObject("SMS_CONTACT");
IDataObject voicecallobject = inMemoryCache_getDataObject("VOICE_CONTACT");
try {
if(emailobject != null){
options [i] = "Email";
i++;
}
if(smsobject != null){
options [i] = "SMS";
i++;
}
if(voicecallobject != null){
options [i] = "VoiceCall";
i++;
}
}catch (Exception e){
}Spinner ivcoptions; ivcoptions = (Spinner)view.findViewById(R.id.spinner);
ArrayAdapter<String> x = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_item,options);
x.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
ivcoptions.setAdapter(x);
I want the spinner click be disabled , if and only if the Spinner contains 1 item.
I have tried with controlling with the string array length. But it doesn't help.
If you want to disable spinner item click event, you'd need to change the adapter, however if you only want to prevent the spinner from being clicked on, you can simply register a data observer on your adapter:
final Spinner ivcoptions = (Spinner) findViewById(R.id.spinner);
final ArrayAdapter<String> x = new ArrayAdapter<>(this,
android.R.layout.simple_spinner_item,options);
x.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Register a data observer
x.registerDataSetObserver(new DataSetObserver() {
#Override
public void onChanged() {
super.onChanged();
if (x.getCount() == 1) {
ivcoptions.setEnabled(false);
} else {
ivcoptions.setEnabled(true);
}
}
});
// Set your adapter
ivcoptions.setAdapter(x);

HashSet to ArrayList not Displaying in Listview

So this project is driving me insane. Thank you to Ahmed Aeon Axan for the last answer. I have never worked with HashTables before but from the all the code I've looked at this should be working. Please tell me why this is not displaying in my listview.
Created in the model.java below
public class Model implements Serializable {
public static final int END_MORNING = 11; // 11:00AM, inclusive
public static final int END_AFTERNOON = 16; // 4:00PM, inclusive
private GregorianCalendar startDate;
private ArrayList<GregorianCalendar> datesSmoked = new ArrayList<GregorianCalendar>();
private ArrayList<String> locationsSmoked = new ArrayList<String>();
private ArrayList<String> locations = new ArrayList<String>();
private ArrayList<String> allIncidents = new ArrayList<String>();
private Set<String> newLocArr = new HashSet<String>(locations);
private SimpleDateFormat sdf = new SimpleDateFormat("E, MMM dd");
private ArrayList<String> times = new ArrayList<String>();
public String [] defaultLocations = {"Home", "Work", "Commuting", "School", "Bar", "Restaurant", "Social Gathering", "Other"};
public String [] eachSmoked;
public Model(GregorianCalendar date){
startDate = date;
for (String s : this.defaultLocations) {
locations.add(s);
}
}
public Model(){
this(new GregorianCalendar()); // now
}
public ArrayList<String> getDates() {
for (int i = 0; i < datesSmoked.size(); i++) {
String s = (sdf.format(i));
times.add(s);
}
return times;
}
public List<String> getPlacesSmoked() {
for (String key : locations) {
newLocArr.add(key+ ": " + Collections.frequency(locationsSmoked, key));
}
return new ArrayList<String>(newLocArr);
}
public ArrayList<String> getAllIncidentsArray() {
for (int i = 0; i < datesSmoked.size(); i++) {
allIncidents.add(getDates().get(i) + ", " + locationsSmoked.get(i));
}
return allIncidents;
}
public ArrayList<String> getlocationsArray() {
return this.locations;
}
public ArrayList<String> getLocationsSmokedArray() {
return this.locationsSmoked;
}
public ArrayList<GregorianCalendar> getDatesSmokedArray() {
return this.datesSmoked;
}
Ends the relevant code for model.java
called into the list view in the Locations Activity below where it is not displaying
public class LocationActivity extends Activity {
public static final String SMOKIN_DATA_FILE = "smokin.dat";
public static Model model = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
restoreModel();
ListView listView = (ListView) findViewById(R.id.location_listview_Id);
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, model.getPlacesSmoked());
listView.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
}
Essentially Im trying to get the ArrayList locationsSmoked which Displays
Home
Home
Home
Home
School
School
School
School
to display
Home: 4
School: 4
Your locTest list is empty, since it is initialized at the Model creation with empty HashSet test1 which is initialized with empty locations list.
The List(Collection<?>) constructor is copying the values, not the pointer to the collection, as far as I remember
fast solution (not sure if it do the trick actually):
public Model(GregorianCalendar date){
startDate = date;
for (String s : this.defaultLocations) {
locations.add(s);
}
// calling setPlacesSmoked to process data
setPlacesSmoked();
}
public void setPlacesSmoked() {
// assuming that locations list holds the data needed to process
for (String key : locations) {
test1.add(key+ ": " + Collections.frequency(locations, key));
}
}
public List<String> getPlacesSmoked() {
//return locTest;
return new ArrayList<String>(test1);
}
The expected output:
Home: 1
Work: 1
Commuting: 1
School: 1
Bar: 1
Restaurant: 1
Social Gathering: 1
Other: 1
But that depends on the locations contents

Updating values to Hash-table?

I have some problem in updating the values to hash-table,here is my problem i will explain it clearly.
1.I have getting the response from server,i am adding the values to layout,by using layout Layout-Inflater.
2.in our application we have streaming request.when the streaming request is turned on the values need to be updated regularly.
storing values in hash-tables
Hashtable<String, View> indicesHashtable = new Hashtable<String, View>();
For(Step 1)code i have written belowthe code.
private void addIndices(LinearLayout parent, final String key,final String value) {
LayoutInflater factory = LayoutInflater.from(mContext);
final View row = factory.inflate(R.layout.indices_values, null);
final TextView keyTextView = (TextView) row.findViewById(R.id.txtCompany);
final TextView valueTextView = (TextView) row.findViewById(R.id.txtIndex);
final Button iconImageView = (Button) row.findViewById(R.id.btnIcon);
row.setBackgroundResource(android.R.drawable.list_selector_background);
if (value.length() > 0) {
keyTextView.setText(Html.fromHtml("<b>"+indices.get(key)+"</b>"));
valueTextView.setText(Html.fromHtml(value));
if(quoteArrowIconId != -1)
iconImageView.setBackgroundResource(quoteArrowIconId);
else
iconImageView.setBackgroundDrawable(null);
}else{
keyTextView.setText(Html.fromHtml(key));
}
indicesHashtable.put(key, row);
parent.addView(row);
}
For(Step 2)i need help from you guys.
i have written code..that i have shown below.
private void handleResponseOfResponses(ResponseParser response) {
Hashtable responses = (Hashtable) response.getValue(Response_890.RESPONSES);
String[] symbols = new String[responses.size()];
int index = 0;
indicesHashtable.clear();
for(int i =indicesSymbols.length-1; i >= 0; i--){
Enumeration e = responses.keys();
while (e.hasMoreElements()) {
ResponseParser subResponse = (ResponseParser) responses.get(e.nextElement());
if (subResponse.getResponseCode() == ResponseCodes.QUOTES_RESPONSE) {
String[] quoteProperties = (String[]) subResponse.getValue(Response_312.QUOTES_KEY);
if(quoteProperties[0].equalsIgnoreCase(indicesSymbols[i])){
// symbolTable.put(quoteProperties[0].toUpperCase(), index);
symbols[index++] = quoteProperties[0];
String value = quoteValue(quoteProperties);
For displaying the values coming for response i have added (AddIndices)method
addIndices(linear_Indices, quoteProperties[0], value);
}
}
}
}
autoscroll();
indicesStreamerClient = new StreamerClient(indicesSymbols){
#Override
public void onStreamDataReceived(QuoteData quoteData) {
System.out.println("onStreamDataReceived () -> "+quoteData.getSymbol());
HERE I NEED TO ADDED ANOTHER METHOD FOR UPDATING THE VALUES..HOW I CAN WRITE THE CODE.
};
};
Streamer.getInstance(mContext).registerStramerClient(indicesStreamerClient);
}
Guys i am fresher as well as new to andriod.
Thanks in advance!!!!!!

Categories

Resources