Select Spinner Item Programatically Custom Adapter - android

I have a spinner which I am filling using the below code:
String[] routeList = response.split("\\^");
List<PresetDetails> list = new ArrayList<PresetDetails>();
for (String x : routeList) {
list.add(new PresetDetails(Arrays.asList(x.split(",")).get(0), Arrays.asList(x.split(",")).get(1), Arrays.asList(x.split(",")).get(2), Arrays.asList(x.split(",")).get(3)));
}
ArrayAdapter<PresetDetails> adap = new ArrayAdapter<PresetDetails>(activity, android.R.layout.simple_spinner_item, list);
TrackingLocations_Spinner_Presets.setAdapter(adap);
PresetDetails
public class PresetDetails {
public String PresetID;
public String Latitude;
public String Longitude;
public String PresetName;
public PresetDetails( String PresetID, String Latitude, String Longitude,String PresetName ) {
this.PresetID = PresetID;
this.Latitude = Latitude;
this.Longitude = Longitude;
this.PresetName = PresetName;
}
#Override
public String toString() {
return PresetName;
}
In another piece of code, I have PresetID and have to programatically select corresponding item in the filled spinner. How can I achieve that.

for(int i = 0; i < list.size(); i++) {
if(list.get(i).equals("your id")) {
spinnerObject.setSelection(i);
break;
}
}

Related

Make an array of my model with an auto-increment

I have a Model and I want make an array of this. The problem is I do it like this :
My code :
final WifiModel itemsData[] = {
new WifiModel(nearbyAccessPoints.get(0).SSID, "name"),
new WifiModel(nearbyAccessPoints.get(1).SSID, "name"),
new WifiModel(nearbyAccessPoints.get(2).SSID, "name"),
new WifiModel(nearbyAccessPoints.get(3).SSID, "name"),
new WifiModel(nearbyAccessPoints.get(4).SSID, "name"),
};
And I would like to do a i++ form to i=4 for example.
How can I do that ?
My Model :
public class WifiModel {
private String SSID;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
WifiModel(String SSID, String name) {
this.SSID = SSID;
this.name = name;
}
public String getSSID() {
return SSID;
}
public void setSSID(String SSID) {
this.SSID = SSID;
}
}
easy :)
WifiModel itemsData[] = new WifiModel[5];
for(int i=0; i<5; i++) itemsData[i]=new WifiModel(nearbyAccessPoints.get(i).SSID, "name");
Arrays are not for dynamic length. You can use ArrayList instead to acheive this goal as following:
ArrayList<WifiModel> itemsData = new ArrayList<>();
int n=4; // any number you want
for(int i=0;i<n;i++)
{
itemData.add(new WifiModel(nearbyAccessPoints.get(i).SSID, "name"));
}
try this :
List<WifiModel> list = new ArrayList<>();
WifiModel wifi=null;
int i;
for(i=0; i<4; i++){
wifi = new WifiModel(nearbyAccessPoints.get(i).SSID, "name");
list.add(wifi);
}

possible to return array of strings in android

