listview not updated baseadapter - android

i working baseadapter.
i have two datetimeformat 09/01/2014 and 09/10/2014.i checked days between there datetimes
public String getDateDiffString(Date dateOne, Date dateTwo)
{
long timeOne = dateOne.getTime();
long timeTwo = dateTwo.getTime();
long oneDay = 1000 * 60 * 60 * 24;
long delta = (timeTwo - timeOne) / oneDay;
if (delta > 0) {
for (int i = 0; i < delta; i++) {
}
return String.valueOf(delta) ;
}
else {
delta *= -1;
return String.valueOf(delta);
}
}
and also i wrote funtciton to change there datetimes format 09/01/2014 i changed it 1 Sep
public static String dateFormatterforLukka(String inputDate,int lenght) {
String inputFormat = "MM/dd/yyyy";
String outputFormat = String.valueOf(lenght)+"MMM";
Date parsed = null;
String outputDate = "";
try {
SimpleDateFormat df_input = new SimpleDateFormat(inputFormat,
new Locale("en", "US"));
SimpleDateFormat df_output = new SimpleDateFormat(outputFormat,
new Locale("en", "US"));
parsed = df_input.parse(inputDate);
outputDate = df_output.format(parsed);
Log.wtf("outputDate", outputDate);
} catch (Exception e) {
outputDate = inputDate;
}
return outputDate;
}
now i want to add my datetimes in listview like this .betweeen days there two datetimes . 1 Sep,2 Sep etc...
BaseAdapter Code
public class HollAdapters extends BaseAdapter {
private Context mContext;
private final ArrayList<CinemaInfoModel> hollitems;
private CinemaInfoModel objBean;
private TextView start_time,holle,time;
private static LayoutInflater inflater = null;
public HollAdapters(Context context, ArrayList<CinemaInfoModel> hollitems) {
mContext = context;
this.hollitems = hollitems;
inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return hollitems.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#SuppressLint("ViewHolder")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View grid;
grid = new View(mContext);
grid = inflater.inflate(R.layout.cinema_holl_adapter, null);
start_time = (TextView) grid.findViewById(R.id.adapter_day);
holle = (TextView) grid.findViewById(R.id.adapter_holl);
time = (TextView) grid.findViewById(R.id.adapter_time);
objBean = hollitems.get(position);
start_time.setText(objBean.getStartTime());
holle.setText(objBean.getHole());
String start_time=objBean.getTime();
start_time=start_time.replace(",", "\n");
time.setText(start_time);
return grid;
}
}
this is a main java code
SimpleDateFormat df = new SimpleDateFormat(
"MM/dd/yyyy");
Date _d = df.parse("09/01/2014");
Date _d1 = df.parse("09/10/2014");
SimpleDateFormat new_df = new SimpleDateFormat(
"d MMM");
String _s1 = new_df.format(_d1);
String datetimeis=getDateDiffString(_d1, _d);
Log.wtf("differentis ", datetimeis);
int abc=Integer.parseInt(datetimeis);
for (int l = 0; l < abc; l++) {
String ab = dateFormatterforLukka(timeJsonArray
.getJSONObject(k).getString("start_time"),l++);
Log.wtf("timeeeeeeeee", ab);
cinemaTime.setStartTime(ab);
cinemaTime.setEndTime(_s1);
cinemaTimesArray.add(cinemaTime);
}
when i run my app only 8 sep added always in my listview ,but i loged and in log i have
different result, meybe listview did not updated
what am i doing wrong? if anyone knows solution please help me

Create a methord in adapter class
public void setdata(ArrayList<CinemaInfoModel> hollitems_temp) {
this.hollitems=hollitems_temp;
}
for (int l = 0; l < abc; l++) {
String ab = dateFormatterforLukka(timeJsonArray
.getJSONObject(k).getString("start_time"),l++);
Log.wtf("timeeeeeeeee", ab);
cinemaTime.setStartTime(ab);
cinemaTime.setEndTime(_s1);
cinemaTimesArray.add(cinemaTime);
}
after this loop i am assuming that cinematimesarray is of type CinemaInfoModel
youradapter.setdata(cinemaTimesArray);
youradapter.notifyDataSetChanged();
put debugger in your getview methord and check;

Related

How to add timestamps to an adapter

