This is my code my problem is this . in calendar view pager adapter i am 5000 page but offScreenPage limit is 1 and I have 3 pages in on time but view pager is not smoth scroll and has bad performance. when I remove this line from Calendar fragment view pager smooth scroll fine. but I dont know what is the problem.
gregorianCal = new GregorianCalendar(persianCal);
IslamicCalendar islamicCal = new IslamicCalendar(persianCal);
///////////////////////////////////////////////
for (int i = 0; i < persianCal.getNumberOfDaysInMonth(); i++) {
DateCalendar dateCalendar = new DateCalendar();
dateCalendar.nameOFDay = persianCal.getWeekDay();
//////set month names/////////////
dateCalendar.shamsiMonthName = persianCal.getMonthName();
dateCalendar.hejriMonthName = islamicCal.getMonthName();
dateCalendar.gregorianMonthName = gregorianCal.getMonthName();
//////set persian calendar/////
dateCalendar.shamsiDayNumber = persianCal.getDay();
dateCalendar.shamsiMonthNumber = persianCal.getMonth();
dateCalendar.shamsiYearNumber = persianCal.getYear();
//////set islamic calendar/////
dateCalendar.hejriDayNumber = islamicCal.getDay();
dateCalendar.hejriMonthNumber = islamicCal.getMonth();
dateCalendar.hejriYearNumber = islamicCal.getYear();
//////set gregorian calendar/////
dateCalendar.gregorianDayNumber = gregorianCal.getDay();
dateCalendar.gregorianMonthNumber = gregorianCal.getMonth();
dateCalendar.gregorianYearNumber = gregorianCal.getYear();
///////select current day of Month
if (persianCal.getDay() == currentPersianCal.getDay() && persianCal.getMonth() == currentPersianCal.getMonth() && persianCal.getYear() == currentPersianCal.getYear()) {
dateCalendar.isCurrentDay = true;
dateCalendar.isDaySelected = true;
}
///////add days of current month//////
dateCalendarList.add(dateCalendar);
if (i < persianCal.getNumberOfDaysInMonth() - 1) {
persianCal.nextDay();
gregorianCal.nextDay();
islamicCal.nextDay();
}
}
I search a lot of similar subject of viewPager but I not found soultion for it.
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.TextView;
import com.example.moein.mycalendar.R;
import com.example.moein.mycalendar.myCalendar_adapter.GridAdapter1;
import com.example.moein.mycalendar.myCalendar_library.date.GregorianCalendar;
import com.example.moein.mycalendar.myCalendar_library.date.IslamicCalendar;
import com.example.moein.mycalendar.myCalendar_library.date.PersianCalendar;
import com.example.moein.mycalendar.myCalendar_library.util.Operations;
import com.example.moein.mycalendar.myCalendar_model.DateCalendar;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
/**
* Created by Moein on 9/16/2017.
*/
public class CalendarFragment extends Fragment {
private int year;
private int month;
private int day;
// newInstance constructor for creating fragment with arguments
public static CalendarFragment newInstance(int year, int month, int day) {
CalendarFragment calendarFragment = new CalendarFragment();
Bundle args = new Bundle();
args.putInt("year", year);
args.putInt("month", month);
args.putInt("day", day);
calendarFragment.setArguments(args);
return calendarFragment;
}
// Store instance variables based on arguments passed
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
year = getArguments().getInt("year");
month = getArguments().getInt("month");
day = getArguments().getInt("day");
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_calendar, container, false);
TextView yearAndMonth = view.findViewById(R.id.yearAndMonth);
GridView gridView = view.findViewById(R.id.gridCalendar);
/////set timeZone Asia/Tehran and set current calendar///////////////////////////////
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
calendar.setTimeZone(TimeZone.getTimeZone("Asia/Tehran"));
GregorianCalendar currentGregorianCal = new GregorianCalendar(calendar);
PersianCalendar currentPersianCal = new PersianCalendar(currentGregorianCal);
GregorianCalendar gregorianCal = new GregorianCalendar(year, month, day);
PersianCalendar persianCal = new PersianCalendar(gregorianCal);
/////////add weekDay names to the list of gridAdapter///////
String[] weekDays = getResources().getStringArray(R.array.weekDays);
List<DateCalendar> dateCalendarList = new ArrayList<>();
for (String weekDay : weekDays) {
DateCalendar dateCalendar = new DateCalendar();
dateCalendar.nameOFDay = weekDay;
dateCalendarList.add(dateCalendar);
}
//set title of calendar/////////
yearAndMonth.setText(persianCal.getMonthName() + " " + Operations.toPersianNumber(String.valueOf(persianCal.getYear())));
///Back to the beginning of the month
persianCal.subtractDays(persianCal.getDay() - 1);
//////add empty days to the beginning of the month
int lengthOfEmptyDays = 0;
switch (persianCal.getWeekDay()) {
case "شنبه":
lengthOfEmptyDays = 0;
break;
case "یکشنبه":
lengthOfEmptyDays = 1;
break;
case "دوشنبه":
lengthOfEmptyDays = 2;
break;
case "سه\u200Cشنبه":
lengthOfEmptyDays = 3;
break;
case "چهارشنبه":
lengthOfEmptyDays = 4;
break;
case "پنج\u200Cشنبه":
lengthOfEmptyDays = 5;
break;
case "جمعه":
lengthOfEmptyDays = 6;
break;
}
for (int i = 0; i < lengthOfEmptyDays; i++) {
DateCalendar dateCalendar = new DateCalendar();
dateCalendar.isEmpty = true;
dateCalendarList.add(dateCalendar);
}
gregorianCal = new GregorianCalendar(persianCal);
IslamicCalendar islamicCal = new IslamicCalendar(persianCal);
///////////////////////////////////////////////
for (int i = 0; i < persianCal.getNumberOfDaysInMonth(); i++) {
DateCalendar dateCalendar = new DateCalendar();
dateCalendar.nameOFDay = persianCal.getWeekDay();
//////set month names/////////////
dateCalendar.shamsiMonthName = persianCal.getMonthName();
dateCalendar.hejriMonthName = islamicCal.getMonthName();
dateCalendar.gregorianMonthName = gregorianCal.getMonthName();
//////set persian calendar/////
dateCalendar.shamsiDayNumber = persianCal.getDay();
dateCalendar.shamsiMonthNumber = persianCal.getMonth();
dateCalendar.shamsiYearNumber = persianCal.getYear();
//////set islamic calendar/////
dateCalendar.hejriDayNumber = islamicCal.getDay();
dateCalendar.hejriMonthNumber = islamicCal.getMonth();
dateCalendar.hejriYearNumber = islamicCal.getYear();
//////set gregorian calendar/////
dateCalendar.gregorianDayNumber = gregorianCal.getDay();
dateCalendar.gregorianMonthNumber = gregorianCal.getMonth();
dateCalendar.gregorianYearNumber = gregorianCal.getYear();
///////select current day of Month
if (persianCal.getDay() == currentPersianCal.getDay() && persianCal.getMonth() == currentPersianCal.getMonth() && persianCal.getYear() == currentPersianCal.getYear()) {
dateCalendar.isCurrentDay = true;
dateCalendar.isDaySelected = true;
}
///////add days of current month//////
dateCalendarList.add(dateCalendar);
if (i < persianCal.getNumberOfDaysInMonth() - 1) {
persianCal.nextDay();
gregorianCal.nextDay();
islamicCal.nextDay();
}
}
gridView.setAdapter(new GridAdapter1(getActivity(), dateCalendarList));
return view;
}
}
public class CalendarViewPagerAdapter extends FragmentStatePagerAdapter{
private GregorianCalendar centerGregorianCalendar;
private GregorianCalendar nextGregorianCalendar;
private GregorianCalendar prevGregorianCalendar;
private final int MAX = 5000;
public CalendarViewPagerAdapter(FragmentManager fm, GregorianCalendar centerGregorianCalendar, GregorianCalendar nextGregorianCalendar, GregorianCalendar prevGregorianCalendar) {
super(fm);
this.centerGregorianCalendar = centerGregorianCalendar;
this.prevGregorianCalendar = prevGregorianCalendar;
this.nextGregorianCalendar = nextGregorianCalendar;
}
#Override
public Fragment getItem(int position) {
position = position % 3;
if (position == 0) {
return new CalendarFragment().newInstance(prevGregorianCalendar.getYear(), prevGregorianCalendar.getMonth(), prevGregorianCalendar.getDay());
} else if (position == 1) {
return new CalendarFragment().newInstance(centerGregorianCalendar.getYear(), centerGregorianCalendar.getMonth(), centerGregorianCalendar.getDay());
} else {
return new CalendarFragment().newInstance(nextGregorianCalendar.getYear(), nextGregorianCalendar.getMonth(), nextGregorianCalendar.getDay());
}
}
#Override
public int getCount() {
return MAX;
}
}
public class MainActivity extends AppCompatActivity {
private int[] CenterPage = {2500};
private CalendarViewPagerAdapter calendarViewPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/////set timeZone Asia/Tehran///////////////////////////////
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
calendar.setTimeZone(TimeZone.getTimeZone("Asia/Tehran"));
final GregorianCalendar gregorianCal = new GregorianCalendar(calendar);
final GregorianCalendar nextGregorianCal = new GregorianCalendar(calendar);
final GregorianCalendar prevGregorianCal = new GregorianCalendar(calendar);
if (gregorianCal.getMonth() == 12) {
nextGregorianCal.setMonth(1);
nextGregorianCal.setYear(nextGregorianCal.getYear() + 1);
} else {
nextGregorianCal.setMonth(nextGregorianCal.getMonth() + 1);
}
if (gregorianCal.getMonth() == 1) {
prevGregorianCal.setMonth(12);
prevGregorianCal.setYear(prevGregorianCal.getYear() - 1);
} else {
prevGregorianCal.setMonth(prevGregorianCal.getMonth() - 1);
}
final ViewPager calendarViewPager = findViewById(R.id.calendar_viewPager);
calendarViewPagerAdapter = new CalendarViewPagerAdapter(getSupportFragmentManager(), gregorianCal, nextGregorianCal, prevGregorianCal);
calendarViewPager.setAdapter(calendarViewPagerAdapter);
calendarViewPager.setOffscreenPageLimit(1);
calendarViewPager.setCurrentItem(2500);
calendarViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (position < CenterPage[0]) {
switch (position % 3) {
case 0:
nextGregorianCal.set(prevGregorianCal);
if (nextGregorianCal.getMonth() == 1) {
nextGregorianCal.setMonth(12);
nextGregorianCal.setYear(nextGregorianCal.getYear() - 1);
} else {
nextGregorianCal.setMonth(nextGregorianCal.getMonth() - 1);
}
break;
case 1:
prevGregorianCal.set(gregorianCal);
if (prevGregorianCal.getMonth() == 1) {
prevGregorianCal.setMonth(12);
prevGregorianCal.setYear(prevGregorianCal.getYear() - 1);
} else {
prevGregorianCal.setMonth(prevGregorianCal.getMonth() - 1);
}
break;
case 2:
gregorianCal.set(nextGregorianCal);
if (gregorianCal.getMonth() == 1) {
gregorianCal.setMonth(12);
gregorianCal.setYear(gregorianCal.getYear() - 1);
} else {
gregorianCal.setMonth(gregorianCal.getMonth() - 1);
}
break;
}
} else if (position > CenterPage[0]) {
switch (position % 3) {
case 0:
gregorianCal.set(prevGregorianCal);
if (gregorianCal.getMonth() == 12) {
gregorianCal.setMonth(1);
gregorianCal.setYear(gregorianCal.getYear() + 1);
} else {
gregorianCal.setMonth(gregorianCal.getMonth() + 1);
}
break;
case 1:
nextGregorianCal.set(gregorianCal);
if (nextGregorianCal.getMonth() == 12) {
nextGregorianCal.setMonth(1);
nextGregorianCal.setYear(nextGregorianCal.getYear() + 1);
} else {
nextGregorianCal.setMonth(nextGregorianCal.getMonth() + 1);
}
break;
case 2:
prevGregorianCal.set(nextGregorianCal);
if (prevGregorianCal.getMonth() == 12) {
prevGregorianCal.setMonth(1);
prevGregorianCal.setYear(prevGregorianCal.getYear() + 1);
} else {
prevGregorianCal.setMonth(prevGregorianCal.getMonth() + 1);
}
break;
}
}
CenterPage[0] = position;
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
}
i hope you can use this code
my site https://mohammadhosseinaref.ir
public static string PersianDayOfWeek(DayOfWeek dayOfWeek)
{
switch (dayOfWeek)
{
case DayOfWeek.Sunday:
return "یکشنبه";
case DayOfWeek.Monday:
return "دوشنبه";
case DayOfWeek.Tuesday:
return "سه شنبه";
case DayOfWeek.Wednesday:
return "چهار شنبه";
case DayOfWeek.Thursday:
return "پنج شنبه";
case DayOfWeek.Friday:
return "جمعه";
case DayOfWeek.Saturday:
return "شنبه";
default:
return null;
}
}
public static Dictionary<int, string> ListOfPersianDayOfMonth(int month, int years)
{
Dictionary<int, string> dicDays = new Dictionary<int, string>();
PersianCalendar p = new PersianCalendar();
var dates = Enumerable.Range(1, p.GetDaysInMonth(years, month))
.Select(day => ParsePersianToGorgian(years + "/" + month + "/" + day))
.ToList();
foreach (var item in dates)
{
var day = GeorgianToPersian(item.Value, ShowMode.OnlyDate);
dicDays.Add(int.Parse(day.Split('/')[2]), DayPersian(item.Value.DayOfWeek) + " " + day);
}
return dicDays;
}
Hi I want to open a activity when a if statement comes true. like "if gameStatus are equal to 12, then open scoreActivity". The Code:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.GridLayout;
import java.util.Random;
import android.os.Build;
import android.os.Handler;
public class Game6x4Activity extends AppCompatActivity implements View.OnClickListener {
private int numberOfElements;
private int[] buttonGraphicLocations;
private MemoryButton selectedButton1;
private MemoryButton selectedButton2;
private boolean isBusy = false;
public int gameStatus;
public int gameScore;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_mode);
gameScore = 0;
gameStatus = 0;
GridLayout gridLayout = (GridLayout)findViewById(R.id.grid_layout_6x4);
int numColumns = gridLayout.getColumnCount();
int numRow = gridLayout.getRowCount();
numberOfElements = numColumns * numRow;
MemoryButton[] buttons = new MemoryButton[numberOfElements];
int[] buttonGraphics = new int[numberOfElements / 2];
buttonGraphics[0] = R.drawable.card1;
buttonGraphics[1] = R.drawable.card2;
buttonGraphics[2] = R.drawable.card3;
buttonGraphics[3] = R.drawable.card4;
buttonGraphics[4] = R.drawable.card5;
buttonGraphics[5] = R.drawable.card6;
buttonGraphics[6] = R.drawable.card7;
buttonGraphics[7] = R.drawable.card8;
buttonGraphics[8] = R.drawable.card9;
buttonGraphics[9] = R.drawable.card10;
buttonGraphics[10] = R.drawable.card11;
buttonGraphics[11] = R.drawable.card12;
buttonGraphicLocations = new int[numberOfElements];
shuffleButtonGraphics();
for(int r=0; r < numRow; r++)
{
for(int c=0; c <numColumns; c++)
{
MemoryButton tempButton = new MemoryButton(this, r, c, buttonGraphics[buttonGraphicLocations[r * numColumns + c]]);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
tempButton.setId(View.generateViewId());
}
tempButton.setOnClickListener(this);
buttons[r * numColumns + c] = tempButton;
gridLayout.addView(tempButton);
}
}
}
protected void shuffleButtonGraphics(){
Random rand = new Random();
for (int i=0; i < numberOfElements; i++)
{
buttonGraphicLocations[i] = i % (numberOfElements / 2);
}
for (int i=0; i < numberOfElements; i++)
{
int temp = buttonGraphicLocations[i];
int swapIndex = rand.nextInt(16);
buttonGraphicLocations[i] = buttonGraphicLocations[swapIndex];
buttonGraphicLocations[swapIndex] = temp;
}
}
private int buttonGraphicLocations(int i) {
return 0;
}
#Override
public void onClick(View view) {
if(isBusy) {
return;
}
MemoryButton button = (MemoryButton) view;
if(button.isMatched) {
return;
}
if(selectedButton1 == null)
{
selectedButton1 = button;
selectedButton1.flip();
return;
}
if(selectedButton1.getId()== button.getId())
{
return;
}
if (selectedButton1.getFrontDrawableId()== button.getFrontDrawableId())
{
button.flip();
button.setMatched(true);
if (selectedButton1 != null) {
selectedButton1.setEnabled(false);
System.out.println("not null");
}
else{
System.out.println("null");
}
if (selectedButton2 != null) {
selectedButton2.setEnabled(false);
System.out.println("not null");
}
else{
System.out.println("null");
}
gameStatus = gameStatus + 1;
gameScore = gameScore + 10;
if (gameStatus == 12){
Intent it = new Intent(Game6x4Activity.this, ActivityScore.class);
startActivity(it);
}
selectedButton1 = null;
return;
}
else
{
selectedButton2 = button;
selectedButton2.flip();
isBusy = true;
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run(){
selectedButton2.flip();
selectedButton1.flip();
selectedButton1 = null;
selectedButton2 = null;
isBusy = false;
}
},500);
return;
}
}
}
The activity that i want to open will show to the player his score. the activity is equal to all game modes, there will be some test to the app understant what path should go on. test like this one:
"
if (gameStatus == 12) {
gameScore = gameScore*55;
TextView scoreText = (TextView) findViewById(R.id.textView8);
scoreText.setText(gameScore);
}
else if (gameStatus == 15){
"
There are 4 game modes: This is the 6x4 game, where we can find 24 cards (12 images).
else if (gameStatus == 15){
Intent intent = new Intent(Game6x4Activity.this, NextActivity.class);
startActivity(intent);
}
I think, you are asking for this. You can pass value to another activity with
intent.putExtra("key",desired value);
I am trying to display a progress dialog inside a fragment.But progressbar.show() do not have any effect.However,I noticed a strange behaviour,if i call showPopUp() method twice,it does show the progress dialog,but unable to dismiss().
package com.snapbizz.snapdashboard.Tabs.v1;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.snapbizz.snapdashboard.Core.v1.SalesData;
import com.snapbizz.snapdashboard.R;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class DashBoardSalesTab extends Fragment {
LinearLayout salesListContainer, salesBarConatainer;
LayoutInflater layoutInflater;
SalesData salesData;
ProgressDialog progressDialog;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.sales_page_layout, container, false);
return rootView;
}
public void showPopUp() {
progressDialog = new ProgressDialog(getContext(), ProgressDialog.THEME_HOLO_LIGHT);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("loading the page...");
progressDialog.setProgressNumberFormat(null);
progressDialog.setProgressPercentFormat(null);
progressDialog.setIndeterminate(true);
progressDialog.show();
}
public void synchronizeScrollers() {
getActivity().findViewById(R.id.page_scroller).setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
getActivity().findViewById(R.id.table_scroller).getParent()
.requestDisallowInterceptTouchEvent(true);
return false;
}
});
getActivity().findViewById(R.id.table_scroller).setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
v.getParent().requestDisallowInterceptTouchEvent(true);
return false;
}
});
}
public void renderSalesGraph(List<String[]> values, Float totalSumY) throws Exception {
salesBarConatainer.removeAllViews();
for (String[] value : values) {
View barView = layoutInflater.inflate(R.layout.bar_char_item_layout, salesBarConatainer, false);
float sumOfSalesForTheDay = Float.parseFloat((value[0] == null) ? "0" : value[0]);
float weightofBar = sumOfSalesForTheDay / totalSumY;
barView.findViewById(R.id.bar_y).setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, weightofBar));
((TextView) barView.findViewById(R.id.value_y)).setText(
(sumOfSalesForTheDay == 0.0f ? "" :
getActivity().getResources().getString(R.string.rupee_symbol) + sumOfSalesForTheDay + "")
);
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy/MM/dd");
SimpleDateFormat outputFormat = new SimpleDateFormat("dd-MMM-yyyy");
Date renderingDate = inputFormat.parse(value[2]);
String[] date = outputFormat.format(renderingDate).split("-");
((TextView) barView.findViewById(R.id.value_x_date)).setText(date[0] + " " + date[1]);
((TextView) barView.findViewById(R.id.value_x_year)).setText(date[2]);
salesBarConatainer.addView(barView);
}
}
public void renderSalesGraphForMonths(List<String[]> values, Float totalSumY) throws Exception {
LinearLayout salesBarConatainer = (LinearLayout) getActivity().findViewById(R.id.bars_container);
salesBarConatainer.removeAllViews();
for (String[] value : values) {
View barView = layoutInflater.inflate(R.layout.bar_char_item_layout, salesBarConatainer, false);
float sumOfSalesForTheDay = Float.parseFloat((value[0] == null) ? "0" : value[0]);
float weightofBar = sumOfSalesForTheDay / totalSumY;
barView.findViewById(R.id.bar_y).setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, weightofBar));
((TextView) barView.findViewById(R.id.value_y)).setText(
(sumOfSalesForTheDay == 0.0f ? "" :
getActivity().getResources().getString(R.string.rupee_symbol) + sumOfSalesForTheDay + "")
);
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy/MM");
SimpleDateFormat outputFormat = new SimpleDateFormat("MMM-yyyy");
Date renderingDate = inputFormat.parse(value[2]);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, renderingDate.getMonth());
cal.set(Calendar.DAY_OF_MONTH, 1);
barView.setOnClickListener(new MonthBarClickListener(cal));
String[] date = outputFormat.format(renderingDate).split("-");
((TextView) barView.findViewById(R.id.value_x_date)).setText(date[0]);
((TextView) barView.findViewById(R.id.value_x_year)).setText(date[1]);
salesBarConatainer.addView(barView);
}
}
public String[] addTOSalesTable(String date, boolean header) throws Exception {
List<String[]> values = salesData.getSalesTableData(date);
String[] value = values.get(0);
String[] newValue = {value[0], value[1], date};
String totalSales = (value[0] == null) ? "0" : value[0];
String totalCredit = (value[1] == null) ? "0" : value[1];
String totalCash = (Float.parseFloat(totalSales) - Float.parseFloat(totalCredit)) + "";
String rupeeSymbol = getActivity().getResources().getString(R.string.rupee_symbol);
if (!header) {
View salesRow = layoutInflater.inflate(R.layout.sales_page_table_row_layout, salesListContainer, false);
((TextView) (salesRow.findViewById(R.id.sale_date))).
setText(date);
((TextView) (salesRow.findViewById(R.id.sales_total_sale))).
setText(rupeeSymbol + " " + totalSales);
((TextView) (salesRow.findViewById(R.id.sales_total_cash))).
setText(rupeeSymbol + " " + totalCash);
((TextView) (salesRow.findViewById(R.id.sales_total_credit))).
setText(rupeeSymbol + " " + totalCredit);
((TextView) (salesRow.findViewById(R.id.sales_ttoal_coupon))).
setText(rupeeSymbol + " " + "0");
if (salesListContainer.getChildCount() % 2 != 0) {
salesRow.setBackgroundColor(getResources().getColor(R.color.table_row_alternate_color));
}
salesListContainer.addView(salesRow);
} else {
((TextView) (getActivity().findViewById(R.id.sales_header_total_sales))).
setText(rupeeSymbol + " " + totalSales);
((TextView) (getActivity().findViewById(R.id.sales_header_total_cash))).
setText(rupeeSymbol + " " + totalCash);
((TextView) (getActivity().findViewById(R.id.sales_header_total_credit))).
setText(rupeeSymbol + " " + totalCredit);
((TextView) (getActivity().findViewById(R.id.sales_header_total_coupon))).
setText(rupeeSymbol + " " + "0");
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
Date presentDate = new Date();
((TextView) (getActivity().findViewById(R.id.sales_header_day))).
setText(date.contentEquals(dateFormat.format(presentDate)) ? "Today" : date);
}
return newValue;
}
public void getMonths() throws Exception {
Calendar cal = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM");
List<String[]> values = new ArrayList<>();
float totalSumY = 0.0f;
for (int i = 0; i < 12; i++) {
cal.add(Calendar.MONTH, (i == 0) ? 0 : -1);
String date = dateFormat.format(cal.getTime());
String[] value = salesData.getSalesDataForMonth(date);
String[] newValue = {value[0] == null ? "0" : value[0], value[1] == null ? "0" : value[1], date};
totalSumY += Float.parseFloat(value[0] == null ? "0" : value[0]);
values.add(newValue);
}
renderSalesGraphForMonths(values, totalSumY);
}
public void initChart() {
FrameLayout dayButton = (FrameLayout) getActivity().findViewById(R.id.day_button);
FrameLayout monthButton = (FrameLayout) getActivity().findViewById(R.id.month_button);
dayButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
((TextView) getActivity().findViewById(R.id.button_day_text)).setTextColor(
getResources().getColor(R.color.dark_darkblue)
);
((TextView) getActivity().findViewById(R.id.button_day_text)).
setBackground(getResources().getDrawable(R.drawable.button_border_active));
((TextView) getActivity().findViewById(R.id.button_month_text)).setTextColor(
getResources().getColor(R.color.default_text_color)
);
((TextView) getActivity().findViewById(R.id.button_month_text)).
setBackground(getResources().getDrawable(R.drawable.button_border));
generateTablesRows(Calendar.getInstance(), 60, -1);
} catch (Exception e) {
e.printStackTrace();
}
}
});
monthButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
((TextView) getActivity().findViewById(R.id.button_month_text)).setTextColor(
getResources().getColor(R.color.dark_darkblue)
);
((TextView) getActivity().findViewById(R.id.button_month_text)).
setBackground(getResources().getDrawable(R.drawable.button_border_active));
((TextView) getActivity().findViewById(R.id.button_day_text)).setTextColor(
getResources().getColor(R.color.default_text_color)
);
((TextView) getActivity().findViewById(R.id.button_day_text)).
setBackground(getResources().getDrawable(R.drawable.button_border));
getMonths();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void generateTablesRows(Calendar cal, int limit, int increment) throws Exception {
salesListContainer.removeAllViews();
float totalSumY = 0.0f;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
List<String[]> barGraphValues = new ArrayList<>();
for (int i = 0; i < limit; i++) {
cal.add(Calendar.DATE, (i == 0) ? 0 : increment);
String date = dateFormat.format(cal.getTime());
String[] value = addTOSalesTable(date, (i == 0) ? true : false);
totalSumY += Float.parseFloat((value[0] == null) ? "1" : value[0]);
barGraphValues.add(value);
}
renderSalesGraph(barGraphValues, totalSumY);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
showPopUp();
layoutInflater = LayoutInflater.from(getContext());
salesListContainer = (LinearLayout) (getActivity().findViewById(R.id.sales_list_container));
salesListContainer.removeAllViews();
salesBarConatainer = (LinearLayout) getActivity().findViewById(R.id.bars_container);
salesBarConatainer.removeAllViews();
new SalesTabLoader().execute();
}
public class MonthBarClickListener implements View.OnClickListener {
Calendar cal;
public MonthBarClickListener(Calendar cal) {
this.cal = cal;
}
#Override
public void onClick(View v) {
try {
//new SalesAsyncTask(cal).execute(cal.getActualMaximum(Calendar.DAY_OF_MONTH),1);
generateTablesRows(cal, cal.getActualMaximum(Calendar.DAY_OF_MONTH), 1);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class SalesTabLoader extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
salesData = new SalesData(getContext());
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
try {
initChart();
generateTablesRows(Calendar.getInstance(), 60, -1);
} catch (Exception e) {
e.printStackTrace();
} finally {
synchronizeScrollers();
progressDialog.dismiss();
}
}
}
}
Try like this :
progressDialog = new ProgressDialog(getActivity());
And if you wish to customize your dialog and put self created Layout in it.
/**
* Created by vivek on 18/10/16.
*/
public class CustomDialog {
private static Dialog dialog;
private static Context context;
public CustomDialog(Context context) {
this.context = context;
}
/**
* Comman progress dialog ... initiates with this
*
* #param message
* #param title
*/
public static void showProgressDialog(Context context, String title, String message) {
if (dialog == null)
{
dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom_loader);
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
}
public static boolean isProgressDialogRunning() {
if (dialog != null && dialog.isShowing()) {
return true;
} else return false;
}
/**
* Dismiss comman progress dialog
*/
public static void dismissProgressDialog() {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
dialog = null;
}
}
} // End of main class over here ...
Replace this:-
progressDialog = new ProgressDialog(getContext(), ProgressDialog.THEME_HOLO_LIGHT);
with
progressDialog = new ProgressDialog(getActivity());
May be. you are showing two progressdialog and both of that progressbar on screen.. but when you dismiss your progressbar at that time the previous one is override by other one before you dismiss first one .. so the firstone is always in screen. that's the issue.
I tried everything.But none of the answers solved the issue.However,i solved it by overriding onResume() method in the fragment.
Thanks All.
I trying to change chatroom.java's createReplayMsg message resource from GCM ,but why apapter.getData().add error?
It tell me java.util.List com.example.yoyotrip.chat.MessageAdapter.getData()' on a null object reference.
maybe I should use AsyncTask to finish it?
PS. I am first use this forum ,other Resources in this-> https://github.com/yyting/yoyotrip or tell me,thanks.
Logcat:
09-17 16:42:14.410 8416-8416/com.example.yoyotrip E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.yoyotrip, PID: 8416
java.lang.RuntimeException: Unable to start receiver com.example.yoyotrip.GCM.GcmBroadcastReceiver: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List com.example.yoyotrip.chat.MessageAdapter.getData()' on a null object reference
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2586)
at android.app.ActivityThread.access$1700(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List com.example.yoyotrip.chat.MessageAdapter.getData()' on a null object reference
at com.example.yoyotrip.GCM.GcmBroadcastReceiver.onReceive(GcmBroadcastReceiver.java:63)
chatroom.java
package com.example.yoyotrip;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ListView;
import android.widget.Toast;
import com.example.yoyotrip.chat.Message;
import com.example.yoyotrip.chat.MessageAdapter;
import com.example.yoyotrip.chat.MessageInputToolBox;
import com.example.yoyotrip.chat.OnOperationListener;
import com.example.yoyotrip.chat.Option;
public class chatroom extends ActionBarActivity {
private MessageInputToolBox box;
public ListView listView;
public MessageAdapter adapter;
public List<Message> messages ;
#SuppressLint("UseSparseArrays")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chatroom);
initMessageInputToolBox();
initListView();
}
/**
* init MessageInputToolBox
*/
#SuppressLint("ShowToast")
public void initMessageInputToolBox(){
box = (MessageInputToolBox) findViewById(R.id.messageInputToolBox);
box.setOnOperationListener(new OnOperationListener() {
#Override
public void send(String content) {
System.out.println("===============" + content);
int rd=(int)(Math.random()*99)+1;
Message message = new Message(0, 1, rd%2==1?"Tom":"helen", "avatar", "Jerry", "avatar", content, true, true, new Date());
adapter.getData().add(message);
listView.setSelection(listView.getBottom());
//Just demo
createReplayMsg(message);
}
#Override
public void selectedFace(String content) {
System.out.println("===============" + content);
Message message = new Message(Message.MSG_TYPE_FACE, Message.MSG_STATE_SUCCESS, "Tomcat", "avatar", "Jerry", "avatar", content, true, true, new Date());
adapter.getData().add(message);
listView.setSelection(listView.getBottom());
//Just demo
createReplayMsg(message);
}
#Override
public void selectedFuncation(int index) {
System.out.println("===============" + index);
switch (index) {
case 0:
//do some thing
break;
case 1:
//do some thing
break;
default:
break;
}
Toast.makeText(chatroom.this, "Do some thing here, index :" +index, Toast.LENGTH_LONG).show();
}
});
ArrayList<String> faceNameList = new ArrayList<String>();
for(int x = 1; x <= 10; x++){
faceNameList.add("big"+x);
}
for(int x = 1; x <= 10; x++){
faceNameList.add("big"+x);
}
ArrayList<String> faceNameList1 = new ArrayList<String>();
for(int x = 1; x <= 7; x++){
faceNameList1.add("cig"+x);
}
ArrayList<String> faceNameList2 = new ArrayList<String>();
for(int x = 1; x <= 24; x++){
faceNameList2.add("dig"+x);
}
Map<Integer, ArrayList<String>> faceData = new HashMap<>();
faceData.put(R.drawable.em_cate_magic, faceNameList2);
faceData.put(R.drawable.em_cate_rib, faceNameList1);
faceData.put(R.drawable.em_cate_duck, faceNameList);
box.setFaceData(faceData);
List<Option> functionData = new ArrayList<Option>();
for(int x = 0; x < 5; x++){
Option takePhotoOption = new Option(this, "Take", R.drawable.take_photo);
Option galleryOption = new Option(this, "Gallery", R.drawable.gallery);
functionData.add(galleryOption);
functionData.add(takePhotoOption);
}
box.setFunctionData(functionData);
}
private void initListView(){
listView = (ListView) findViewById(R.id.messageListview);
//create Data
Message message = new Message(Message.MSG_TYPE_TEXT, Message.MSG_STATE_SUCCESS, "Tom", "avatar", "Jerry", "avatar", "Hi,大家好我是你們的導遊", true, true, new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24) * 8));
Message message1 = new Message(Message.MSG_TYPE_TEXT, Message.MSG_STATE_SUCCESS, "Tom", "avatar", "Jerry", "avatar", "Hello", false ,true, new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24)* 8));
Message message2 = new Message(Message.MSG_TYPE_TEXT, Message.MSG_STATE_SUCCESS, "helen", "avatar", "Jerry", "avatar", "我們要在哪集合??", false, true, new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24) * 7));
Message message3 = new Message(Message.MSG_TYPE_TEXT, Message.MSG_STATE_SUCCESS, "Tom", "avatar", "Jerry", "avatar", "台北車站嗎!?", false, true, new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24) * 7));
Message message4 = new Message(Message.MSG_TYPE_FACE, Message.MSG_STATE_SUCCESS, "Joe", "avatar", "Jerry", "avatar", "big3", false, true, new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24) * 6));
Message message5 = new Message(Message.MSG_TYPE_TEXT, Message.MSG_STATE_SUCCESS, "Joe", "avatar", "Jerry", "avatar", "可以在229公園那邊嗎?", false, true, new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24) * 6));
// Message message6 = new Message(Message.MSG_TYPE_TEXT, Message.MSG_STATE_FAIL, "Tom", "avatar", "Jerry", "avatar", "test send fail", true, false, new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24) * 6));
// Message message7 = new Message(Message.MSG_TYPE_TEXT, Message.MSG_STATE_SENDING, "Tom", "avatar", "Jerry", "avatar", "test sending", true, true, new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24) * 6));
messages = new ArrayList<Message>();
messages.add(message);
messages.add(message1);
messages.add(message2);
messages.add(message3);
messages.add(message4);
messages.add(message5);
// messages.add(message6);
// messages.add(message7);
adapter = new MessageAdapter(this, messages);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
listView.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
box.hide();
return false;
}
});
}
//change message resource from GCM
public void createReplayMsg(final Message message){
final Message reMessage = new Message(message.getType(), 1, message.getFromUserName(), "avatar", "Jerry", "avatar",
message.getType() == 0 ? "Re:" + message.getContent() : message.getContent(),
false, true, new Date()
);
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(1000 * (new Random().nextInt(3) +1));
runOnUiThread(new Runnable() {
#Override
public void run() {
adapter.getData().add(reMessage);
adapter.notifyDataSetChanged();
listView.setSelection(listView.getBottom());
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
MessageAdapter.java
package com.example.yoyotrip.chat;
import android.annotation.SuppressLint;
import android.content.Context;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import com.example.yoyotrip.R;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
//import com.nostra13.universalimageloader.core.DisplayImageOptions;
//import com.nostra13.universalimageloader.core.ImageLoader;
public class MessageAdapter extends BaseAdapter {
private Context context;
private List<Message> data = null;
public MessageAdapter(Context context, List<Message> list) {
super();
this.context = context;
this.data = list;
}
#Override
public int getCount() {
return data != null ? data.size() : 0;
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return this.data.get(position).getIsSend() ? 1 : 0;
}
#Override
public int getViewTypeCount() {
return 2;
}
#SuppressLint("InflateParams")
public View getView(int position, View convertView, ViewGroup parent) {
final Message message = data.get(position);
boolean isSend = message.getIsSend();
ViewHolder viewHolder = null;
if (convertView == null) {
viewHolder = new ViewHolder();
if (isSend) {
convertView = LayoutInflater.from(context).inflate(R.layout.msg_item_right, null);
} else {
convertView = LayoutInflater.from(context).inflate(R.layout.msg_item_left, null);
}
viewHolder.sendDateTextView = (TextView) convertView.findViewById(R.id.sendDateTextView);
viewHolder.sendTimeTextView = (TextView) convertView.findViewById(R.id.sendTimeTextView);
viewHolder.userAvatarImageView = (ImageView) convertView.findViewById(R.id.userAvatarImageView);
viewHolder.userNameTextView = (TextView) convertView.findViewById(R.id.userNameTextView);
viewHolder.textTextView = (TextView) convertView.findViewById(R.id.textTextView);
viewHolder.photoImageView = (ImageView) convertView.findViewById(R.id.photoImageView);
viewHolder.faceImageView = (ImageView) convertView.findViewById(R.id.faceImageView);
viewHolder.failImageView = (ImageView) convertView.findViewById(R.id.failImageView);
viewHolder.sendingProgressBar = (ProgressBar) convertView.findViewById(R.id.sendingProgressBar);
viewHolder.isSend = isSend;
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
try {
String dateString = DateFormat.format("yyyy-MM-dd h:mmaa", message.getTime()).toString();
String[] t = dateString.split(" ");
viewHolder.sendDateTextView.setText(t[0]);
viewHolder.sendTimeTextView.setText(t[1]);
if(position == 0){
viewHolder.sendDateTextView.setVisibility(View.VISIBLE);
}else{
//TODO is same day ?
Message pmsg = data.get(position-1);
if(inSameDay(pmsg.getTime(), message.getTime())){
viewHolder.sendDateTextView.setVisibility(View.GONE);
}else{
viewHolder.sendDateTextView.setVisibility(View.VISIBLE);
}
}
} catch (Exception e) {
}
viewHolder.userNameTextView.setText(message.getFromUserName());
switch (message.getType()) {
case 0://text
viewHolder.textTextView.setText(message.getContent());
viewHolder.textTextView.setVisibility(View.VISIBLE);
viewHolder.photoImageView.setVisibility(View.GONE);
viewHolder.faceImageView.setVisibility(View.GONE);
if(message.getIsSend()){
LayoutParams sendTimeTextViewLayoutParams = (LayoutParams) viewHolder.sendTimeTextView.getLayoutParams();
sendTimeTextViewLayoutParams.addRule(RelativeLayout.LEFT_OF, R.id.textTextView);
viewHolder.sendTimeTextView.setLayoutParams(sendTimeTextViewLayoutParams);
LayoutParams layoutParams = (LayoutParams) viewHolder.failImageView.getLayoutParams();
layoutParams.addRule(RelativeLayout.LEFT_OF, R.id.textTextView);
if( message.getSendSucces() != null && message.getSendSucces() == false){
viewHolder.failImageView.setVisibility(View.VISIBLE);
viewHolder.failImageView.setLayoutParams(layoutParams);
}else{
viewHolder.failImageView.setVisibility(View.GONE);
}
if(message.getState() != null && message.getState() == 0){
viewHolder.sendingProgressBar.setVisibility(View.VISIBLE);
viewHolder.sendingProgressBar.setLayoutParams(layoutParams);
}else{
viewHolder.sendingProgressBar.setVisibility(View.GONE);
}
}else{
viewHolder.failImageView.setVisibility(View.GONE);
viewHolder.sendingProgressBar.setVisibility(View.GONE);
LayoutParams sendTimeTextViewLayoutParams = (LayoutParams) viewHolder.sendTimeTextView.getLayoutParams();
sendTimeTextViewLayoutParams.addRule(RelativeLayout.RIGHT_OF, R.id.textTextView);
viewHolder.sendTimeTextView.setLayoutParams(sendTimeTextViewLayoutParams);
}
break;
case 1://photo
viewHolder.textTextView.setVisibility(View.GONE);
viewHolder.photoImageView.setVisibility(View.VISIBLE);
viewHolder.faceImageView.setVisibility(View.GONE);
//TODO set image
int id = context.getResources().getIdentifier(message.getContent(), "drawable", context.getPackageName());
viewHolder.photoImageView.setImageResource(id);
if(message.getIsSend() ){
LayoutParams sendTimeTextViewLayoutParams = (LayoutParams) viewHolder.sendTimeTextView.getLayoutParams();
sendTimeTextViewLayoutParams.addRule(RelativeLayout.LEFT_OF, R.id.photoImageView);
viewHolder.sendTimeTextView.setLayoutParams(sendTimeTextViewLayoutParams);
LayoutParams layoutParams = (LayoutParams) viewHolder.failImageView.getLayoutParams();
layoutParams.addRule(RelativeLayout.LEFT_OF, R.id.photoImageView);
if(message.getSendSucces() != null && message.getSendSucces() == false){
viewHolder.failImageView.setVisibility(View.VISIBLE);
viewHolder.failImageView.setLayoutParams(layoutParams);
}else{
viewHolder.failImageView.setVisibility(View.GONE);
}
if(message.getState() != null && message.getState() == 0){
viewHolder.sendingProgressBar.setVisibility(View.VISIBLE);
viewHolder.sendingProgressBar.setLayoutParams(layoutParams);
}else{
viewHolder.sendingProgressBar.setVisibility(View.GONE);
}
}else{
viewHolder.failImageView.setVisibility(View.GONE);
LayoutParams sendTimeTextViewLayoutParams = (LayoutParams) viewHolder.sendTimeTextView.getLayoutParams();
sendTimeTextViewLayoutParams.addRule(RelativeLayout.RIGHT_OF, R.id.photoImageView);
viewHolder.sendTimeTextView.setLayoutParams(sendTimeTextViewLayoutParams);
}
break;
case 2://face
viewHolder.photoImageView.setVisibility(View.GONE);
viewHolder.textTextView.setVisibility(View.GONE);
viewHolder.faceImageView.setVisibility(View.VISIBLE);
int resId = context.getResources().getIdentifier(message.getContent(), "drawable", context.getPackageName());
viewHolder.faceImageView.setImageResource(resId);
if(message.getIsSend()){
LayoutParams sendTimeTextViewLayoutParams = (LayoutParams) viewHolder.sendTimeTextView.getLayoutParams();
sendTimeTextViewLayoutParams.addRule(RelativeLayout.LEFT_OF, R.id.faceImageView);
viewHolder.sendTimeTextView.setLayoutParams(sendTimeTextViewLayoutParams);
LayoutParams layoutParams = (LayoutParams) viewHolder.failImageView.getLayoutParams();
layoutParams.addRule(RelativeLayout.LEFT_OF, R.id.faceImageView);
if(message.getSendSucces() != null && message.getSendSucces() == false){
viewHolder.failImageView.setVisibility(View.VISIBLE);
viewHolder.failImageView.setLayoutParams(layoutParams);
}else{
viewHolder.failImageView.setVisibility(View.GONE);
}
if(message.getState() != null && message.getState() == 0){
viewHolder.sendingProgressBar.setVisibility(View.VISIBLE);
viewHolder.sendingProgressBar.setLayoutParams(layoutParams);
}else{
viewHolder.sendingProgressBar.setVisibility(View.GONE);
}
}else{
viewHolder.failImageView.setVisibility(View.GONE);
LayoutParams sendTimeTextViewLayoutParams = (LayoutParams) viewHolder.sendTimeTextView.getLayoutParams();
sendTimeTextViewLayoutParams.addRule(RelativeLayout.RIGHT_OF, R.id.faceImageView);
viewHolder.sendTimeTextView.setLayoutParams(sendTimeTextViewLayoutParams);
}
break;
default:
viewHolder.textTextView.setText(message.getContent());
viewHolder.photoImageView.setVisibility(View.GONE);
viewHolder.faceImageView.setVisibility(View.GONE);
break;
}
// viewHolder.textTextView.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
return convertView;
}
public List<Message> getData() {
return data;
}
public void setData(List<Message> data) {
this.data = data;
}
public static boolean inSameDay(Date date1, Date Date2) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date1);
int year1 = calendar.get(Calendar.YEAR);
int day1 = calendar.get(Calendar.DAY_OF_YEAR);
calendar.setTime(Date2);
int year2 = calendar.get(Calendar.YEAR);
int day2 = calendar.get(Calendar.DAY_OF_YEAR);
if ((year1 == year2) && (day1 == day2)) {
return true;
}
return false;
}
static class ViewHolder {
public ImageView userAvatarImageView;
public TextView sendDateTextView;
public TextView userNameTextView;
public TextView textTextView;
public ImageView photoImageView;
public ImageView faceImageView;
public ImageView failImageView;
public TextView sendTimeTextView;
public ProgressBar sendingProgressBar;
public boolean isSend = true;
}
}
GcmBroadcastReceiver.java
package com.example.yoyotrip.GCM;
/**
* Created by colm on 2015/8/3.
*/
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.util.Log;
import android.widget.ListView;
import com.example.yoyotrip.MainActivity;
import com.example.yoyotrip.R;
import com.example.yoyotrip.chat.Message;
import com.example.yoyotrip.chat.MessageAdapter;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import java.util.Date;
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
public static final int NOTIFICATION_ID = 0;
public ListView listView;
public MessageAdapter adapter;
#Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) {
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR
.equals(messageType)) {
Log.i(getClass() + " GCM ERROR", extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED
.equals(messageType)) {
Log.i(getClass() + " GCM DELETE", extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
.equals(messageType)) {
Log.i(getClass() + " GCM MESSAGE", extras.toString());
if (extras.getString("title") .equals("chat")) {
/*show noteic*/
Intent i = new Intent(context, MainActivity.class);
i.setAction("android.intent.action.MAIN");
i.addCategory("android.intent.category.LAUNCHER");
MagicLenGCM.sendLocalNotification(context, NOTIFICATION_ID,
R.drawable.icon, "noteic", extras
.getString("message"), extras.getString("whofrom"), false,
PendingIntent.getActivity(context, 0, i,
PendingIntent.FLAG_CANCEL_CURRENT));
//message addchat
final Message message = new Message(0, 1, extras.getString("whofrom"), "avatar", "Jerry", "avatar", extras.getString("message"), false, true, new Date());
adapter.getData().add(message);
adapter.notifyDataSetChanged();
listView.setSelection(listView.getBottom());
} else if (extras.getString("title").equals("GCM")) {
Intent i = new Intent(context, MainActivity.class);
i.setAction("android.intent.action.MAIN");
i.addCategory("android.intent.category.LAUNCHER");
MagicLenGCM.sendLocalNotification(context, NOTIFICATION_ID,
R.drawable.icon, "GCM noteic", extras
.getString("message"), "yoyotrip", false,
PendingIntent.getActivity(context, 0, i,
PendingIntent.FLAG_CANCEL_CURRENT));
}
}
}
setResultCode(Activity.RESULT_OK);
}
}
You never use your adapter's constructor to create a new instance in GcmBroadcastReceiver. Your adapter will always be null, hence, NullPointerExceptions on that getData() call.
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;
}