i want to load group of images and text to item in list,so every item have 3 text view and group of image in viewpager , so i make java class contain methods to get and set text and images url,that is my code
updates i solve previous problem but when send array of string to projects class it gives me red underline error
public class Projects {
private String yourText = "";
private String yourstatu= "";
private String yourdes= "";
private String yourversion= "";
private String[] img;
public String getyourText () {
return yourText ;
}
public void setyourText(String yourText) {
this.yourText = yourText;
}
public String getyourdescription () {
return yourdes ;
}
public void setyourdescription( String yourdes) {
this.yourdes = yourdes;
}
public String getyourstatu () {
return yourstatu ;
}
public void setyourstatu( String yourstatu) {
this.yourstatu = yourstatu;
}
public String getYourversion() {
return yourversion ;
}
public void setYourversion( String yourversion) {
this.yourversion = yourversion;
}
public String getYourimages() {
return new String[] img ; // here red underline
}
public void setYourimages( String []img) {
this.img = img;
}
}
part of my main page
mProduct.setyourText(name11);
mProduct.setyourstatu(status);
mProduct.setYourversion(version);
mProduct.setyourdescription(description);
mArrayList.add(mProduct);
for (int i = 0; i < jreimages.length(); i++) {
JSONObject jjobject = jreimages.getJSONObject(i);
String imageid=jjobject.getString("project_id");
if(imageid==id){
String urlimage=jjobject.getString("screenshot");
String total=url+urlimage;
images[j]=total;
}
mProduct.getYourimages(images); // here underline error says getYourimages cannot be applied to java.lang,string[]
how to return array of strings ?
You defined an array of Strings - String[] img, so you can just return it from your function.
Just remove new String[] and left 'img' and change the return type from String to String[]
public String[] getYourimages() {
return img ;
}

How to sort a listview by string numbers?

Here is my main issue, after some researches, I didn't find a solution so... I would like to sort my list of custom objects. These items have a price, but for a reason they are strings not int. I would like to know how to achieve this, thanks for helping !
Little personnal question, sorting a listview and a recyclerview are they done the same way ?
EDIT:
public class Product implements Parcelable {
private String imgUrl, titre, description, prix, nomAgence, pays, ville, type_produit, nbPieces = null;
List<String> urlImageList_thumb = new ArrayList<>();
List<String> urlImageList_full = new ArrayList<>();
private int isAdded = 0;
/* getters and setters*/
}
EDIT 2 :After your help, here's my code for comparable
#Override
public int compareTo(Product otherProduct) {
String tmp = prix.replace(" €", "");
String tmp2 = otherProduct.prix.replace(" €", "");
//Integer p1 = Integer.valueOf(tmp); --> does not work
//Integer p2 = Integer.valueOf(tmp2); --> does not work
Integer p1 = Integer.parseInt(tmp); //same error
Integer p2 = Integer.parseInt(tmp2); // same error
return p1.compareTo(p2);
}
Here's the code in the activity:
bouton_tri.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Collections.sort(productList);
}
});
EDIT 3 :
#Override
public int compareTo(Product otherProduct) {
String tmp = prix.replace(" €", "").replaceAll(" ", "");
String tmp2 = otherProduct.prix.replace(" €", "").replaceAll(" ", "");
Integer p1 = Integer.valueOf(tmp);
Integer p2 = Integer.valueOf(tmp2);
return p1.compareTo(p2);
}
I still have an error, but when I just take off " €" the value is "5 300 000", if only spaces "5300000€". But putting both together gives me this error java.lang.NumberFormatException: Invalid int: "-" ... Any ideas ? Thanks
You can make modify your Product class to implement Comparable
Before converting the String to an Integer you need to remove the €and all spaces.
public class Product implements Parcelable, Comparable<Product> {
private String prix;
//...
#Override
public int compareTo(Product otherProduct) {
String tmp = prix.replace(" €", "").replaceAll(" ", "");
String tmp2 = otherProduct.prix.replace(" €", "").replaceAll(" ", "");
Integer p1 = Integer.valueOf(tmp);
Integer p2 = Integer.valueOf(tmp2);
return p1.compareTo(p2);
}
}
Once done to sort your collection you can use : Collections.sort(...); this method will take as parameter the list of custom objects you are using in your adapter.
For example:
List<Product> l = new ArrayList();
Collections.sort(l);
Note that sorting the collection will not refresh the views of the recyclerview.
You will have to call notifyDataSetChanged() on your adapter to refresh the recyclerview:
You can do this in your main activity where you have declared your adapter :
yourAdapter.notifyDataSetChanged();
Just assuming you have List<String> sampleData object
Collections.sort(sampleData, new Comparator<String>() {
#Override
public int compare(String c1, String c2) {
return Integer.valueOf(c1) - Integer.valueOf(c2);
}
});
This will sort your data.
(int) Integer.parseInt(p2.getNumberOfRecords()) - Integer.parseInt(p1.getNumberOfRecords())
So the simple compare of an integer in a String data type would not result correctly but to parse the string first by:
int value = Integer.parseInt(string)
Try this:
Collections.sort (list, new Comparator<String> () {
#Override
public int compare (String s1, String s2) {
return s1.compareToIgnoreCase(s2);
}
});
OR
Collections.sort (list, new Comparator<String> () {
#Override
public int compare (String s1, String s2) {
//cast string price to integer
int price1 = Integer.parseInt(s1);
int price2 = Integer.parseInt(s2);
if (price1 > price1) {
return 1;
}
else if (price2 > price1) {
return -1;
}
else {
return 0;
}
}
});

how to draw Bitmaps with specific ArrayList of coordinates on google maps api 2 using asynctask?

