Android: Data in grid view appearing with delay - android

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)

Related

My custom ArrayAdapter only repeats a few items

I'm using it for grid view, the count of object displayed is correct and it's returning in log is correct but for example 6 object display and the rest repeat them
1,2,3,4,5,6, 1,2,3,4,5,6,.....
my code
public class CustomAdapter extends ArrayAdapter<ItemObject> {
private static float textViewWidth;
public CustomAdapter(ArrayList<ItemObject> array, float textViewWidth) {
super(G.context, R.layout.sample_album_item, array);
CustomAdapter.textViewWidth = textViewWidth;
}
private static class ViewHolder {
ImageView imgScreenShot;
TextView txtAlbumName;
TextView txtAlbumAuthor;
public ViewHolder(View view) {
imgScreenShot = (ImageView) view.findViewById(R.id.screen_shot);
txtAlbumName = (TextView) view.findViewById(R.id.album_name);
txtAlbumAuthor = (TextView) view.findViewById(R.id.album_author);
}
public void fill(final ArrayAdapter<ItemObject> adapter, final ItemObject item, final int position) {
imgScreenShot.setImageResource(item.getScreenShot());
String albumName = item.getAlbumName();
String albumAuthor = item.getAlbumAuthor();
float musicNameWidthSizeViaParent = widthSizeViaParent(txtAlbumName, albumName);
float musicAuthorWidthSizeViaParent = widthSizeViaParent(txtAlbumAuthor, albumAuthor);
if (musicNameWidthSizeViaParent < 0) {
for (int i = 1; i < albumName.length() - 1; i++) {
if (widthSizeViaParent(txtAlbumName, albumName.substring(0, i).trim() + "...") < 0) {
albumName = albumName.substring(0, i - 1).trim() + "...";
break;
}
}
}
if (musicAuthorWidthSizeViaParent < 0) {
for (int i = 1; i < albumAuthor.length() - 1; i++) {
if (widthSizeViaParent(txtAlbumName, albumAuthor.substring(0, i).trim() + "...") < 0) {
albumAuthor = albumAuthor.substring(0, i - 1).trim() + "...";
break;
}
}
}
txtAlbumName.setText(albumName);
txtAlbumAuthor.setText(albumAuthor);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
ItemObject item = getItem(position);
if (convertView == null) {
convertView = G.inflater.inflate(R.layout.sample_album_item, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.fill(this, item, position);
return convertView;
}
private static float widthSizeViaParent(TextView text, String newText) {
float textWidth = text.getPaint().measureText(newText);
return textViewWidth - (textWidth * G.displayMetrics.density);
}
}
if getView method without this (convertView == null) condition, everything is correct but scrolling is slowly
My guess is that this block of code makes it run slow:
public void fill(final ArrayAdapter<ItemObject> adapter, final ItemObject item, final int position) {
imgScreenShot.setImageResource(item.getScreenShot());
String albumName = item.getAlbumName();
String albumAuthor = item.getAlbumAuthor();
float musicNameWidthSizeViaParent = widthSizeViaParent(txtAlbumName, albumName);
float musicAuthorWidthSizeViaParent = widthSizeViaParent(txtAlbumAuthor, albumAuthor);
if (musicNameWidthSizeViaParent < 0) {
for (int i = 1; i < albumName.length() - 1; i++) {
if (widthSizeViaParent(txtAlbumName, albumName.substring(0, i).trim() + "...") < 0) {
albumName = albumName.substring(0, i - 1).trim() + "...";
break;
}
}
}
if (musicAuthorWidthSizeViaParent < 0) {
for (int i = 1; i < albumAuthor.length() - 1; i++) {
if (widthSizeViaParent(txtAlbumName, albumAuthor.substring(0, i).trim() + "...") < 0) {
albumAuthor = albumAuthor.substring(0, i - 1).trim() + "...";
break;
}
}
}
txtAlbumName.setText(albumName);
txtAlbumAuthor.setText(albumAuthor);
}
Two loops runs for every single item. You probably want to have that logic in the models instead. So when rendering the items, albumName and albumAuthor is already set.

listview not updated baseadapter

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;

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.");
}
}
}
}

How to get previous month's days on the gridview (Calendar)

