Android Extract a specific value from a ListView item - android

I'm working on an application where I have a ListView that shows the coordinates of my smartphone's position previously stored on a database. The rows of the ListView appear to be like: (latitude, longitude), date.
Is it possible to get the single values of the item? I was thinking to retrieve only the latitude and longitude values of the clicked item so that I can open a new MapsActivity that sets a marker at those specific coordinates.
Looking through other similar questions I've got that with ((TextView) view).getText() or with listView.getItemAtPosition(position) I can read the entire content of the item, but I'd like to apply that to the first two values of the ListView.

So for anyone interested I solved my problem by parsing the content of the item as a String by doing like this:
String str = (String) listView.getItemAtPosition(position);
String parts[] = str.split(",");
String lat = parts[0];
String lon = parts[1];
I had to get rid of "(" and ")" in the visualization of the coordinates as they were hindering the string parsing.

Related

Maps address storing problem in arraylist

I'm working on google maps project.Users can add location and view them on the gridview.When I run my app to view all locations from database,all indexes get retrived from database successfuly and pushed arraylist.But when I try to add location.All previous locations get added database again , then my desired location added end of the array.So when I try to reach desired location from gridview,it shows me first location.I want it to be repeated just once.I think there's problem on my select query.Here's output result.
Result
GridView gridView= (GridView) findViewById(R.id.gridView);
list = new ArrayList<>();
try {
MapsActivity.database = this.openOrCreateDatabase("Places",MODE_PRIVATE,null);
Cursor cursor = MapsActivity.database.rawQuery("SELECT * FROM places",null);
int nameIx = cursor.getColumnIndex("name");
int latitudeIx = cursor.getColumnIndex("latitude");
int longitudeIx = cursor.getColumnIndex("longitude");
while (cursor.moveToNext()) {
nameFromDatabase = cursor.getString(nameIx);
String latitudeFromDatabase = cursor.getString(latitudeIx);
String longitudeFromDatabase = cursor.getString(longitudeIx);
image = cursor.getBlob(3);
// names.add(nameFromDatabase);
Double l1 = Double.parseDouble(latitudeFromDatabase);
Double l2 = Double.parseDouble(longitudeFromDatabase);
// System.out.println("coordinates:"+l1+","+l2);
locationFromDatabase = new LatLng(l1, l2);
names.add(nameFromDatabase);
locations.add(locationFromDatabase);
list.add(new Location(nameFromDatabase, image));
}
cursor.close();
} catch (Exception e) {
e.printStackTrace();
}
adapter = new LocationListAdapter(this, R.layout.location_items, list);
gridView.setAdapter(adapter);
I suspect that your issue is that when adding a new location, your get all the locations again from google maps.
Your code doesn't include the code for adding a location.
However, you could prevent duplicated data by defining appropriate UNIQUE constraints for your Places Database.
As an example, based upon your code, you could CREATE the table using :-
CREATE TABLE IF NOT EXISTS places (name TEXT UNIQUE ON CONFLICT IGNORE,longitude REAL,latitude REAL,image BLOB, UNIQUE (longitude,latitude) ON CONFLICT IGNORE)
Using name TEXT UNIQUE ON CONFLICT IGNORE will add a restriction/rule/constraint that the name must be unique and if an attempt is made to use a name that already exists (insert or update) then that attempt will be ignored (no error raised).
Using UNIQUE (longitude,latitude) ON CONFLICT IGNORE does the same BUT for the combination of BOTH columns.
e.g. if a row in the table has latitude 1 and longitude 1 then :-
an attempt to add a row with latitude 1 and longitude 1 will result in the attempt being ignored.
an attempt to add a row with latitude 2 and longitude 1 will work as the combination of the two values has not been used.
likewise, an attempt to add a row with latitude 1 and longitude 2 will work.

How to extract lat and long values from a google maps link

I have a web view that shows google maps on my android activity. I am currently getting the link that contains the latitude and longitude values of the selected location by clicking a button. What I want to know is, how can I extract and save the latitude and longitude values in to variables? I tried this code but it doesn't seem to work
Uri uri = Uri.parse(str);
uri.getQueryParameter(q1);
If you have the url as a String, named str:
String[] part1 = str.split(Pattern.quote("#"));
String[] part2 = part1[1].split(Pattern.quote(","));
double lat = Double.parseDouble(part2[0]);
double lon = Double.parseDouble(part2[1]);

Displaying items of the same name in Android SQLite