I am trying to make a Chat bubble and I need to insert the timestamps in each bubble, I have my adapter to insert the messages but I do not know how to add the timestamps, someone could tell me how to do it.
Here the MainActivity code:
public class MainActivity extends AppCompatActivity {
private ListView listView;
private View btnSend;
private EditText editText;
boolean myMessage = true;
private List<ChatBubble> ChatBubbles;
private ArrayAdapter<ChatBubble> adapter;
private TextView dateTimeTx;
private TextView dateTimeRx;
private String dateTime;
private String timestamp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ChatBubbles = new ArrayList<>();
listView = (ListView) findViewById(R.id.list_msg);
btnSend = findViewById(R.id.btn_chat_send);
editText = (EditText) findViewById(R.id.msg_type);
//set ListView adapter first
adapter = new MessageAdapter(this, R.layout.tx_chat_bubble, ChatBubbles);
listView.setAdapter(adapter);
//event for button SEND
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (editText.getText().toString().trim().equals("")) {
Toast.makeText(MainActivity.this, "Please input some text...", Toast.LENGTH_SHORT).show();
} else {
//add message to list
ChatBubble ChatBubble = new ChatBubble(editText.getText().toString(), myMessage, timestamp.toString() );
ChatBubbles.add(ChatBubble);
adapter.notifyDataSetChanged();
editText.setText("");
if (myMessage) {
myMessage = false;
} else {
myMessage = true;
}
}
}
});
}
}
But I have a error in :
ChatBubble ChatBubble = new ChatBubble(editText.getText().toString(), myMessage, timestamp.toString() );
Here mi Adapter code:
public class MessageAdapter extends ArrayAdapter<ChatBubble> {
private Activity activity;
private List<ChatBubble> messages;
private String dateTime;
private SimpleDateFormat simpleDateFormat ;
public MessageAdapter(Activity context, int resource, List<ChatBubble> objects) {
super(context, resource, objects);
this.activity = context;
this.messages = objects;
String isoDatePattern = "dd/MM/yyyy HH:mm";
simpleDateFormat = new SimpleDateFormat(isoDatePattern);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
int layoutResource = 0; // determined by view type
ChatBubble ChatBubble = getItem(position);
int viewType = getItemViewType(position);
if (ChatBubble.myMessage()) {
layoutResource = R.layout.tx_chat_bubble;
} else {
layoutResource = R.layout.rx_chat_bubble;
}
if (convertView != null) {
holder = (ViewHolder) convertView.getTag();
} else {
convertView = inflater.inflate(layoutResource, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
//set message content
holder.msg.setText(ChatBubble.getContent());
holder.dateTimeTx.setText(ChatBubble.getTimestamp());
return convertView;
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getItemViewType(int position) {
return position % 2;
}
private class ViewHolder {
private TextView msg;
private TextView dateTimeTx;
public ViewHolder(View v) {
msg = (TextView) v.findViewById(R.id.txt_msg);
dateTimeTx = (TextView) v.findViewById(R.id.time_msg);
}
}
private String readFechaActual(long timestamp){
return simpleDateFormat.format(new Date(timestamp));
}
}
But I have another error in:
holder.dateTimeTx.setText(ChatBubble.getTimestamp());
Here is the ChatBubble class:
public class ChatBubble {
private String content;
private boolean myMessage;
private long timestamp;
public ChatBubble(String content, boolean myMessage, long timestamp) {
this.content = content;
this.myMessage = myMessage;
this.timestamp = timestamp;
}
public String getContent() {
return content;
}
public boolean myMessage() {
return myMessage;
}
public long getTimestamp() {
return timestamp;
}
}
Create single (to avoid unused resource requirements) SimpleDateFormat in an adapter constructor:
private SimpleDateFormat simpleDateFormat ;
public MessageAdapter(Activity context, int resource, List<ChatBubble> objects) {
super(context, resource, objects);
this.activity = context;
this.messages = objects;
String isoDatePattern = "dd/MM/yyyy HH:mm";
simpleDateFormat = new SimpleDateFormat(isoDatePattern);
}
Update the helper method to return formatted date string:
private String readFechaActual(long timestamp){
return simpleDateFormat.format(new Date(timestamp));
}
}
Use it in getView:
//set message content
holder.msg.setText(ChatBubble.getContent());
holder.dateTimeTx.setText("" + ChatBubble.getTimestamp()); // <--- ADD HERE
The adapter only connects View and Model, but actual data keeps in model, so you should change the BubbleChat class and add timestamp field:
public class ChatBubble {
private String content;
private boolean myMessage;
private long timestamp;
public ChatBubble(String content, boolean myMessage, long timestamp) {
this.content = content;
this.myMessage = myMessage;
this.timestamp = timestamp;
}
public String getContent() {
return content;
}
public boolean myMessage() {
return myMessage;
}
public long getTimestamp() {
return timestamp;
}
}
You should set the time in getView, same way you set the bubble's message.
You already have the field in the ViewHolder.
Also, ChatBubble ChatBubble = getItem(position); should be ChatBubble chatBubble = getItem(position);
And please use RecyclerView
Create a model
public class TimeDifference {
int years;
int months;
int days;
int hours;
int minutes;
int seconds;
String differenceString;
public TimeDifference(Context mContext, Date curdate, Date olddate) {
String y = " "+mContext.getString(R.string.year);
String ys = " "+mContext.getString(R.string.years);
String m = " "+mContext.getString(R.string.month);
String ms = " "+mContext.getString(R.string.months);
String d = " "+mContext.getString(R.string.day);
String ds = " "+mContext.getString(R.string.days);
String h = " "+mContext.getString(R.string.hour);
String hs = " "+mContext.getString(R.string.hours);
String mm = " "+mContext.getString(R.string.minute);
String mms= " "+mContext.getString(R.string.minutes);
String s = " "+mContext.getString(R.string.second);
String ss = " "+mContext.getString(R.string.seconds);
String a = " "+mContext.getString(R.string.ago);
float diff=curdate.getTime() - olddate.getTime();
if (diff >= 0) {
int yearDiff = Math.round( ( diff/ (365l*2592000000f))>=1?( diff/ (365l*2592000000f)):0);
if (yearDiff > 0) {
years = yearDiff;
setDifferenceString(years + (years == 1 ? y : ys) + a);
} else {
int monthDiff = Math.round((diff / 2592000000f)>=1?(diff / 2592000000f):0);
if (monthDiff > 0) {
if (monthDiff > 11)
monthDiff = 11;
months = monthDiff;
setDifferenceString(months + (months == 1 ? m : ms) + a);
} else {
int dayDiff = Math.round((diff / (86400000f))>=1?(diff / (86400000f)):0);
if (dayDiff > 0) {
days = dayDiff;
if(days==30)
days=29;
setDifferenceString(days + (days == 1 ? d : ds) + a);
} else {
int hourDiff = Math.round((diff / (3600000f))>=1?(diff / (3600000f)):0);
if (hourDiff > 0) {
hours = hourDiff;
setDifferenceString( hours + (hours == 1 ? h : hs) + a);
} else {
int minuteDiff = Math.round((diff / (60000f))>=1?(diff / (60000f)):0);
if (minuteDiff > 0) {
minutes = minuteDiff;
setDifferenceString(minutes + (minutes == 1 ? mm : mms) + a);
} else {
int secondDiff =Math.round((diff / (1000f))>=1?(diff / (1000f)):0);
if (secondDiff > 0)
seconds = secondDiff;
else
seconds = 1;
setDifferenceString(seconds + (seconds == 1 ? s : ss) + a);
}
}
}
}
}
}
}
public String getDifferenceString() {
return differenceString;
}
public void setDifferenceString(String differenceString) {
this.differenceString = differenceString;
}
public int getYears() {
return years;
}
public void setYears(int years) {
this.years = years;
}
public int getMonths() {
return months;
}
public void setMonths(int months) {
this.months = months;
}
public int getDays() {
return days;
}
public void setDays(int days) {
this.days = days;
}
public int getHours() {
return hours;
}
public void setHours(int hours) {
this.hours = hours;
}
public int getMinutes() {
return minutes;
}
public void setMinutes(int minutes) {
this.minutes = minutes;
}
public int getSeconds() {
return seconds;
}
public void setSeconds(int seconds) {
this.seconds = seconds;
}
}
Create Utils.java and add this
public static Date getDefaultDate(){
SimpleDateFormat f = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
f.setTimeZone(TimeZone.getDefault());
Date nowDate = new Date();
try {
nowDate = dateFormatter.parse(f.format(new Date()));
}catch (ParseException e){
e.printStackTrace();
}
return nowDate;
}
public static Date newDate(String timeStamp){
Date OurDate = null;
try{
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date value = formatter.parse(timeStamp);
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
dateFormatter.setTimeZone(TimeZone.getDefault());
String n = dateFormatter.format(value);
OurDate = dateFormatter.parse(n);
}catch (ParseException e){
e.printStackTrace();
}
return OurDate;
}
For pass date into Adapter
TimeDifference now = new TimeDifference(mContext,Utils.getDefaultDate(),Utils.newDate("Your current time");
Toast.makeText(context, "Posted by "+now.getDifferenceString(), Toast.LENGTH_SHORT).show();

Can fragments retain the state of collected data of cardviews

Before I change my design of my android application, I was wondering if I can retain the state of my fragment including all data collected when it is recreated. In my fragment i have an async task that collects the proper data usinf json and it publishes them to diffeerent cardviews. Here is my code:
LatestEventsFragment.java
public class LatestEventsFragment extends Fragment {
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
ArrayList<Event> arrayList = new ArrayList();
ProgressDialog progressDialog;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
setRetainInstance(true);
View view = inflater.inflate(R.layout.events_list, container, false);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
recyclerView = (RecyclerView)view.findViewById(R.id.events_recycler);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
adapter = new EventsRecyclerAdapter(arrayList);
recyclerView.setAdapter(adapter);
EventsAsyncTask eventsAsyncTask = new EventsAsyncTask();
eventsAsyncTask.execute();
return view;
}
class EventsAsyncTask extends AsyncTask<String, Event, String> {
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setTitle("Please wait...");
progressDialog.setMessage("Loading");
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected void onPostExecute(String s) {
progressDialog.dismiss();
}
#Override
protected void onProgressUpdate(Event... values) {
arrayList.add(values[0]);
adapter.notifyDataSetChanged();
}
#Override
protected String doInBackground(String... params) {
try {
ServerConfig serverConfig = new ServerConfig();
URL url = new URL(serverConfig.getEvents_url());
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line = "";
while((line = bufferedReader.readLine()) != null){
stringBuilder.append(line+"\n");
}
httpURLConnection.disconnect();
String json_string = stringBuilder.toString().trim();
JSONObject jsonObject = new JSONObject(json_string);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
while(count<jsonArray.length()){
JSONObject JO = jsonArray.getJSONObject(count);
count++;
String jsonString = JO.get("image").toString();
byte[] temp = Base64.decode(jsonString.getBytes(), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(temp, 0, temp.length);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone("UCT"));
Date date = dateFormat.parse(JO.getString("date_posted"));
Date server_date = dateFormat.parse(JO.getString("server_date"));
Event event = new Event(JO.getString("name"), decodedByte, JO.getInt("views"), date, server_date);
publishProgress(event);
Thread.sleep(500);
}
} catch (Exception e){
e.printStackTrace();
}
return null;
}
}
}
EventsRecyclerAdapter.java
public class EventsRecyclerAdapter extends RecyclerView.Adapter<EventsRecyclerAdapter.RecyclerViewHolder>{
ArrayList<Event> arrayList = new ArrayList<>();
public EventsRecyclerAdapter(ArrayList<Event> arrayList){
this.arrayList = arrayList;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.latest_events_card, parent, false);
return new RecyclerViewHolder(view);
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
Event event = arrayList.get(position);
try{
String views = String.valueOf(event.getViews())+" views";
String date_string = getTime(event.getServer_date().getTime() - event.getDate_posted().getTime());
holder.name.setText(event.getName());
holder.image.setImageBitmap(event.getImage());
holder.views.setText(views);
holder.date_posted.setText(date_string);
}catch (Exception e){
e.printStackTrace();
}
}
private String getTime(Long time_difference){
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long elapsedDays = time_difference / daysInMilli;
int daysInt = (int)elapsedDays;
time_difference = time_difference % daysInMilli;
long elapsedHours = time_difference / hoursInMilli;
int hoursInt = (int)elapsedHours;
time_difference = time_difference % hoursInMilli;
long elapsedMinutes = time_difference / minutesInMilli;
int minutesInt = (int)elapsedMinutes;
//time_difference = time_difference % minutesInMilli;
//long elapsedSeconds = time_difference / secondsInMilli;
String date_string = String.valueOf(daysInt);
if(daysInt > 0) {
if (daysInt == 1) {
date_string = "1 Day";
} else if (daysInt > 1) {
date_string = daysInt + " Days";
}
}else if(hoursInt > 0){
if(hoursInt == 1){
date_string = "1 Hour ";
if(minutesInt > 1){
date_string = date_string + minutesInt + " Minutes";
}
} else if(hoursInt > 1){
date_string = hoursInt + " Hours ";
if(minutesInt > 1){
date_string = date_string + minutesInt + " Minutes";
}
}
}else if(minutesInt > 0){
if (minutesInt == 1) {
date_string = "1 Minute";
} else if (minutesInt > 1) {
date_string = minutesInt + " Minutes";
}
}
return date_string + " ago";
}
#Override
public int getItemCount() {
return arrayList.size();
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder{
protected TextView name, views, date_posted, start_date, end_date;
protected ImageView image;
public RecyclerViewHolder(View v){
super(v);
name = (TextView)v.findViewById(R.id.name);
image = (ImageView)v.findViewById(R.id.thumbnail);
views = (TextView)v.findViewById(R.id.views);
date_posted = (TextView)v.findViewById(R.id.date_posted);
}
}
}
and finally Events.java
public class Event {
private int id;
private String name;
private String description;
private String start_date;
private String end_date;
private double entrance_fee;
private Bitmap image;
private int views;
private Date date_posted;
private Date server_date;
public Event(String name, Bitmap image, int views, Date date_posted, Date server_date){
//int id, String name, , String start_date, double entrance_fee, Bitmap image, int views
this.setDescription(description);
this.setEnd_date(end_date);
this.setEntrance_fee(entrance_fee);
this.setId(id);
this.setImage(image);
this.setName(name);
this.setViews(views);
this.setStart_date(start_date);
this.setDate_posted(date_posted);
this.setServer_date(server_date);
}
public Date getServer_date() {
return server_date;
}
public void setServer_date(Date server_date) {
this.server_date = server_date;
}
public Date getDate_posted() {
return date_posted;
}
public void setDate_posted(Date date_posted) {
this.date_posted = date_posted;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getStart_date() {
return start_date;
}
public void setStart_date(String start_date) {
this.start_date = start_date;
}
public String getEnd_date() {
return end_date;
}
public void setEnd_date(String end_date) {
this.end_date = end_date;
}
public double getEntrance_fee() {
return entrance_fee;
}
public void setEntrance_fee(double entrance_fee) {
this.entrance_fee = entrance_fee;
}
public Bitmap getImage() {
return image;
}
public void setImage(Bitmap image) {
this.image = image;
}
public int getViews() {
return views;
}
public void setViews(int views) {
this.views = views;
}
}
You can use onSaveInstanceState inside your Fragment to save your data, then check the savedInstanceState variable inside onCreateView to see if it has data. If it does, just retrieve the data to recreate your view.
Inside Fragment:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
if(mDataToSave != null) {
savedInstanceState.putString("myData", mDataToSave);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
if(savedInstanceState != null){
String restoredData = (String)savedInstanceState.getString("myData");
//do something with restoredData
}
return rootView;
}
Just remember to change the put and get: savedInstanceState.putString() to savedInstanceState.put<WhateverYourDataTypeIs>()
If you're adding your Fragment through a Fragment Transaction in your Main Activity, make sure to only add it if the Main Activity's savedInstanceState is null. That way you won't replace the Fragment if it's already been added.
Inside Activity (if you have a Fragment Transaction):
if(savedInstanceState == null) {
Fragment newFragment = new MyFragment();
//add main fragment to fragment frame
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().add(R.id.fragment_container, newFragment).commit();
}

Get the value of clicked Item of a custom listview?

I have created a Custom listview and set data by parsing a link and sorted them inside the list. Now when I am going to make a click and get the value of the individual object of a row I can't get the object of clicked row.
public class MainActivity extends Activity implements OnChildClickListener,
OnItemClickListener {
private ExpandableListView mExpandableListView;
private List<GroupEntity> mGroupCollection;
String URL;
ArrayList<EventParsingClass> EventObject_Collection = new ArrayList<EventParsingClass>();
ArrayList<Date> DateArray = new ArrayList<Date>();
ArrayList<ArrayList<EventParsingClass>> arrayOfEventDescription = new ArrayList<ArrayList<EventParsingClass>>();
MyListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.event_mainactivity);
prepareResource();
initPage();
URL = "http://..............";
ParsingWithURL(URL);
}
private void ParsingWithURL(String uRL2) {
// TODO Auto-generated method stub
new JSONPARSINGFOREVENTSTREAM().execute(URL);
}
private class JSONPARSINGFOREVENTSTREAM extends
AsyncTask<String, Void, String> {
private final String TAG_ID = "id";
private final String TAG_Title = "title";
private final String TAG_Description = "description";
private final String TAG_StartDate = "start_datetime";
private final String TAG_EndDate = "end_datetime";
private final String TAG_City = "place_city";
private final String TAG_Club = "place_club";
private final String TAG_AgeLimit = "event_agelimit";
private static final String TAG_Event_streamable = "data";
EventParsingClass EPC;
JSONArray streamable = null;
ProgressDialog pDialog;
#SuppressLint("SimpleDateFormat")
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
Log.d("************PARAMS", arg0[0]);
JSONParser jparser = new JSONParser();
JSONObject json = jparser.getJSONFromUrl(arg0[0]);
try {
streamable = json.getJSONArray(TAG_Event_streamable);
for (int i = 0; i < streamable.length(); i++) {
EPC = new EventParsingClass();
JSONObject c = streamable.getJSONObject(i);
EPC.setId(c.getString(TAG_ID));
EPC.setPlace_city(c.getString(TAG_City));
EPC.setPlace_club(c.getString(TAG_Club));
EPC.setTitle(c.getString(TAG_Title));
EPC.setDescription(c.getString(TAG_Description));
EPC.setSratdate_time(c.getString(TAG_StartDate));
EPC.setEnddate_time(c.getString(TAG_EndDate));
EPC.setEvent_agelimit(c.getString(TAG_AgeLimit));
long difference = EPC.geEnddate_time_date().getTime()
- EPC.getSratdate_time_date().getTime();
int day_difference = (int) (difference / (1000 * 3600 * 24));
// Log.d("Difference", "" + day_difference);
if (day_difference == 0) {
AddDay(EPC.getSratdate_time_date());
} else {
if (DateArray.size() == 0) {
DateArray.add(EPC.getSratdate_time_date());
long startday = EPC.getSratdate_time_date()
.getTime();
for (int k = 1; k <= day_difference; k++) {
long constructedday = startday
+ (1000 * 3600 * 24) * k;
Date Constructed_value = new Date(
constructedday);
DateArray.add(Constructed_value);
}
} else {
AddDay(EPC.getSratdate_time_date());
long startday = EPC.getSratdate_time_date()
.getTime();
for (int k = 1; k <= day_difference; k++) {
long constructedday = startday
+ (1000 * 3600 * 24) * k;
Date Constructed_value = new Date(
constructedday);
AddDay(Constructed_value);
}
}
}
EventObject_Collection.add(EPC);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
private void AddDay(Date value) {
// TODO Auto-generated method stub
if (DateArray.size() == 0) {
DateArray.add(value);
} else {
boolean b = true;
for (Date s : DateArray) {
if (s.equals(value)) {
b = false;
break;
}
}
if (b) {
DateArray.add(value);
}
}
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.d("+++++++++++++++++++++++number of Items in List", ""
+ DateArray.size());
AddDetailedItemToListView();
AddHeaderItemsToListView();
pDialog.dismiss();
}
private void AddDetailedItemToListView() {
// TODO Auto-generated method stub
for (Date s : DateArray) {
ArrayList<EventParsingClass> constructed_arrayfor_items = new ArrayList<EventParsingClass>();
for (int g = 0; g < EventObject_Collection.size(); g++) {
EventParsingClass EVPC = EventObject_Collection.get(g);
long new_startdate = EVPC.getSratdate_time_date().getTime();
long new_endtdate = EVPC.geEnddate_time_date().getTime();
long date = s.getTime();
if (date >= new_startdate && date <= new_endtdate) {
Log.d("^^^^^^^^^^^ Value Of Date ", "" + s);
Log.d("^^^^^^^^^^^ Value Of StartDay ",
"" + EVPC.getSratdate_time_date());
Log.d("^^^^^^^^^^^ Value Of EndDay ",
"" + EVPC.geEnddate_time_date());
constructed_arrayfor_items.add(EVPC);
}
}
arrayOfEventDescription.add(constructed_arrayfor_items);
Log.d("^^^^^^^^^^^^^^^^^^^arrayOfEventDescription", ""
+ arrayOfEventDescription);
}
}
private void AddHeaderItemsToListView() {
// TODO Auto-generated method stub
ListView lv = (ListView) findViewById(R.id.list_evevnt);
LayoutInflater i = LayoutInflater.from(MainActivity.this);
List<Item> items = new ArrayList<Item>();
int length_of_datearray = DateArray.size();
Log.d("!!!!!!!!!!!!!!!", "" + DateArray.size());
Log.d("EEEEEEEEEEEEEEEEEEEE", "" + arrayOfEventDescription.size());
for (ArrayList<EventParsingClass> It : arrayOfEventDescription) {
Log.d("", "" + It.size());
for (EventParsingClass oETC : It) {
Log.d("*******" + oETC.getTitle(),
"" + oETC.getSratdate_time_date());
}
}
for (int m = 0; m < length_of_datearray; m++) {
String day_of_header = (String) android.text.format.DateFormat
.format("EEEE", DateArray.get(m));
String month_of_header = (String) android.text.format.DateFormat
.format("MMM", DateArray.get(m));
String date_of_header = (String) android.text.format.DateFormat
.format("dd", DateArray.get(m));
String total_header = day_of_header + " " + month_of_header
+ " " + date_of_header;
items.add(new Header(i, "" + total_header));
ArrayList<EventParsingClass> Arraylist_for_loop = arrayOfEventDescription
.get(m);
for (int h = 0; h < Arraylist_for_loop.size(); h++) {
String description = Arraylist_for_loop.get(h).getId();
String title = Arraylist_for_loop.get(h).getTitle();
String place_city = Arraylist_for_loop.get(h)
.getPlace_city();
String age_limit = Arraylist_for_loop.get(h)
.getEvent_agelimit();
String dayOfTheWeek = (String) android.text.format.DateFormat
.format("EEEE", Arraylist_for_loop.get(h)
.getSratdate_time_date());
String DayofWeek = dayOfTheWeek;
if (!(dayOfTheWeek == day_of_header)) {
DayofWeek = day_of_header;
}
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date d = new Date();
String Today = sdf.format(d);
String Value_of_today = "";
if (Today.contentEquals(DayofWeek)) {
Value_of_today = "Today";
}
items.add(new EventItem(i, Value_of_today, DayofWeek,
"12:00", title, description, place_city, "10",
age_limit));
}
}
MyListAdapter adapter = new MyListAdapter(MainActivity.this, items);
lv.setAdapter(adapter);
lv.setOnItemClickListener(MainActivity.this);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(true);
pDialog.show();
}
}
private void prepareResource() {
mGroupCollection = new ArrayList<GroupEntity>();
for (int i = 1; i < 3; i++) {
GroupEntity ge = new GroupEntity();
ge.Name = "City " + i;
for (int j = 1; j < 4; j++) {
GroupItemEntity gi = ge.new GroupItemEntity();
gi.Name = "Venu" + j;
ge.GroupItemCollection.add(gi);
}
mGroupCollection.add(ge);
}
}
private void initPage() {
mExpandableListView = (ExpandableListView) findViewById(R.id.expandableListView);
ExpandableListAdapter adapter = new ExpandableListAdapter(this,
mExpandableListView, mGroupCollection);
mExpandableListView.setAdapter(adapter);
mExpandableListView.setOnChildClickListener(this);
}
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
Toast.makeText(getApplicationContext(), childPosition + "Clicked",
Toast.LENGTH_LONG).show();
return true;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
EventParsingClass obj = (EventParsingClass) parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), obj.getPlace_city() + "Clicked",Toast.LENGTH_LONG).show();
}
}
How can I proceed in these two scenarios?
EventParsingClass EPSP= ??? and
EPSP.getid= ??
fetch[0]="XXX"
fetch[1]="YYY"
fetch[2]="ZZZ"
lv.setOnItemClickListener(MainActivity.this);
public void onItemClick(AdapterView<?> parent, View view, int position,long id)
Toast.makeText(getApplicationContext(), fetch[position] + "Clicked",
Toast.LENGTH_LONG).show();
}
just declare fetch[position] to get the value of clicked item. hope this will give you some solution.
Use int position to find out values from your data list (array list or what ever you used).
lv.setOnItemClickListener(MainActivity.this);
public void onItemClick(AdapterView<?> parent, View view, int position,long id)
Toast.makeText(getApplicationContext(), EPSP.getid(position) + "Clicked",Toast.LENGTH_LONG).show();
}
EventItem item = (EventItem) parent.getItemAtPosition(position);
Now you have a hold of EventItem. So you can start using the get methods of your EventItem class in order to get whatever you want from it.
I got the solution:
EventParsingClass new_method(int value) {
int item_count = 0;
for (int i = 0; i < arrayOfEventDescription.size(); i++) {
ArrayList<EventParsingClass> Arraylist_for_loop = arrayOfEventDescription
.get(i);
item_count++;
for (int j = 0; j < Arraylist_for_loop.size(); j++) {
if (value == item_count) {
return Arraylist_for_loop.get(j);
}
item_count++;
}
}
return null;
}
And call it from here:
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
EventParsingClass newObject = new_method(arg2);
if (newObject == null) {
} else {
Log.d("Generated Value Id : ", "" + newObject.getId());
Toast.makeText(getApplicationContext(),
"Item Clicked" + arg2 + "-----" + newObject.getTitle(),
Toast.LENGTH_LONG).show();
}
}