I need help on how to go about and make prev month's days visible (grayed out) on this calendar.
I am getting a present months view here.. but as you can see the previous months days are not visible.I know why.. but how to go about it? also few bugs are there in this present one as well.please help.Posting the code for the custom adapter class:
CalendarAdapter.java
import java.util.ArrayList;
import java.util.Calendar;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CalendarAdapter extends BaseAdapter {
static final int FIRST_DAY_OF_WEEK =0; // Sunday = 0, Monday = 1
private Context mContext;
private java.util.Calendar month;
private Calendar selectedDate;
private ArrayList<String> items;
public CalendarAdapter(Context c, Calendar monthCalendar) {
month = monthCalendar;
selectedDate = (Calendar)monthCalendar.clone();
mContext = c;
month.set(Calendar.DAY_OF_MONTH, 1);
this.items = new ArrayList<String>();
refreshDays();
}
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));
}
}
this.items = items;
}
public int getCount() {
return days.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new view for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
TextView dayView;
if (convertView == null) { // if it's not recycled, initialize some attributes
LayoutInflater vi = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.calendar_item, null);
}
dayView = (TextView)v.findViewById(R.id.date);
// disable empty days from the beginning
if(days[position].equals("")) {
dayView.setClickable(false);
dayView.setFocusable(false);
//need to show previous months date
}
else {
// mark current day as focused
if(month.get(Calendar.YEAR)== selectedDate.get(Calendar.YEAR) && month.get(Calendar.MONTH)== selectedDate.get(Calendar.MONTH) && days[position].equals(""+selectedDate.get(Calendar.DAY_OF_MONTH))) {
v.setBackgroundResource(R.drawable.date_area);
dayView.setTextColor(Color.parseColor("#FFFFFF"));
}
else {
v.setBackgroundResource(R.drawable.current_date_area);
}
}
dayView.setText(days[position]);
// create date string for comparison
String date = days[position];
if(date.length()==1) {
date = "0"+date;
}
String monthStr = ""+(month.get(Calendar.MONTH)+1);
if(monthStr.length()==1) {
monthStr = "0"+monthStr;
}
// show icon if date is not empty and it exists in the items array
/* ImageView iw = (ImageView)v.findViewById(R.id.date_icon);
if(date.length()>0 && items!=null && items.contains(date)) {
iw.setVisibility(View.VISIBLE);
}
else {
iw.setVisibility(View.INVISIBLE);
}*/
return v;
}
public void refreshDays()
{
// clear items
items.clear();
int lastDay = month.getActualMaximum(Calendar.DAY_OF_MONTH);
int firstDay = (int)month.get(Calendar.DAY_OF_WEEK);
// figure size of the array
if(firstDay==1){
days = new String[lastDay+(FIRST_DAY_OF_WEEK*6)];
}
else {
days = new String[lastDay+firstDay-(FIRST_DAY_OF_WEEK+1)];
}
int j=FIRST_DAY_OF_WEEK;
// populate empty days before first real day
if(firstDay>1) {
for(j=0;j<firstDay-FIRST_DAY_OF_WEEK;j++) {
days[j] = "";
}
}
else {
for(j=0;j<FIRST_DAY_OF_WEEK*6;j++) {
days[j] = "";
}
j=FIRST_DAY_OF_WEEK*6+1; // sunday => 1, monday => 7
}
// populate days
int dayNumber = 1;
for(int i=j-1;i<days.length;i++) {
days[i] = ""+dayNumber;
dayNumber++;
}
}
// references to our items
public String[] days;}
and this is the Activity code on how i am using this adapter:
CalendarView.java
/*some code above*/
/*this is in the OnCreate block*/
adapter = new CalendarAdapter(this, month);
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(adapter);
/*some code below*/
and heres my calendar view screen (grid):
CalendarView Screenshot:
To be straight and to the point,All i want is that blank boxes before 1st of the month be filled in with the previous month's last week's days
Declare another calendar
private java.util.Calendar month, prevMonth;
Add a clone to calendar in the constructor
prevMonth = (Calendar) month.clone();
prevMonth.roll(Calendar.MONTH, false);
Then replace the refreshDays with this one.This fills up the blank spaces with the days from the last month and the next month for the first and last week of the current month respectively.
public void refreshDays() {
// clear items
items.clear();
int lastDay = month.getActualMaximum(Calendar.DAY_OF_MONTH);
int firstDay = (int) month.get(Calendar.DAY_OF_WEEK);
int maxweek = month.getActualMaximum(Calendar.WEEK_OF_MONTH);
Log.d("CalendarAdapter", String.valueOf(maxweek));
// figure size of the array
/*
* if (firstDay == 1) { days = new String[lastDay + (FIRST_DAY_OF_WEEK *
* 6)]; }
*
* else { days = new String[lastDay + firstDay - (FIRST_DAY_OF_WEEK +
* 1)]; }
*/
days = new String[maxweek * 7];
int j = FIRST_DAY_OF_WEEK;
// populate empty days before first real day
if (firstDay > 1) {
// can be made a bit faster if implemented without this following
// for loop for roll
for (j = 0; j < firstDay - FIRST_DAY_OF_WEEK; j++) {
prevMonth.roll(Calendar.DAY_OF_MONTH, false);
Log.d("CalendarAdapter",
"roll block: " + prevMonth.get(Calendar.DAY_OF_MONTH));
}
for (j = 0; j < firstDay - FIRST_DAY_OF_WEEK; j++) {
// days[j] = "";
prevMonth.roll(Calendar.DAY_OF_MONTH, true);
int dayPrev = prevMonth.get(Calendar.DAY_OF_MONTH);
days[j] = " " + String.valueOf(dayPrev) + " ";
Log.d("CalendarAdapter", "calculation:J if firstDay>1 -- " + j
+ " roll gives:" + dayPrev);
}
} else {
for (j = 0; j < FIRST_DAY_OF_WEEK * 6; j++) {
days[j] = "";
Log.d("CalendarAdapter", "calculation:J if firstDay<1 -- " + j);
}
j = FIRST_DAY_OF_WEEK * 6 + 1; // sunday => 1, monday => 7
}
// populate days
int dayNumber = 1;
boolean flag = false;
for (int i = j - 1; i < days.length; i++) {
days[i] = String.valueOf(dayNumber).trim() + ".";
if (flag)
days[i] = String.valueOf(dayNumber).trim();
if (dayNumber == lastDay) {
dayNumber = 0;
flag=true;
}
dayNumber++;
}
}
// references to our items
public String[] days;
}

