I am developing an android application and I am using a Hashmap to store some data the app works fine when I define the Arraylist this way
ArrayList<String> eventList = new ArrayList<>();
but the app crashes when I change it to:
ArrayList<String> eventList = hmap.get(date);
I need to know the reason why?.
And here is the whole function in case you need to have a look
HashMap<Date, ArrayList<String>> hmap = new HashMap<>();
void eventMaker(String d, String ev) {
Date date = null;
try {
date = df.parse(d);
} catch (ParseException e) {
e.printStackTrace();
}
long epoch = date.getTime();
Event event = new Event(Color.RED,epoch,ev);
compactCalendar.addEvent(event);
ArrayList<String> eventList = new ArrayList<>();
eventList.add(ev);
hmap.put(date,eventList);
}
You need to cast the value of Hashmap to required type .
ArrayList<String> eventList =(ArrayList<String>) hmap.get(date);
The problem was that I was trying to get a value of a key that does not exist, I solved it like this:
if(!hmap.containsKey(date)){
ArrayList<String> eventList =new ArrayList<>();
eventList.add(ev);
hmap.put(date,eventList);
}
else{
ArrayList<String> eventList = hmap.get(date);
eventList.add(ev);
hmap.put(date,eventList);
}
Related
choose which diaper is chosen and record the date and time, every time a diaper is changed then save it.
I tried to use shared preference but i do not really know how to use it properly as I am completely new to this.
Try This
Define an Array list in which you will save your date time
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
List<Date> dateList = new ArrayList<>();
Then on diaper change function try this
public void onDiaperChange(Date date){
if(sharedpreferences.contains("DateList")){
dateList = sharedpreferences.getString("DateList","");
}
dateList.add(date);
sharedpreferences.putString(ObjectSerializer.serialize(dateList));
}
and to get the list use this
public void getAllDateTime(){
List<Date> fetchedData = new ArrayList<>();
fetchedData = (ArrayList<Date>) ObjectSerializer.deserialize(prefs.getString("DateList", ObjectSerializer.serialize(new ArrayList<Date>())));
} catch (IOException e) {
}
you can get ObjectSerializer from here ObjectSerializer
Use Realm to store data in database
To store data is like
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
DateModel datemodel = realm.createObject(DateM.class);
datemodel.setDate(your date);
realm.commitTransaction();
Get stored data :
RealmResults< DateModel > result = realm.where(DateModel.class)
.findAll();
i want to sort my data as par desc date in local cloudant query.
i have insert_ts in my database document.
my code for simple query is:-
public List<BasicDocumentMAP> allTasksWithAllArg(Map<String, Object> query, int skip, int limit, List<String> fields, List<Map<String, String>> sortDocument) {
int nDocs = this.sunDatastore.getDocumentCount();
QueryResult all = this.im.find(query, skip, limit, fields, sortDocument);
List<BasicDocumentMAP> arrayListBasicDocumentMAP = new ArrayList<>();
// Filter all documents down to those of type Task.
for (DocumentRevision rev : all) {
}}
please help me to sort data as date wise. thank you
Try this code:
Sql query :
Select _id , _rev , insert_ts , title from table
where year=2010 order by insert_ts
Cloudant query :
{
"selector": {
"year": {
"$gt": 2010
}
},
"fields": ["_id", "_rev", "insert_ts", "title"], //
"sort": [{"insert_ts": "asc"}]
}
Update: The original answer (at the bottom) shows you how to sort by year (OP asked how to get the year, so I assumed that was how they wanted to sort). This is how to sort by date:
Either change the insert_ts field to be a date, or add a new field that is a date, for example:
Date insertTsDate = null;
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy-hh-mm-ss-SS");
try {
insertTsDate = dateFormat.parse(insert_ts);
}
catch (Exception e) {
// handle exception
}
Then add a new field to your document called insert_ts_date (or whatever you want to call it), set it to the insertTsDate variable above, and sort like so:
List<Map<String, String>> sortDocument = new ArrayList<Map<String, String>>();
Map<String, String> sortByInsertTsDate = new HashMap<String, String>();
sortByInsertTsDate.put("insert_ts_date", "asc");
sortDocument.add(sortByInsertTsDate);
Original Answer:
I think you are going to have to explicitly add a year property to your document. If you have the year then just add it to your document. If you need to parse it from the string you can use regex or the Date/Calendar classes to parse the date:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy-hh-mm-ss-SS");
try {
Date date = dateFormat.parse(insert_ts);
Calendar c = Calendar.getInstance();
c.setTime(date);
int year = c.get(Calendar.YEAR);
}
catch (Exception e) {
// handle exception
}
Then issue your query as follows:
List<Map<String, String>> sortDocument = new ArrayList<Map<String, String>>();
Map<String, String> sortByYear = new HashMap<String, String>();
sortByYear.put("year", "asc");
sortDocument.add(sortByYear);
hi can you help me how to display the next 10 data in json by click the next button. i have 50 data and i want to display first 10. Then when I click the next button, 11-20 will display in listview. Ill post my code below and i dont have any idea how to do it. Also when i click previous button it will go back to previous listview which is 1-10. Thanks!
doctordata = new ArrayList<Map<String, String>>();
try {
jsonObject = new JSONObject(d);
jsonArray = jsonObject.optJSONArray("Doctors");
int arraylength = jsonArray.length();
for (int i = 0; i < arraylength; i++) {
Map<String, String> doctormap = new HashMap<String, String>();
JSONObject jsonChildNode = jsonArray.getJSONObject(i);
doctor = jsonChildNode.optString("Name").toString();
specialty = jsonChildNode.optString("Specialty").toString();
doctormap.put("name", doctor);
doctormap.put("specialty", specialty);
doctordata.add(doctormap);
}
String[] from = {"name", "specialty"};
int[] views = {R.id.doctorlist_name, R.id.doctorlist_specialty,};
final SimpleAdapter myadapter = new SimpleAdapter(MainActivity.this, doctordata, R.layout.doctor_list, from, views);
list.setAdapter(myadapter);
} catch (JSONException e) {
e.printStackTrace();
}
Define a class called Doctors, with fields String name and String Specialty, and add the Doctors to a list that you can iterate or convert to Array.
class Doctors {
private final String specialty;
private final String name;
public Doctors (){
specialty= "Spe1";
name = "name";
}
}
public String convertToJson(){
Gson gson = new Gson();
return gson.toJson(this);
}
Ok, there are several ways to do what do you want to achieve. I will explain you how I would do it:
Firts, in the doctorData arraylist you have all the items (50 items) that you need to show.
Create a partialDoctorData arraylist and assing to it only the first 10 items from doctorData, ok? and add this new arraylist to the SimpleAdaper.
So you will need to do instead of your code:
final SimpleAdapter myadapter = new SimpleAdapter(MainActivity.this, **partialDoctorData**, R.layout.doctor_list, from, views);
list.setAdapter(myadapter);
So when the user click in the next button, you can clean the partialDoctorData content, add from the 11-20 items from the original doctorData arrayList and and and directly call to the
myadapter.notifyDataSetChanged();
(you don't have to repeat the step to create a new SimpleAdapter, only changing the values of the arraylist and calling to this method, the content of the list is going to be updated with the content of the partialDoctorData)
Try ;)
Try this one:
Android ListView with Load More Button
You can use pagination when 10 items will be loaded after that you will call agin api to get next 10 items
Trying to make a listview with data from JSON. phonelist decalred below hold the data parsed from the json.
ArrayList<HashMap<String, String>> phonelist = new ArrayList<HashMap<String, String>>();
I am doing this in onCreateView of the fragment
for (int i = 0; i < phone.length(); i++) {
try {
JSONObject c = phone.getJSONObject(i);
String phId = c.getString("ph_id");
String phNo = c.getString("ph_no");
HashMap<String, String> map = new HashMap<String, String>();
map.put("ph_id", phId);
map.put("ph_no", phNo);
phonelist.add(map);
} catch (JSONException e) {
e.printStackTrace();
}
}
ListView list = (ListView) rootView.findViewById(R.id.listview1);
ListAdapter adapter = new SimpleAdapter(getActivity(), phonelist,
R.layout.list_item_phone,
new String[]{"ph_id", "ph_no"}, new int[]{
R.id.txtPhoneID, R.id.txtPhoneNum});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//TODO
}
});
The phonelist is getting populated from json and here is its content
[{ph_id=1, ph_no=0120-2550000}, {ph_id=2, ph_no=1860-180-3474}, {ph_id=3, ph_no=0120-4698114}, {ph_id=4, ph_no=0361-2525256}, {ph_id=5, ph_no=033-2525368}, {ph_id=6, ph_no=011-25252525}, {ph_id=7, ph_no=0361-2525257}, {ph_id=8, ph_no=033-2525369}, {ph_id=9, ph_no=011-25252526}, {ph_id=10, ph_no=0361-2525258}, {ph_id=11, ph_no=033-2525370}, {ph_id=12, ph_no=011-25252527}]
For some reason though, only the first item shows up in the listview.
Edit:
Declaration of the phone variable
JSONArray phone = null;
And then I am getting its value onCreate like below
phone = ((JSonArrayParser) getArguments().getParcelable("phoneJsonArray")).getJsonArray();
phone.length is showing correct value (12)
HashMap is specified as key and value, based on webpage # Map. Search text for "put (K key, V value)" for reference. In your code:
map.put("ph_id", phId);
map.put("ph_no", phNo);
I can see only 2 keys are added into this map object, even though you added lots of data from JSON.
As a suggestion, instead of literal string "ph_id" as the key, you can have variable phId as key instead, and the value can be phNo. That can be one code design.
Maybe it's a good idea if you post the SimpleAdapter also, especially in getView().
I've got a little problem, and i don't see it.
I retrieve Json data (the JSONArray) and i wanted to make a List of all the names in the JSONArray, something like this.
List list = new ArrayList<String>();
for(int i=0;i < data.length();i++){
list.add(data.getJSONObject(i).getString("names").toString());
}
And i wanted to take this list in an `ListView' so i did this :
ArrayList<String> test = history_share.list;
names_list = (String[]) test.toArray();
ArrayAdapter<String> adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, names_list);
setListAdapter(adapter);
(history_share is one of the method i created to take json data from an api .
Eclipse doesn't see any error, and me neither.
Can somebody help me please ?
Why do your methods have underscores in their names? Methods by convention begin with a lowercase letter. For example myMethod(). Class names begin with uppercase letters like MyClass. You should stick to that.
Also history_share is not a method the way you posted your code plus you won't be able to retrieve anything from a method by calling it that way.
A getter method just returns the defined member. I'm very surprised that Eclipse doesn't highlight that. Are you sure error checking is turned on?
Update: Naming your classes like already existing classes is generally a very bad idea and it gets even worse if you plan to use the original class somewhere or any class deriving that class. In the original Connection class I cant spot any static member called list which leads to the assumption that you've created your own Connection class. This doesn't have to be the problem here but it may raise problems in the future if you continue to do that.
for(int i=0;i < data.length();i++){
list.add(data.getJSONObject(i).getString("names").toString());
}
.getString("names") returns String, remove .toString()
Also,
ArrayAdapter<String> adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, names_list);
replace with
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, names_list);
You try this using ArrayList with Hashmap:
ArrayList<HashMap<String, String>> comunitylist = new ArrayList<HashMap<String, String>>();
String url =_url + _uid + uid;
JSONParstring jParser = new JSONParstring();
// getting JSON string from URL
String json = jParser.getJSONFromUrl(url,apikey);
Log.e("kPN", json);
try
{
JSONObject jobj = new JSONObject(json);
Log.e("kPN", json.toString());
System.out.print(json);
JSONArray comarray = jobj.getJSONArray(TAG_COMMU);
for(int i = 0; i <= comarray.length(); i++){
JSONObject c = comarray.getJSONObject(i);
Log.w("obj", c.toString());
JSONObject d = c.getJSONObject(TAG_PERSON);
Log.w("obj", d.toString());
String name =d.getString(TAG_NAME);
Log.w("name", name);
String nick =d.getString(TAG_NICK);
String home = d.getString(TAG_HOME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_NAME, name);
map.put(TAG_NICK, nick);
}
}
catch (JSONException ie)
{
}
list=(ListView)findViewById(R.id.list);
adapter=new Lazycommunity(this,listz);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#SuppressWarnings("unchecked")
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//Having Trouble with this line, how to retrieve value???
HashMap<String, String> map2 = (HashMap<String, String>) list.getAdapter().getItem(position);
Intent in = new Intent(getApplicationContext(), Communityprofile.class);
in.putExtra(TAG_NAME, map2.get(TAG_NAME));
in.putExtra(TAG_IMG, map2.get(TAG_IMG));
startActivity(in);
}
});