Missing data in Section list view in Android?

I am working with Section list view in Android to show Call details according to date.
Means under a particular date number of call details. But when I get 2 calls under the same date, the last date is visible only and the list does not show the rest of the calls of that date.
Calls under different dates are shown correctly but calls under same date are not shown correctly, only the last call is shown.
I am using the below code:
public String response = "{ \"Message\":\"Success\", "
+ "\"Data\":[ { \"ACCOUNT\":\"000014532497\", "
+ "\"DATE\":\"8/6/2006\", \"TIME\":\"15:37:14\", "
+ "\"CH_ITEM\":\"341T\", \"ITEM\":\"TIMEUSED\", "
+ "\"DESCRIPTION\":\"FROM3103475779\", \"DETAIL\":"
+ "\"UnitedKingdom011441980849463\", \"QUANTITY\":84, "
+ "\"RATE\":0.025, \"AMOUNT\":2.1, \"ACTUAL\":83.2, "
+ "\"NODE_NAME\":\"TNT02\", \"USER_NAME\":\"Shailesh Sharma\""
+ ", \"MODULE_NAME\":\"DEBIT\", \"ANI\":\"3103475779\", "
+ "\"DNIS\":\"3103210104\", \"ACCOUNT_GROUP\":\"WEBCC\", "
+ "\"SALES_REP\":\"sascha_d\", \"SALES_REP2\":\"\", \"SALES_REP3"
+ "\":\"\", \"IN_PORT\":\"I10\", \"EXTRA1\":\"RATE\", \"EXTRA2\":"
+ "\"44\", \"EXTRA3\":\"UnitedKingdom\", \"OUT_PORT\":\"I70\", "
+ "\"CRN\":\"WEBCC\", \"CallId\":null, \"ID\":4517734, \"PhoneNumber"
+ "\":\"011441980849463\" }, {\"ACCOUNT\":\"000014532497\",\"DATE\":"
+ "\"8/6/2006\",\"TIME\":\"09:22:57\",\"CH_ITEM\":\"541T\",\"ITEM\":"
+ "\"TIMEUSED\",\"DESCRIPTION\":\"FROM3103475779\",\"DETAIL\":"
+ "\"UnitedKingdom011447914422787\",\"QUANTITY\":1,\"RATE\":0.29,"
+ "\"AMOUNT\":0.29,\"ACTUAL\":0.5,\"NODE_NAME\":\"TNT02\",\"USER_NAME"
+ "\":\"Tusshar\",\"MODULE_NAME\":\"DEBIT\",\"ANI\":\"3103475779\",\"DNIS"
+ "\":\"6173950047\",\"ACCOUNT_GROUP\":\"WEBCC\",\"SALES_REP\":\"sascha_d"
+ "\",\"SALES_REP2\":\"\",\"SALES_REP3\":\"\",\"IN_PORT\":\"I30\",\"EXTRA1"
+ "\":\"RATE\",\"EXTRA2\":\"44\",\"EXTRA3\":\"UnitedKingdom-Special\","
+ "\"OUT_PORT\":\"I90\",\"CRN\":\"WEBCC\",\"CallId\":null,\"ID\":4535675,"
+ "\"PhoneNumber\":\"011447914422787\"}, ], \"NumberOfContacts\":2, "
+ "\"TotalCharges\":4.830000000000001 }";
try {
JSONObject jsonObj = new JSONObject(response);
String message = jsonObj.getString("Message");
if (message != null && message.equalsIgnoreCase("Success")) {
JSONArray dataArray = jsonObj.getJSONArray("Data");
System.out.println(dataArray.length());
for (int i = 0; i < dataArray.length(); i++) {
JSONObject history = dataArray.getJSONObject(i);
_date = history.getString("DATE");
String updatedDate = createDateFormat(_date);
// notes =new ArrayList<String>();
itemList = new ArrayList<Object>();
// ADDING DATE IN THE ARRAYLIST<String>
days.add(updatedDate);
_username = history.getString("USER_NAME");
_number = history.getString("PhoneNumber");
_time = history.getString("TIME");
_amount = history.getString("AMOUNT");
_duration = history.getString("QUANTITY");
/*
* notes.add(_username); notes.add(_number);
* notes.add(_time);
*/
AddObjectToList(_username, _number, _time, _amount,
_duration);
// listadapter = new <String>(this, R.layout.list_item,
// notes);
listadapter = new ListViewCustomAdapter(this, itemList);
adapter.addSection(days.get(i), listadapter);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public class SeparatedListAdapter extends BaseAdapter {
/*
* public final Map<String, Adapter> sections = new
* LinkedHashMap<String, Adapter>();
*/
public final Map<String, Adapter> sections = new LinkedHashMap<String, Adapter>();
public final ArrayAdapter<String> headers;
public final static int TYPE_SECTION_HEADER = 0;
public SeparatedListAdapter(Context context) {
headers = new ArrayAdapter<String>(context, R.layout.list_header);
}
public void addSection(String section, Adapter adapter) {
this.headers.add(section);
this.sections.put(section, adapter);
}
public Object getItem(int position) {
for (Object section : this.sections.keySet()) {
Adapter adapter = sections.get(section);
int size = adapter.getCount() + 1;
// check if position inside this section
if (position == 0)
return section;
if (position < size)
return adapter.getItem(position - 1);
// otherwise jump into next section
position -= size;
}
return null;
}
public int getCount() {
// total together all sections, plus one for each section header
int total = 0;
for (Adapter adapter : this.sections.values())
total += adapter.getCount() + 1;
return total;
}
#Override
public int getViewTypeCount() {
// assume that headers count as one, then total all sections
int total = 1;
for (Adapter adapter : this.sections.values())
total += adapter.getViewTypeCount();
return total;
}
#Override
public int getItemViewType(int position) {
int type = 1;
for (Object section : this.sections.keySet()) {
Adapter adapter = sections.get(section);
int size = adapter.getCount() + 1;
// check if position inside this section
if (position == 0)
return TYPE_SECTION_HEADER;
if (position < size)
return type + adapter.getItemViewType(position - 1);
// otherwise jump into next section
position -= size;
type += adapter.getViewTypeCount();
}
return -1;
}
public boolean areAllItemsSelectable() {
return false;
}
#Override
public boolean isEnabled(int position) {
return (getItemViewType(position) != TYPE_SECTION_HEADER);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
int sectionnum = 0;
for (Object section : this.sections.keySet()) {
Adapter adapter = sections.get(section);
int size = adapter.getCount() + 1;
// check if position inside this section
if (position == 0)
return headers.getView(sectionnum, convertView, parent);
if (position < size)
return adapter.getView(position - 1, convertView, parent);
// otherwise jump into next section
position -= size;
sectionnum++;
}
return null;
}
#Override
public long getItemId(int position) {
return position;
}
}
This is my actual requirement:
This is what is happening right now.
SectionListExampleActivity is my Main class in which I am getting RESPONSE from JSON web service. In getJSONResposne method I am calling the EntryAdaptor.
There are two separate geter setter classes for SECTION HEADER and ITEM ENTRY for each header.
public class SectionListExampleActivity extends Activity implements OnClickListener, OnItemSelectedListener, IServerResponse {
/** Called when the activity is first created. */
private ArrayList<Item> items = new ArrayList<Item>();
boolean firstTime = true;
private Spinner _spinner=null;
private ArrayAdapter _amountAdaptor = null;
private ArrayList<String> _monthList =new ArrayList<String>();
private ListView _list=null;
private Button _monthButton=null;
private ImageButton _backImageButton=null;
private ImageButton _headerImageButton=null;
private String _token;
private String _account;
private Point p=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.account_history);
String response = this.getIntent().getExtras().getString("history_resp");
_token = Constant.AUTH_TOKEN;
_account = Constant.ACCOUNT_NUM;
_list = (ListView)findViewById(R.id.listview);
getJSON_Response(response,Constant.PID_ACCOUNT_HISTORY);
EntryAdapter adapter = new EntryAdapter(this, items);
_list.setAdapter(adapter);
_monthList.add("Months");
_monthList.add("January");
_monthList.add("February");
_monthList.add("March");
_monthList.add("April");
_monthList.add("May");
_monthList.add("June");
_monthList.add("July");
_monthList.add("August");
_monthList.add("September");
_monthList.add("October");
_monthList.add("November");
_monthList.add("December");
_spinner = (Spinner)findViewById(R.id.month_spinner);
_amountAdaptor = new ArrayAdapter(this,
android.R.layout.simple_spinner_dropdown_item,
_monthList);
_spinner.setAdapter(_amountAdaptor);
_spinner.setOnItemSelectedListener(this);
_monthButton = (Button)findViewById(R.id.monthSpinner_button);
_monthButton.setOnClickListener(this);
_backImageButton = (ImageButton)findViewById(R.id.back_ImageButton);
_backImageButton.setOnClickListener(this);
_headerImageButton =(ImageButton)findViewById(R.id.header_ImageButton);
_headerImageButton.setOnClickListener(this);
}
private void getJSON_Response(String response,int pid) {
switch (pid) {
case Constant.PID_ACCOUNT_HISTORY:
try {
JSONObject jsonObj = new JSONObject(response);
String message = jsonObj.getString("Message");
if(message!=null && message.equalsIgnoreCase("Success")){
JSONArray dataArray = jsonObj.getJSONArray("Data");
System.out.println(dataArray.length());
String lastAddedDate = null;
for (int i = 0; i <dataArray.length(); i++) {
JSONObject history = dataArray.getJSONObject(i);
String date = history.getString("DATE");
if(firstTime || !(date.equalsIgnoreCase(lastAddedDate))){
firstTime=false;
lastAddedDate = date;
items.add(new SectionItem(date));
}
String username= history.getString("USER_NAME");
String number = history.getString("PhoneNumber");
String time = history.getString("TIME");
String amount=history.getString("AMOUNT");
String duration =history.getString("QUANTITY");
items.add(new EntryItem(username,duration,amount,number,time));
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
default:
break;
}
}
#Override
public void onClick(View v) {
if(v==_monthButton){
_spinner.performClick();
}else if(v==_backImageButton){
SectionListExampleActivity.this.finish();
}else if(v== _headerImageButton){
if (p != null)
showPopup(SectionListExampleActivity.this, p);
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position,
long arg3) {
if(position!=0){
switch (parent.getId()) {
case R.id.month_spinner:
String selectedItem = _spinner.getSelectedItem().toString();
_monthButton.setBackgroundResource(R.drawable.month_blank);
_monthButton.setText(selectedItem);
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
String _historyURL = Constant.prodORdevUrl + "GetAccountHistory?token="+_token+"&account="+_account+"&month="+month+"&year="+year;
getHistory(_historyURL,true);
break;
default:
break;
}
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
public class EntryAdapter extends ArrayAdapter<Item> implements IServerResponse {
private Context context;
private ArrayList<Item> items;
private LayoutInflater vi;
private String _token;
private String _account;
public EntryAdapter(Context context,ArrayList<Item> items) {
super(context,0, items);
this.context = context;
this.items = items;
vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
_token = Constant.AUTH_TOKEN;
_account = Constant.ACCOUNT_NUM;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
final Item i = items.get(position);
if (i != null) {
if(i.isSection()){
SectionItem si = (SectionItem)i;
v = vi.inflate(R.layout.list_item_section, null);
v.setOnClickListener(null);
v.setOnLongClickListener(null);
v.setLongClickable(false);
final TextView sectionView = (TextView) v.findViewById(R.id.list_item_section_text);
String date =createDateFormat(si.getTitle());
sectionView.setText(date);
}else{
EntryItem ei = (EntryItem)i;
v = vi.inflate(R.layout.list_item_entry, null);
final RelativeLayout relay = (RelativeLayout)v.findViewById(R.id.account_history_item_relay);
final TextView username = (TextView)v.findViewById(R.id.user_name_textview);
final TextView amount = (TextView)v.findViewById(R.id.amount_textview);
final TextView duration = (TextView)v.findViewById(R.id.duration_textview);
final TextView phone = (TextView)v.findViewById(R.id.phone_no_textview);
final TextView time = (TextView)v.findViewById(R.id.time_textview);
relay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
makeCall(phone.getText().toString());
}
});
if (username != null)
username.setText(ei.username);
if(amount != null)
amount.setText(ei.duration + "min");
if(duration != null)
duration.setText("$"+ ei.amount);
if(phone != null)
phone.setText(ei.number);
if(time != null)
time.setText(ei.time);
}
}
return v;
}
void makeCall(String destination) {
if(_token!=null && _account!=null){
if(destination!=null && !destination.equals("")){
String phoneNumber = Constant.getPhoneNumber(this.context.getApplicationContext());
if(phoneNumber!=null && phoneNumber.length()>0){
String callURL =WebService.WEB_SERVICE_URL+"PlaceLongDistanceCall?token="+_token +
"&phonenumber="+phoneNumber+"&destinationNumber="+destination+"&authtoken="+_token;
getCall(callURL,true);
}else{
Constant.showToast(this.context, Constant.INSERT_SIM);
}
}else{
Constant.showToast(this.context, "In valid destination number.");
}
}
}
}

Android: Data in grid view appearing with delay

In my app, I have requirement of showing calendar. Since, calendar view is available from API level 11, so, I used grid view instead. Basically, I follwed this tutorial. Calendar is working, but data in Calendar in appearing with delay, means, when I click on button to display the calendar, it comes up after delay of around 5-10 seconds. I even tested with disabling the log, which I have put in the program, but it didn't made any difference. I am posting my code below.
Calendar Adapter
public class CalendarAdapter extends BaseAdapter //implements OnClickListener
{
static final int FIRST_DAY_OF_WEEK = 0; // Sunday = 0, Monday = 1
private Context mContext;
private Calendar month;
private Calendar selectedDate;
public String[] days;
TextView txtCurMonth;
public static final String TAG = "CalendarAdapter";
int curYear, curMonth;
public ArrayList<EventDetailDAO> mEventDAOList;
String date, dateToHighlight;
public static boolean calendarItemClicked = false;
ViewHolder holder;
public CalendarAdapter(Context c, Calendar monthCalendar, TextView txtCurMonth)
{
month = monthCalendar;
selectedDate = (Calendar)monthCalendar.clone();
mContext = c;
month.set(Calendar.DAY_OF_MONTH, 1);
new ArrayList<String>();
this.txtCurMonth = txtCurMonth;
mEventDAOList = new ArrayList<EventDetailDAO>();
curYear = selectedDate.get(Calendar.YEAR);
curMonth = selectedDate.get(Calendar.MONTH) + 1;
refreshDays();
}//Constructor
public void setItems(ArrayList<String> items)
{
for(int i = 0; i != items.size(); i++)
{
if(items.get(i).length() == 1)
{
items.set(i, "0" + items.get(i));
}//if
}//for
}//setItems
public int getCount()
{
return days.length;
}//getCount
public Object getItem(int position)
{
return null;
}//getItem
public long getItemId(int position)
{
return 0;
}//getItemId
// create a new view for each item referenced by the Adapter
public View getView(final int position, View convertView, ViewGroup parent)
{
if (convertView == null)
{
holder = new ViewHolder();
convertView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.calendar_grid_adapter, null);
holder.linCalAdapParent = (LinearLayout)convertView
.findViewById(R.id.linCalAdapParent);
holder.dayView = (TextView)convertView.findViewById(R.id.date);
convertView.setTag(holder);
}//if
else
{
holder = (ViewHolder)convertView.getTag();
}//else
Typeface date_TF = Typeface.createFromAsset(mContext.getAssets(), "fonts/arial.ttf");
txtCurMonth.setTypeface(date_TF);
txtCurMonth.setText(DateFormat.format("MMMM yyyy", month.getTime()));
holder.dayView.setTypeface(date_TF);
holder.dayView.setText(days[position]);
if(days[position].equals(""))
{
holder.linCalAdapParent.setBackgroundResource(R.drawable.calendar_tile);
}//if
else
{
String monthToCheck = null;
if(curMonth < 10)
{
monthToCheck = "0"+curMonth;
}//if
else
{
monthToCheck = Integer.toString(curMonth);
}//else
dateToHighlight = curYear+"-"+monthToCheck;
Log.v(TAG, "date to highlight: "+dateToHighlight);
if(isEnabled(position))
{
holder.linCalAdapParent.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Log.v(TAG, "CalendarAdapter mEventDAOList size: "+mEventDAOList.size());
String daysToMatch = days[position];
if(daysToMatch.length() == 1)
{
daysToMatch = "0"+daysToMatch;
}//if
Log.v(TAG, "CalendarAdapter day selected: "+daysToMatch);
ArrayList<EventDetailDAO> mSelectedEventDAOList
= new ArrayList<EventDetailDAO>();
for(int i = 0; i < mEventDAOList.size(); i++)
{
if(mEventDAOList.get(i).getEvent_Date().contains(daysToMatch))
{
mSelectedEventDAOList.add(mEventDAOList.get(i));
selectedDate.set(Calendar.YEAR, curYear);
selectedDate.set(Calendar.MONTH, curMonth - 1);
selectedDate.set(Calendar.DAY_OF_MONTH, Integer.parseInt(daysToMatch));
}//if
}//for
((EventsActivity)mContext).getDataFromCalendar(mSelectedEventDAOList, selectedDate);
((EventsActivity)mContext).calInstanceFromAdapter = selectedDate;
calendarItemClicked = true;
}//onClick
});
}//if
}//else
Log.v(TAG, "Calendar adapter getView called");
return convertView;
}//getView
public void refreshDays()
{
// clear items
//items.clear();
int lastDay = month.getActualMaximum(Calendar.DAY_OF_MONTH);
int firstDay = (int)month.get(Calendar.DAY_OF_WEEK);
Log.v(TAG, "in refreshDays, lastDay: "+lastDay);
Log.v(TAG, "in refreshDays, firstDay: "+firstDay);
// figure size of the array
if(firstDay == 1)
{
Log.v(TAG, "if first day 1");
days = new String[lastDay + (FIRST_DAY_OF_WEEK * 6)];
}//if
else
{
Log.v(TAG, "else first day not 1");
days = new String[lastDay + firstDay - (FIRST_DAY_OF_WEEK + 1)];
}//else
int j=FIRST_DAY_OF_WEEK;
// populate empty days before first real day
if(firstDay > 1)
{
Log.v(TAG, "if first day > 1");
for(j = 0; j < firstDay - FIRST_DAY_OF_WEEK; j++)
{
Log.v(TAG, "in for if first day > 1");
days[j] = "";
}//for
}//if
else
{
Log.v(TAG, "else first day < 1");
for(j = 0; j < FIRST_DAY_OF_WEEK * 6; j++)
{
Log.v(TAG, "in for else first day < 1");
days[j] = "";
}//for
j = FIRST_DAY_OF_WEEK * 6 + 1; // sunday => 1, monday => 7
}//else
// populate days
int dayNumber = 1;
for(int i = j - 1; i < days.length; i++)
{
Log.v(TAG, "in for day number");
days[i] = "" + dayNumber;
dayNumber++;
}//for
}//refreshDays
#Override
public boolean isEnabled(int position)
{
date = days[position];
if(date.length() == 1)
{
date = "0"+date;
}//if
dateToHighlight = dateToHighlight+"-"+date;
for(EventDetailDAO mEventDetailDAO: GetEventDetailAsyncTask.mainEventDetailArrayList)
{
Log.v(TAG, "CalendarAdapter isEnabled dateToHighlight: "+dateToHighlight);
if(mEventDetailDAO.getEvent_Date().equals(dateToHighlight))
{
mEventDAOList.add(mEventDetailDAO);
holder.linCalAdapParent.setBackgroundResource(R.drawable.calendar_tile_sel);
return true;
}//if
}//for
return false;
}//isEnabled
class ViewHolder
{
LinearLayout linCalAdapParent;
TextView dayView;
}//ViewHolder
}//CalendarAdapter
In my calendar, I have to highlight the dates which have some event. And, on click of highlighted date, it will show the list of events on that date. Every thing is working. except the calendar appears with delay even if I change month. I am not getting the cause.
One of the possible causes of the delay may be the call to Typeface.createFromAsset() which is called for every cell. The createFromAsset() method consumes a lot of resources.
To mitigate this, you could create a singleton class that retains the typeface used, so the font is not generated from the font file every time. Or you initialize it in onCreate() and pass it as an argument to the CalendarAdapter constructor and then use that instance in getView().
(To test this assumption comment the lines that sets the font to txtCurMonth TextView, and see if any difference)

Categories

Resources