Application randomly stops responding.

I am new to programming and I'm making a very simple blackjack game with only basic functions. When I run the program on the emulator it runs maybe for one hand, two, sometimes 5 or more but it always stops responding at some stage when i click on one of the three butons. There is a splash screen that runs for three seconds and the there is a thread comming from that activity that starts this menu activity. Could anyone maybe tell why this is happening? It usually happens when I clcik on one of the buttons even though there is no much comput
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btDeal = (Button) findViewById(R.id.deal);
playerCards1 = (TextView) findViewById(R.id.playerCards);
playerPoints = (TextView) findViewById(R.id.playerPoints);
dealerCards1 = (TextView) findViewById(R.id.dealerCard);
mpBusted= MediaPlayer.create(this, R.raw.busted);
mpWin = MediaPlayer.create(this, R.raw.win);
mpShuffling = MediaPlayer.create(this, R.raw.shuffling);
mpEven = MediaPlayer.create(this, R.raw.even);
mpHit= MediaPlayer.create(this, R.raw.hit);
btDeal.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
deal ();
}
}); //getTotalDealerCards()
//getTotalPlayerCards()
btHit = (Button) findViewById(R.id.hit);
btHit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Boolean busted = isBusted();
if(!busted){
hitPlayer();
playerCards1.setText(getPlayerCardsToString());
if (isBusted()){
mpBusted.start();
}else{
playerCards1.setText(getPlayerCardsToString());
playerPoints.setText(Integer.toString(getTotalPlayerPoints()));
}
}
}
});
btStand = (Button) findViewById(R.id.stand);
btStand.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
checkWinner();
}// testValue(getTotalPlayerCards())
});
}
/*********** Function declarations starts here **********/
//Sum and return the total points for the dealer cards
public int getTotalDealerPoints(){
int points = 0;
int aceFlag = 0; //flag to deal with Aces
int counter;
for (counter = 0; counter <= getTotalDealerCards(); counter++){
if (dealerCards [counter].getCard() + 1 == 1){
points += 11;
aceFlag++;
}
else if (dealerCards [counter].getCard() + 1 > 10)
points += 10;
else
points += dealerCards [counter].getCard() + 1;
}
do {
if (points > 21 && aceFlag > 0){
points -= 10;
aceFlag--;
}
} while (aceFlag>0);
return points;
}
//Get the total player points deal
public int getTotalPlayerPoints(){
int points = 0;
int aceFlag = 0; //flag to deal with Aces
int counter;
for (counter = 0; counter <= getTotalPlayerCards(); counter++){
if (playerCards [counter].getCard() + 1 == 1){
points += 11;
aceFlag++;
}
else if (playerCards [counter].getCard() + 1 > 10)
points += 10;
else
points += playerCards [counter].getCard() + 1;
}
do {
if (points > 21 && aceFlag > 0){
points -= 10;
aceFlag--;
}
} while (aceFlag>0);
return points;
}
//Deal function to start hand
public void deal (){
// If deal is pressed reset all and start over.
mpShuffling.start();
totalDealerPoints = 0;
totalPlayerPoints = 0;
totalCreatedCards = 0;
for (int i = 0; i < TOTAL_CARDS; i++){
dealerCards [i] = null;
playerCards [i] = null;
createdCards [i] = null;
}
// create dealer & player cards and save them to dealer, player and total arrays.
for (int dealcounter = 0; dealcounter <=1 ; dealcounter++){
dealerCards[dealcounter]= createCard();
addCardToCreatedCards(dealerCards[dealcounter]);
playerCards[dealcounter] = createCard();
addCardToCreatedCards(playerCards[dealcounter]);
}
String theCards = getPlayerCardsToString();
String dealerCard = dealerCards[0].toString();
String playerpoints= Integer.toString(getTotalPlayerPoints());
playerCards1.setText(theCards);
dealerCards1.setText(dealerCard);
playerPoints.setText(playerpoints);//getTotalPlayerPoints()
while (getTotalDealerPoints() < 16){
hitDealer();
}
}
// Create card and validate against existing before returning object.
public Card createCard(){
int counter2 = 0;
int flag = 0;
int value;
int suit;
do {
flag = 0;
suit = randomer.nextInt(4);
value = randomer.nextInt(13);
// validate against permitted values before creating cards
while (counter2 <= getTotalPlayerCards()) {
if (createdCards[counter2].getSuit() == suit && createdCards[counter2].getCard() == value || suit > 3 || suit < 0 || value > 12 || value < 0){
flag = -1;
}
counter2++;
}
} while (flag != 0);
Card theCard = new Card (suit, value);
return theCard;
}
// Add card to the records of created cards
public void addCardToCreatedCards(Card aCard){
createdCards [totalCreatedCards] = aCard;
totalCreatedCards++;
}
// Add a card to dealers cards
public void hitPlayer(){
//If the hand was started add card, else deal to start hand.
if (getTotalPlayerCards()+1 != 0){
mpHit.start();
playerCards [getTotalPlayerCards()+1] = createCard();
addCardToCreatedCards(playerCards [getTotalPlayerCards()]);
}
else
deal();
}
// Create a new card for the dealer
public void hitDealer(){
dealerCards [getTotalDealerCards()+1] = createCard();
addCardToCreatedCards(dealerCards [getTotalDealerCards()]);
}
public String getPlayerCardsToString(){
String cards = "";
int total = getTotalPlayerCards();
if (getTotalPlayerPoints() <=21){
int counter = 0;
while (counter <= total){
cards += playerCards[counter].toString() + " ";
counter++;
}
return cards;
}else {
int counter=0;
while (counter <= total){
cards += playerCards[counter].toString() + " ";
counter++;
}
return cards;
}
}
public int getTotalPlayerCards(){
int initialCount = 0;
while (playerCards[initialCount] != null){
initialCount++;
}
return initialCount-1;
}
public int getTotalDealerCards(){
int initialCount = 0;
while (dealerCards[initialCount] != null){
initialCount++;
}
return initialCount-1;
}
public int getTotalCreatedCards(){
int initialCount = 0;
while (createdCards[initialCount] != null){
initialCount++;
}
return initialCount-1;
}
public Boolean isBusted(){
Boolean busted = false;
if (getTotalPlayerPoints()>21){
busted=true;
totalDealerPoints = 0;
totalPlayerPoints = 0;
mpBusted.start();
playerPoints.setText("You were busted!!");
for (int i = 0; i < TOTAL_CARDS; i++){
dealerCards [i] = null;
playerCards [i] = null;
createdCards [i] = null;
}
}
return busted;
}
//Check for winner
public void checkWinner(){
if (getTotalDealerPoints() <= 21 || getTotalPlayerPoints() <= 21 && !isBusted()){
if (getTotalDealerPoints() > 21 || getTotalDealerPoints() < getTotalPlayerPoints()){
playerPoints.setText("You won!!");
mpWin.start();
}
else if(getTotalDealerPoints() > getTotalPlayerPoints()){
mpBusted.start();
playerPoints.setText("You were busted!!");
for (int i = 0; i < TOTAL_CARDS; i++){
dealerCards [i] = null;
playerCards [i] = null;
createdCards [i] = null;
}
}
else{
mpEven.start();
playerCards1.setText("We have same points!");
}
}
else {
deal ();
}
}
}
Use the debugger in eclipse to find out where it gets frozen.
Also the android emulator is very slow even with a fast PC.
Try using the low resolution simulators.
open DDMS from the android-sdk\tools and check which method or thread is taking more time to execute.
Use AsyncTask or Handler when there is a functional(Computational) things running.

Categories

Resources