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
Related
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 ;
}
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;
}
}
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;
}
}
});
I am new to Android. I'm trying to sort by the date in the JSON data, but nothing works. I'm not even getting an error. I've tried so many different ways, but its not working.
I did a lot of searching but could not figure out how to implement this. How can I sort this by the days column? Thank you in advance.
Here's my code
public class ParseJSONTask extends AsyncTask< Void , Void , Void > {
public Handler handler = new Handler();
public Activity act = null;
private static String TAG_SERVICES = "services";
private static String TAG_ID = "id";
private static String TAG_COMMAND = "command";
private static String TAG_DAYS = "days";
private static String TAG_HOURS = "hours";
private static String TAG_OSMS = "osms";
private static String TAG_ISMS = "isms";
private static String TAG_TIMEOUT = "timeout";
public String SMS_SENT = "SMS Gönderildi";
public String SMS_DELIVERED = "SMS İletildi";
public String serviceString = "";
ArrayList<ServiceData> services;
#Override
public void onPreExecute() {
super.onPreExecute();
services = new ArrayList<ServiceData>();
}
#Override
public Void doInBackground(Void... params) {
WebServiceHandler webServiceHandler = new WebServiceHandler();
String JsonStr = webServiceHandler.getJSONData("http://jsonblob.com/55e34310e4b01190df36e861");
try {
JSONObject jsonObject = new JSONObject(JsonStr);
final JSONArray contactsJSON = jsonObject.getJSONArray(TAG_SERVICES);
for (int i = 0; i < contactsJSON.length(); i++) {
ServiceData aServiceData = new ServiceData();
//json parse istedimiz veriyi kullanabiliriz.
JSONObject serviceObject = contactsJSON.getJSONObject(i);
aServiceData.id = serviceObject.getString(TAG_ID);
aServiceData.command = serviceObject.getString(TAG_COMMAND);
aServiceData.days = serviceObject.getString(TAG_DAYS);
aServiceData.hours = serviceObject.getString(TAG_HOURS);
aServiceData.osms = serviceObject.getString(TAG_OSMS);
aServiceData.isms = serviceObject.getString(TAG_ISMS);
aServiceData.timeout = serviceObject.getString(TAG_TIMEOUT);
String input = aServiceData.days + " " + aServiceData.hours;
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(input);
long milliseconds = date.getTime();
final long millisecondsFromNow = milliseconds - (new Date()).getTime();
aServiceData.milliseconds = milliseconds;
services.add(aServiceData);
if(millisecondsFromNow > 0) {
new DateSendSMS().onCreate(aServiceData.days, aServiceData.hours, aServiceData.osms, aServiceData.command);
Thread.sleep(Integer.parseInt(aServiceData.timeout) * 60000);
}
//Timeout aşağı kısımda sürelendirilecek
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
String serviceString = "";
for (ServiceData aServiceData:services){
serviceString+=aServiceData.toString();
}
Collections.sort(services, new Comparator<ServiceData>() {
#Override
public int compare(ServiceData t1, ServiceData t2) {
return t1.milliseconds <= t2.milliseconds ? -1 : 1;
}
});
// here is sorted data
for (ServiceData aServiceData : services) {
// move DateSendSMS here. above you can add additional logic about millis
new DateSendSMS().onCreate(aServiceData.days, aServiceData.hours, aServiceData.osms, aServiceData.command);
Log.d("+++++", aServiceData.toString());
}
}
}
ServiceData Class:
public static class ServiceData {
public long milliseconds;
public String id = "";
public String command = "";
public String days = "";
public String hours = "";
public String osms = "";
public String isms = "";
public String timeout = "";
#Override
public String toString() {
return id + ", " + command + ", " + days + ", " + hours + ", " + osms + ", " + isms
+ ", " + timeout + "\n \n ";
}
}
Add time field to ServiceData class
ServiceDate {
...
long milliseconds;
...
}
Fill this field in for loop:
long milliseconds = date.getTime();
aServiceData.milliseconds = milliseconds;
Sort services in onPostExecute
Collections.sort(services, new Comparator<ServiceData>() {
#Override
public int compare(ServiceData t1, ServiceData t2) {
return t1.milliseconds <= t2.milliseconds ? -1 : 1;
}
});
I am not sure you can directly sort Json Data (I dont know weather there is a library that will actually do it - if so go for it). I Suggest you to put all the ServiceData into a collection (Which you do at the moment) and then Sort it.
You can write your own sorting algorithm or you can use a Java Collections library to do the sorting by implimention Comparable on your ServiceData class or using a Comparable and them you can use Colletions.sort() to sort your list.
Here is a good tutorial.
public class GlobalVariable extends Application {
private static String[] array;
public static void setarray(String[] array) {
GlobalVariable.array = Arrays.copyOf(array, array.length);
}
public static String[] getArray() {
return Arrays.copyOf(array, array.length);
}
}
i have use it like this
String []array = new String[list.size()];
for(int i1 = 0; i1 < list.size(); i1++)
{
array[i1] = list.get(i1);
System.out.println("this is from array"+array[i1]);// this statment running proper.. displays in my logcate
}
GlobalVariable.setarray(array);
}
now i want this value in another activity that extends Frgment
i have use it like:
String[] array1 = new String[1000];
array1 = GlobalVariable.getArray();
for(int i=0;i<array1.length;i++)
{
System.out.println(array1[i]);
}
But it crashes my application by saying null pointer exception how to use it?