I'm using this below to add map markers to a Google Map. I have a table column FIELD_NAME. There are several locations each tied to a same FIELD_NAME. So for example there may be 5 entries of FIELD_NAME Woods with each entry having its own latitude/long value. I'm trying to figure out how to query the table to provide the FIELD_NAME but I only want it to show one of each name, not every time it is used. Once I get the name I will use it to display all the lat long points of that selected FIELD_NAME. How do you do this and does anyone have any links to tutorials on queries of this type?
#Override
public void onLoadFinished(Loader<Cursor> arg0,
Cursor arg1) {
int locationCount = 0;
double lat=0;
double lng=0;
// Number of locations available in the SQLite database table
locationCount = arg1.getCount();
// Move the current record pointer to the first row of the table
arg1.moveToFirst();
for(int i=0;i<locationCount;i++){
// Get the latitude
name = arg1.getString(arg1.getColumnIndex(LocationsDB.FIELD_NAME));
lacomments = arg1.getString(arg1.getColumnIndex(LocationsDB.FIELD_COMMENTS));
lat = arg1.getDouble(arg1.getColumnIndex(LocationsDB.FIELD_LAT));
// Get the longitude
lng = arg1.getDouble(arg1.getColumnIndex(LocationsDB.FIELD_LNG));
// Creating an instance of LatLng to plot the location in Google Maps
locationEngine = new LatLng(lat, lng);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(locationEngine);
// Adding marker on the Google Map
getMap().addMarker(markerOptions);
arg1.moveToNext();
}
}
if you want to populate distinct FIELD_NAME in some spinner and then on selection of it display all the location for that, better do it with 2 queries
bind the spinner with result of
"select distinct FIELD_NAME from tablename"
and then once user provides his selection, use the below query
select * from tablename where FIELD_NAME ='whatever_user_selected'
Note: tablename - replace with your table's name
Let me know if there is not UI for user selection and you want random
entries for a specific field

How to get Text written after "," in MultiAutoCompleteTextView?

I am developing an application that uses MultiAutoCompleteTextView for showing hints in the drop down list.In this application I retrieve the value written in the MultiAutoCompleteTextView by using
multitextview.getText();
and then query this value to server to recieve JSON response which is shown as suggestions in the drop down list.
If a user types Mu and then Selects music from the list and then types box for another suggestion the content in the MultiAutoCompleteTextView becomes Music,box and now the value for querying to the server is Music,box instead of this I want to select only box.
My question is how to retrieve text written after "," in MultiAutoCompleteTextView?
Can this be achieved using getText()?
I solved this issue
String intermediate_text=multitextview.getText().toString();
String final_string=intermediate_text.substring(intermediate_text.lastIndexOf(",")+1);
I'm sure there are several ways to get around this. One way to do it would be:
String textToQuerryServer = null;
String str = multitextview.getText().toString(); // i.e "music, box" or "any, thing, you , want";
Pattern p = Pattern.compile(".*,\\s*(.*)");
Matcher m = p.matcher(str);
if (m.find()) {
textToQuerryServer = m.group(1);
System.out.println("Pattern found: "+ textToQuerryServer);
}else {
textToQuerryServer = str;
System.out.println("No pattern: "+ textToQuerryServer);
}

Android - Get single String value using HashMap

In my application, I've preloaded Spinner with ArrayList.The ArrayList contains multiple Text String. These text Strings will serve as message template user can select from spinner. Also I want these String keyword might be replaced with variable when message is being sent. Like "Text" will be replaced with EditText content, "Phone No " replaced with Sender's no, "Date" replaced with Message Date
I have tried to search on HashMap in Android, but getting problem:
HashMap<String, String> template=new HashMap<String, String>();
template.put("Text", editText.getText().toString());
template.put("Phone No",senderPhone);
template.put("Date",receivedDate);
now I want to display it as Single string like Text, Phone No, Date. can this String be editable.
You can use
StringBuilder builder = new StringBuilder();
for (String name : template.values())
{
builder.append(name + " ");
}
String templateString = builder.toString();
This will get all the values from the HashMap using the values() and concat it into a String
To get a value from Hashmap, use:
String Text = (String)template.get("Text");
String phoneNo= (String)template.get("PhoneNo");
String date = (String)template.get("Date");
You can combine all the above 3 and display it where ever you want to
For Example,
String displayString = Text + "-" + phoneNo + " -" + date
editText.setText(displayString);
This edit text by default would be editable until and unless you make it non editable.!
EDIT: (Refer comments for purpose of Edit)
(1) Set the edit text value as the value selected by user from spinner.
editText.setText(displayString);
(2) After user selects and modifies the edittext, let the user click a confirm button.
(3) In confirm button code, add the value to your local storage (IF REQUIRED!).
(4) Refresh the spinner to include this modified value
To refresh, if you want to modify the existing list in spinner then refer Refresh spinner data
To refresh, if you want to keep the existing spinner list as such, and add the new value, then refer dynamic add data to spinner but not update the data on the spinner

Categories

Resources