The idea of the application is to get ArrayList<LatLng> from the database then draw these coordinates as markers using bitmaps on the map
I'm getting:
NullPointerException at android.graphics.Canvas.drawBitmap(Canvas.java:1195) in onPostExecute
There's two questions in here:
Is it normal to draw bitmaps in onPostExecute method..??
Why I get NullPointerException at android.graphics.Canvas.drawBitmap(Canvas.java:1195) in onPostExecute...??
Asynctask Class:
public class BitmapAsyncTask extends
AsyncTask<ArrayList<Obstacle>, Void, ArrayList<LatLng>> {
static Canvas canvas1;
static BitmapFactory.Options o;
private Bitmap bmp;
MarkerOptions balloonmarker;
private double latitude;
private double longitude;
GoogleMap gm;
LatLng ll;
LatLng latlong;
private int len;
private static int resID = 1;
static ArrayList<Obstacle> obs;
static ArrayList<LatLng> coordinates;
static ArrayList<LatLng> sendingCoord;
private static double mydirection = 45;
static Context context;
public BitmapAsyncTask(Context contextx) {
context = contextx;
}
#Override
protected ArrayList<LatLng> doInBackground(ArrayList<Obstacle>... params) {
int i;
ArrayList<Obstacle> obstacleArray = params[0];
coordinates = new ArrayList<LatLng>();
len = obstacleArray.size();
for (i = 0; i < len; i++) {
Obstacle obstacle = obstacleArray.get(i);
latitude = obstacle.getLatitude();
longitude = obstacle.getLongitude();
mydirection = obstacle.getDirection();
}
for (int x = 0; x < 1; x++) {
ll = new LatLng(latitude, longitude);
coordinates.add(ll);
}
}
return coordinates;
}
#Override
protected void onPostExecute(ArrayList<LatLng> result) {
int i;
int size = result.size();
bmp = BitmapFactory.decodeResource(context.getResources(),
R.drawable.map_pin, null);
bmp=Bitmap.createBitmap(50, 50, Config.ARGB_4444);
for (i = 0; i < size; i++) {
latlong = result.get(i);
canvas1=new Canvas();
//the exception happens here
canvas1.drawBitmap(bmp, null, null);
balloonmarker = new MarkerOptions().title("MyLocation")
.snippet("This Is Me").position(latlong).anchor(0, 1)
.icon(BitmapDescriptorFactory.fromBitmap(bmp));
gm.addMarker(balloonmarker);
}
if (bmp != null) {
bmp.recycle();
bmp = null;
System.gc();
}
}
Obstacle class:
public class Obstacle {
long id;
double longitude;
double latitude;
double direction;
public Obstacle(double longitude, double latitude, double direction) {
super();
this.longitude = longitude;
this.latitude = latitude;
this.direction = direction;
}
public Obstacle() {
// TODO Auto-generated constructor stub
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getDirection() {
return direction;
}
public void setDirection(double direction) {
this.direction = direction;
}
public Location getLocation() {
Location myLocation = new Location(MatabbatManager.PROVIDER_STRING);
myLocation.setLongitude(longitude);
myLocation.setLatitude(latitude);
return myLocation;
}
}
DataBase Class:
public class LocalCachedObstacles extends SQLiteOpenHelper {
static String DATABASE_NAME="localobstaclesdb";
private static final int DATABASE_VERSION = 1;
static String OBSTACLES_TABLE ="obstacles";
private static final String OBSTACLES_TABLE_CREATE ="" +
"CREATE Table " + OBSTACLES_TABLE +
"(" +
"long REAL," +
"lat REAL," +
"direction REAL, " +
"type REAL, " +
"address VARCHAR(500)," +
"time VARCHAR(100)," +
"submitterName VARCHAR(200) " +
")";
public ArrayList<Obstacle> getCachedObstacles() {
try {
SQLiteDatabase dblocs=this.getReadableDatabase();
Cursor cur=dblocs.rawQuery("SELECT * FROM "+OBSTACLES_TABLE,new String [] {});
ArrayList<Obstacle> obstacles = new ArrayList<Obstacle>();
while (cur.moveToNext()) {
Obstacle obstacle = new Obstacle
(cur.getDouble(0),
cur.getDouble(1),cur.getDouble(2),
cur.getDouble(3),cur.getString(4),
cur.getString(5),cur.getString(6));
obstacles.add(obstacle);
}
cur.close();
dblocs.close();
return obstacles;
}
catch (Exception locex){
Log.e(MatabbatManager.TAG," Get Local cache" + locex.getMessage());
return null;
}
}
Excecution class:
public class AnonymousUser extends FragmentActivity{
LocalCachedObstacles lo = new LocalCachedObstacles(
MyApplication.getAppContext());
ArrayList<Obstacle> localObstacles = lo.getCachedObstacles();
DrawTypes(localObstacles);
public void DrawTypes(ArrayList<Obstacle> obs) {
len = obs.size();
BitmapAsyncTask async = new BitmapAsyncTask(MyApplication.getAppContext());
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
async.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, obs);
}
}
You can not use Canvas as in your code , we can get canvas object by overriding onDraw method.
In my opinion you should use overlays to draw bitmaps on map.
I solved it finally after 2 weeks of trying everything related to threads threadpool,asynctaskloader.....
Solution:
Making aservice instead of AsyncTask because i need it to keep running in the background.

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

Categories

Resources