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.
Related
I'm new in android and also new in English sorry my bad English...
I have learned android course at the academy.
My sentence may be wrong because it is written through a translator. I hope you understand with a generous heart.
Here's what I want:
If I click 15 days in Calendar View,
It is hoped that only the 15th day information will be shown in the Recyclerview. If I click on another date in calenderview, for example, 20 days, I hope that the 15th item will disappear and only the 20th item view will be displayed.
Here's what I'm trying to do.
When I click a date in a calendar view, I want to see the Item View corresponding to that date.
package com.example.myapplication;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.icu.util.Calendar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class Calender extends AppCompatActivity {
// CalendarView myCalenderView;
// TextView schedule1, schedule11;
String a, b, c;
static String data1;
long Now;
Date date;
java.text.SimpleDateFormat mFormat = new SimpleDateFormat("YYYY_MM_dd");
TextView datetext;
Context mcontext;
private String getTime() {
Now = System.currentTimeMillis();
date = new Date(Now);
return mFormat.format(date);
}
private ArrayList<calenderArrayList> mArrayList = new ArrayList<>();
private ArrayList<calenderArrayList> bArrayList = new ArrayList<>();
SharedPreferences preferences;
SharedPreferences.Editor editor;
private static String TAG = "recyclerview_example";
//private ArrayList<calenderArrayList> mArrayList;
//ArrayList 선언
calendarAdapter mAdapter = new calendarAdapter(this, mArrayList);
//mAdapter 선언
// calendarAdapter bAdapter = new calendarAdapter(this, bArrayList);
private RecyclerView mRecyclerView;
private LinearLayoutManager mLinearLayoutManager;
private int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calender);
Log.d("스케쥴선택액티비티", "OnCreate()실행");
SharedPreferences calender_load = getSharedPreferences("calender", MODE_PRIVATE);
calender_load.getInt("save_size", 0);
int calender_size = calender_load.getInt("save_size", 0);
Log.d("시작시b사이즈1", "" + calender_size);
Log.d("시작시b사이즈1", "" + bArrayList.size());
Log.d("시작시m사이즈1", "" + mArrayList.size());
if (calender_size != 0) {
for (int i = 0; i < calender_size; i++) {
calenderArrayList calender = new calenderArrayList(calender_load.getString("save_date" + i, ""), calender_load.getString("save_work" + i, ""), calender_load.getString("save_place" + i, ""), calender_load.getBoolean("save_box" + i, false));
if (calender.number_exam.equals(data1)) {
Log.d("불러오기값", "" + calender_load.getString("save_date" + i, ""));
bArrayList.add(calender);
mArrayList.add(calender);
}
mAdapter = new calendarAdapter(this, mArrayList);
mAdapter.notifyDataSetChanged();
}
} else if (calender_size == 0) {
mAdapter = new calendarAdapter(this, mArrayList);
mAdapter.notifyDataSetChanged();
}
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view_exam);
//recycler_view라는 id를 가진 recycler_view를 mRecyclerView로 지정해준다.
mRecyclerView.addItemDecoration(new DividerItemDecoration(mRecyclerView.getContext(), 1));
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
//RecyclerView 내에 Item view들의 크기를 측정하고 위치를 지정
//언제 item view를 재사용해야하는지에 대한 정책을 결정하고 결정.
//mArrayList = new ArrayList<>();
mAdapter = new calendarAdapter(this, mArrayList);
//RecyclerView 내에 보여지는 view 들에 date set을 binding 시켜주는 역할.
//binding? 데이터 끼리 묵어준다?
mRecyclerView.setAdapter(mAdapter);
//mRecyclerView의 Adapter를 mAdapter로 set한다.
//set? 지정한다. 놓다. 위치하다.
// myCalenderView = (CalendarView) findViewById(R.id.calendar);
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
// Toast.makeText(getApplicationContext(), "onStart()", Toast.LENGTH_SHORT).show();
Log.d("스케쥴선택액티비티", "OnStart()실행");
Log.d("스케쥴선택액티비티", "OnResume()실행");
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
// Toast.makeText(getApplicationContext(), "onResume()", Toast.LENGTH_SHORT).show();
final CalendarView calendar = (CalendarView) findViewById(R.id.calendar);
calendar.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
#Override
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
data1 = year + "/" + (month + 1) + "/" + dayOfMonth;
String a = data1 + dayOfMonth;
Log.d("날짜", "" + a);
ArrayList<calenderArrayList> dayofMonth = new ArrayList<>();
Log.d("어떤 이름으로?", "" + dayofMonth);
if (dayofMonth.size() != 0) {
SharedPreferences load = getSharedPreferences("" + data1, MODE_PRIVATE);
}
/* if(mArrayList.size()!=0) {
for (int i=0; i<mArrayList.size() ; i++) {
SharedPreferences save11 = getSharedPreferences("save", MODE_PRIVATE );
SharedPreferences.Editor save_editor = save11.edit();
save_editor.putBoolean("save_box"+i+mArrayList.get(i).number_exam, mArrayList.get(i).selected );
save_editor.putString("save_date"+i+mArrayList.get(i).number_exam, mArrayList.get(i).number_exam);
save_editor.putString("save_work"+i+mArrayList.get(i).number_exam, mArrayList.get(i).content_exam);
save_editor.putString("save_place"+i+mArrayList.get(i).number_exam, mArrayList.get(i).content_exam2);
save_editor.putInt("save_size"+mArrayList.get(i).number_exam, mArrayList.size());
save_editor.commit();
}
}
mArrayList.clear();
if(mArrayList.size()!=0)
{
for (int i =0; i<mArrayList.size(); i++){
if(mArrayList.get(i).number_exam.equals(data1)){
}
}
}*/
//int a = dayOfMonth;
Toast.makeText(Calender.this, year + "/" + (month + 1) + "/" + dayOfMonth, Toast.LENGTH_SHORT).show();
Log.d("리사이클러뷰 실행 전", "실행 전");
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view_exam);
Log.d("리사이클러뷰 실행 후", "실행 후");
final EditText number_exam = (EditText) view.findViewById(R.id.calender_date);
final EditText content_exam = (EditText) view.findViewById(R.id.calender_place);
final EditText content_exam2 = (EditText) view.findViewById(R.id.calender_content);
//TextView ee = findViewById(R.id.number_exam);
Log.d("사이즈 측정 실행 전", "실행 전");
ArrayList<calenderArrayList> calenderArrayLists = new ArrayList<>();
Log.d("실행11111", mAdapter.getItemCount() + "");
Log.d("뭐가 들어있나?", "" + mArrayList);
Log.d("뭐가 들어있나?", "" + mArrayList.size());
// Log.d("뭐가 들어았나?", ""+mArrayList.get(1).number_exam.toString());
// Log.d("뭐가 들어았나?", ""+mArrayList.get(2).number_exam.toString());
// Log.d("뭐가 들어았나?", ""+mArrayList.get(3).number_exam.toString());
if (mArrayList.size() != 0) {
Log.d("if구문 실행됨?", "" + mArrayList.size());
//1. 일단 뷰 자체를 초기화 해주어야함.
//2. 초기화 된 뷰에 다시 mArrayList에서 선정 된 정보를 다시 나타내주어야한다.
/* for(int i = 0; i<mArrayList.size(); i++){
Log.d("얼마?", ""+i);
Log.d("for 구문 작동?실행", "여기까진 접속?");
if(mArrayList.get(i).number_exam.toString().contains(a)){
Log.d("뭐가 들어있나? 실행여부", ""+mArrayList.get(i).number_exam.toString());
a = mArrayList.get(i).number_exam;
b = mArrayList.get(i).content_exam;
c = mArrayList.get(i).content_exam2;
//mArrayList.add(mArrayList.get(i));
}
}*/
}
}
});
Button buttonInsert_exam = (Button) findViewById(R.id.exam_button);
//button 클릭시 발생하는 이벤트를 나타낸다. 여기서는 입력하기 버튼 클릭시 발생하는 상황.
buttonInsert_exam.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(Calender.this);
View view = LayoutInflater.from(Calender.this)
.inflate(R.layout.activity_calender_edit_box, null, false);
builder.setView(view);
final Button ButtonSubmit_exam = (Button) view.findViewById(R.id.button_dialog_submit_exam);
final EditText number_exam = (EditText) view.findViewById(R.id.calender_date);
final EditText content_exam = (EditText) view.findViewById(R.id.calender_place);
final EditText content_exam2 = (EditText) view.findViewById(R.id.calender_content);
// final EditText editTextKorean = (EditText) view.findViewById(R.id.edittext_dialog_korean);
ButtonSubmit_exam.setText("입력하기");
number_exam.setText(data1);
final AlertDialog dialog = builder.create();
dialog.show();
//dialog에 나타나는 입력하기 버튼을 눌렀을 때 발생하는 상황
ButtonSubmit_exam.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String strID = number_exam.getText().toString();
String strID2 = content_exam.getText().toString();
String strID3 = content_exam2.getText().toString();
//number와 content view에 입력한 문자열을 strID, strID2에 담는다.
//String strKorean = editTextKorean.getText().toString();
calenderArrayList dict = new calenderArrayList(strID, strID2, strID3);
bArrayList.add(0, dict);
mArrayList.add(0, dict); //첫 줄에 삽입
//mArrayList.add(dict); //마지막 줄에 삽입
mAdapter.notifyDataSetChanged(); //변경된 데이터를 화면에 반영
Log.d("b사이즈", "" + bArrayList.size());
Log.d("m사이즈", "" + mArrayList.size());
dialog.dismiss();
//dialog를 종료 시켜준다.
}
});
}
});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
// Toast.makeText(getApplicationContext(), "onPause()", Toast.LENGTH_SHORT).show();
SharedPreferences calendersave = getSharedPreferences("calender", MODE_PRIVATE);
SharedPreferences.Editor calendersaveeditor = calendersave.edit();
//calenderArrayList calenderArrayList = new calenderArrayList();
if (bArrayList.size() != 0) {
for (int i = 0; i < bArrayList.size(); i++) {
calendersaveeditor.putBoolean("save_box" + i, bArrayList.get(i).selected);
calendersaveeditor.putString("save_date" + i, bArrayList.get(i).number_exam);
calendersaveeditor.putString("save_work" + i, bArrayList.get(i).content_exam);
calendersaveeditor.putString("save_place" + i, bArrayList.get(i).content_exam2);
calendersaveeditor.putInt("save_size", bArrayList.size());
calendersaveeditor.commit();
Log.d("종료시b사이즈", "" + bArrayList.size());
Log.d("종료시m사이즈", "" + mArrayList.size());
}
} else if (bArrayList.size() == 0) {
calendersaveeditor.clear();
calendersaveeditor.commit();
}
Log.d("스케쥴선택액티비티", "OnPause()실행");
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
// Toast.makeText(getApplicationContext(), "onStop()", Toast.LENGTH_SHORT).show();
/*
* if(mArrayList.size()!=0){
for(int i = 0; i< mArrayList.size(); i++){
calendersaveeditor.putBoolean("save_box"+i, mArrayList.get(i).selected);
calendersaveeditor.putString("save_date"+i, mArrayList.get(i).number_exam);
calendersaveeditor.putString("save_work"+i, mArrayList.get(i).content_exam);
calendersaveeditor.putString("save_place"+i, mArrayList.get(i).content_exam2);
calendersaveeditor.putInt("save_size", mArrayList.size());
calendersaveeditor.commit();
}
}
else if(mArrayList.size()==0){
calendersaveeditor.clear();
calendersaveeditor.commit();
}
*/
Log.d("스케쥴선택액티비티", "OnStop()실행");
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
// Toast.makeText(getApplicationContext(), "onRestart()", Toast.LENGTH_SHORT).show();
Log.d("스케쥴선택액티비티", "OnRestart()실행");
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
// Toast.makeText(getApplicationContext(), "onDestroy()", Toast.LENGTH_SHORT).show();
Log.d("스케쥴선택액티비티", "OnDestroy()실행");
}
}
First you need to add new entry in your existing mArrayList as i am can see from your code you are adding all existing entries again but not new entry.
After that you need to set adapter again with new mArrayList only then you will be able to see new data in your recycler view.
I do not understand why last contact is added to the first card in recyclerview again when activity is resumed. I know that it is to do with cursor or content resolver.
Here is the java class with which I have problem.
while retreiving contacts again on onResume, last contact is re-added on first card in recycler view
package com.android.eventers;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.ContactsContract;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberType;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
import java.util.ArrayList;
import java.util.Locale;
public class ContactsActivity extends AppCompatActivity implements ContactsAdapter.ListItemClickListener {
private static final int CHECK_CLICK = 1;
private static final String LIST_STATE_KEY = "list_state";
FloatingActionButton mFloatingActionButton;
RecyclerView mRecyclerView;
ContactsAdapter mAdapter;
String contactName;
String mobileNumber;
String mobileNumberSelected;
Contacts contactsObject;
TextView noItem;
private ArrayList<Contacts> contactsArrayList;
ArrayList<String> tempList;
private Parcelable mListState;
private LinearLayoutManager mLayoutManager;
SharedPreferences mSharedPreferences;
SharedPreferences.Editor mEditor;
private boolean mCalledFromOncreate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
mCalledFromOncreate = true;
noItem = (TextView) findViewById(R.id.no_listitem_in_contacts);
noItem.setVisibility(View.GONE);
mFloatingActionButton = (FloatingActionButton) findViewById(R.id.add_fab_in_main);
contactsArrayList = new ArrayList<Contacts>();
mSharedPreferences = getPreferences(Context.MODE_PRIVATE);
mEditor = mSharedPreferences.edit();
launchConacts();
for (int i = 0; i < contactsArrayList.size(); i++) {
Log.e("name:", "" + contactsArrayList.get(i).getName());
for (int j = 0; j < contactsArrayList.get(i).getMobileNumber().size(); j++) {
Log.e("num:", contactsArrayList.get(i).getMobileNumber().get(j));
}
}
mFloatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String data = "";
int counter = 0;
for (int i = 0; i < contactsArrayList.size(); i++) {
Contacts singleContact = contactsArrayList.get(i);
if (contactsArrayList.get(i).getFlag()) {
data = data + "\n" + singleContact.getName().toString() + " " + singleContact.getSelectedMobileNumber();
counter++;
mEditor.putBoolean("checkbox_" + contactsArrayList.get(i).getName(), true);
mEditor.putString("selected_mobile_number_for_" + contactsArrayList.get(i).getName(), "" + singleContact.getSelectedMobileNumber());
} else {
mEditor.putBoolean("checkbox_" + contactsArrayList.get(i).getName(), false);
mEditor.putString("selected_mobile_number_for_" + contactsArrayList.get(i).getName(), "" + singleContact.getSelectedMobileNumber());
}
}
mEditor.commit();
Toast.makeText(ContactsActivity.this, "Selected contacts: \n" + data, Toast.LENGTH_LONG).show();
Intent intent = new Intent(ContactsActivity.this, ReportActivity.class);
intent.putExtra("TOTAL_KEY", contactsArrayList.size() + "");
intent.putExtra("SELECTED_KEY", counter + "");
startActivity(intent);
}
});
}
#Override
public void onListItemClick(final int clickedItemIndex, int whichClick) {
switch (whichClick) {
case CHECK_CLICK: {
//Toast.makeText(ContactsActivity.this, "Clicked on Checkbox: "+clickedItemIndex , Toast.LENGTH_SHORT).show();
int selectedMobileNumberPosition = 0;
String selectedMobileNumber = contactsArrayList.get(clickedItemIndex).getSelectedMobileNumber();
if (contactsArrayList.get(clickedItemIndex).getMobileNumber().size() > 1) {
final String items[] = new String[contactsArrayList.get(clickedItemIndex).getMobileNumber().size()];
for (int j = 0; j < contactsArrayList.get(clickedItemIndex).getMobileNumber().size(); j++) {
items[j] = contactsArrayList.get(clickedItemIndex).getMobileNumber().get(j);
if (items[j].contains(selectedMobileNumber)) {
selectedMobileNumberPosition = j;
}
}
AlertDialog levelDialog;
// Creating and Building the Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Please select the mobile number");
builder.setSingleChoiceItems(items, selectedMobileNumberPosition, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
mobileNumberSelected = items[item];
contactsArrayList.get(clickedItemIndex).setSelectedMobileNumber(mobileNumberSelected);
// levelDialog.dismiss();
}
});
builder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// Toast.makeText(ContactsActivity.this, "You clicked yes button", Toast.LENGTH_LONG).show();
}
});
levelDialog = builder.create();
levelDialog.show();
}
break;
}
}
}
protected void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
// Save list state
mListState = mLayoutManager.onSaveInstanceState();
state.putParcelable(LIST_STATE_KEY, mListState);
}
protected void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
// Retrieve list state and list/item positions
if (state != null)
mListState = state.getParcelable(LIST_STATE_KEY);
}
#Override
protected void onResume() {
super.onResume();
if (!mCalledFromOncreate) {
contactsArrayList.clear();
launchConacts();
mAdapter.notifyDataSetChanged();
Log.e("Inside", "onResume after clear");
}
if (mListState != null) {
mLayoutManager.onRestoreInstanceState(mListState);
}
}
void launchConacts() {
//Cursor pho = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE NOCASE ASC");
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE NOCASE ASC");
Log.i("Size is "," "+phones.getCount());
if (phones != null && (phones.getCount() > 0)) {
phones.moveToFirst();
phones.move(0);
for (int i = 0; i < phones.getCount(); i++) {
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumberStr = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
try {
final PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
PhoneNumber phoneNumber = phoneNumberUtil.parse(phoneNumberStr, Locale.getDefault().getCountry());
PhoneNumberUtil.PhoneNumberType phoneNumberType = phoneNumberUtil.getNumberType(phoneNumber);
if (phoneNumberType == PhoneNumberType.MOBILE) {
if (name.equals(contactName)) {
phoneNumberStr = phoneNumberStr.replaceAll(" ", "");
if (phoneNumberStr.contains(mobileNumber)) {
} else {
mobileNumber = String.valueOf(phoneNumber.getNationalNumber());
if (!tempList.contains(mobileNumber)) {
// Log.e("phone: ", " " + phoneNumber);
contactsObject.setMobileNumber(mobileNumber);
tempList.add(mobileNumber);
}
}
} else {
if (contactsObject != null) {
contactsArrayList.add(contactsObject);
Log.e("object added", contactsObject.getName());
}
contactsObject = new Contacts();
tempList = new ArrayList<String>();
contactName = name;
mobileNumber = String.valueOf(phoneNumber.getNationalNumber());
tempList.add(mobileNumber);
// Log.e("name: ", " " + name);
// Log.e("phone: ", " " + mobileNumber);
contactsObject.setName(name);
contactsObject.setMobileNumber(mobileNumber);
contactsObject.setFlag(mSharedPreferences.getBoolean("checkbox_" + name, false));
contactsObject.setSelectedMobileNumber(mSharedPreferences.getString("selected_mobile_number_for_" + name, mobileNumber));
}
}
} catch (Exception e) {
} finally {
}
if (phones.isLast()) {
contactsArrayList.add(contactsObject);
// Log.e("object added last>>>>>", contactsObject.getName());
}
phones.moveToNext();
}
//phones.close();
}
mRecyclerView = (RecyclerView)
findViewById(R.id.recycler_view_in_contacts);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new
LinearLayoutManager(getApplicationContext());
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new
ContactsAdapter(contactsArrayList, ContactsActivity.this);
mRecyclerView.setAdapter(mAdapter);
if (contactsArrayList.size() == 0)
{
noItem.setVisibility(View.VISIBLE);
}
}
#Override
protected void onPause() {
super.onPause();
mCalledFromOncreate = false;
}
}
Here is what I found which is adding one more item in your list
Try removing:
if (contactsObject != null) {
contactsArrayList.add(contactsObject);
Log.e("object added : ", contactsObject.getName);
}
Hope this helps.
Main goal: android app-messendger for chating with company support.
Task: To impliment timers of waiting response from operator or client in listview.
Trouble: In all listview items rendering one of all timer, and then application is listing some timers for a moment are rendering for correctly result, but when they are overlap.
Visually you can see here: https://drive.google.com/file/d/0B_SjoeZavdZwdXlUQlU3QTVKeG8/view?usp=sharing]1
Code:
public class SessionAdapter extends BaseAdapter {
private static final String TAG = SessionAdapter.class.toString();
List<SessionInterface> sessions = new ArrayList<>();
Context context;
private Message mLastMessage;
private List<ViewHolder> lstHolders;
private Handler mHandler = new Handler();
private Runnable updateRemainingTimeRunnable = new Runnable() {
#Override
public void run() {
synchronized (lstHolders) {
long currentTime = System.currentTimeMillis();
for (ViewHolder holder : lstHolders) {
holder.updateTimeRemaining(currentTime, 0);
}
}
}
};
public SessionAdapter(List<SessionInterface> sessions, Context context) {
this.sessions = sessions;
this.context = context;
lstHolders = new ArrayList<>();
startUpdateTimer();
}
public void updateSessions(List<SessionInterface> sessionInterface) {
this.sessions = sessionInterface;
}
#Override
public int getCount() {
return sessions.size();
}
#Override
public SessionInterface getItem(int position) {
return sessions.get(position);
}
#Override
public long getItemId(int position) {
SessionInterface session = sessions.get(position);
return session.getId();
}
public long getPositionById(long id) {
for (int i = 1; i < sessions.size(); i++) {
long sessionId = getItemId(i);
Log.d(TAG, "getPositionById-i: " + i);
Log.d(TAG, "getPositionById-id: " + id);
Log.d(TAG, "getPositionById-sessionId: " + sessionId);
boolean eq = id == sessionId;
Log.d(TAG, "getPositionById-sessionId==id: " + eq);
if(eq) {
return i;
}
}
return 0;
}
private void startUpdateTimer() {
Timer tmr = new Timer();
tmr.schedule(new TimerTask() {
#Override
public void run() {
mHandler.post(updateRemainingTimeRunnable);
}
}, 1000, 1000);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final SessionInterface session = sessions.get(position);
ViewHolder holder;
mLastMessage = session.getMessages().get(session.getMessages().size() - 1);
if(convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.adapter_sessions, null);
holder.label = (TextView) convertView.findViewById(R.id.label);
holder.sessionTitle = (TextView) convertView.findViewById(R.id.ticket_title);
holder.date = (TextView) convertView.findViewById(R.id.date);
holder.message = (TextView) convertView.findViewById(R.id.comment);
holder.status = (TextView) convertView.findViewById(R.id.status);
holder.chatStatusImage = (ImageView) convertView.findViewById(R.id.ticket_status);
holder.timeRemaining = (TextView) convertView.findViewById(R.id.time_remaining);
convertView.setTag(holder);
synchronized (lstHolders) {
lstHolders.add(holder);
}
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.label.setText("Чат #" + session.getId());
holder.sessionTitle.setText(Helpers.stringLimit(session.getQueue().getName(), 30));
try {
Date jud = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", new Locale("ru")).parse(mLastMessage.getDate());
String targetFormat = new SimpleDateFormat("d MMMM, HH:mm", new Locale("ru")).format(jud);
long milliseconds = jud.getTime();
holder.date.setText(targetFormat);
if(session.getClosedTimeAgo() == null) {
holder.updateTimeRemaining(System.currentTimeMillis(), milliseconds);
holder.timeRemaining.setVisibility(View.VISIBLE);
} else {
holder.timeRemaining.setVisibility(View.GONE);
}
} catch (ParseException e) {
e.printStackTrace();
}
holder.message.setText(Helpers.stringLimit(Helpers.stripLineBreaks(mLastMessage.getText(), " "), 50));
if(session.getIs_closed() == 1) {
holder.setClosed(convertView);
} else {
if(mLastMessage.getSender_type().equals(Constants.CLIENT_TYPE)) {
holder.setClientWaiting(convertView);
} else {
holder.setOperatorWaiting(convertView);
}
}
return convertView;
}
private class ViewHolder {
TextView label;
TextView sessionTitle;
TextView date;
TextView message;
TextView status;
ImageView chatStatusImage;
TextView timeRemaining;
public void updateTimeRemaining(long currentTime, long timeAgo) {
Log.d(TAG, "updateTimeRemaining:\n currentTime - " + currentTime + ";\n timeAgo - " + timeAgo + ";\n timeDiff(currentTime - timeAgo) = " + (currentTime - timeAgo));
Log.d(TAG, "updateTimeRemaining:\n currentTime - " + currentTime + ";\n timeAgo - " + timeAgo + ";\n timeDiff(timeAgo - currentTime) = " + (timeAgo - currentTime));
long timeDiff = currentTime - timeAgo;
if (timeDiff > 0) {
int seconds = (int) (timeDiff / 1000) % 60;
int minutes = (int) ((timeDiff / (1000 * 60)) % 60);
int hours = (int) ((timeDiff / (1000 * 60 * 60)) % 24);
int hourMinutes = hours*60 + minutes;
timeRemaining.setText(hourMinutes + ":" + (seconds < 10 ? "0" + seconds : seconds));
} else {
timeRemaining.setText("Expired!!");
}
}
public void setClosed(View convertView) {
this.status.setText("Закрыто");
this.status.setTextColor(convertView.getResources().getColor(R.color.closedText));
this.chatStatusImage.setImageDrawable(convertView.getResources().getDrawable(R.drawable.chat_status_closed));
}
public void setOperatorWaiting(View convertView) {
this.status.setText("Оператор ожидает ваш ответ");
this.status.setTextColor(convertView.getResources().getColor(R.color.clientColor));
this.timeRemaining.setTextColor(convertView.getResources().getColor(R.color.clientColor));
this.chatStatusImage.setImageDrawable(convertView.getResources().getDrawable(R.drawable.chat_status_client));
}
public void setClientWaiting(View convertView) {
this.status.setText("Ожидается ответ оператора");
this.status.setTextColor(convertView.getResources().getColor(R.color.operatorColor));
this.timeRemaining.setTextColor(convertView.getResources().getColor(R.color.operatorColor));
this.chatStatusImage.setImageDrawable(convertView.getResources().getDrawable(R.drawable.chat_status_operator));
}
}
}
Fooh.. year.. It's was realy not easy..
Here is my resolving.. maybe it will help anobody in future..
import android.content.Context;
import android.os.Handler;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import ru.pinspb.pinsupport.R;
import ru.pinspb.pinsupport.common.Constants;
import ru.pinspb.pinsupport.pojo.Message;
import ru.pinspb.pinsupport.pojo.SessionInterface;
import ru.pinspb.pinsupport.utils.Helpers;
public class SessionAdapter extends RecyclerView.Adapter<SessionAdapter.Holder> {
public interface OnItemClickListener {
void onItemClick(SessionInterface item);
}
private static final String TAG = SessionAdapter.class.toString();
private final OnItemClickListener listener;
List<SessionInterface> sessions = new ArrayList<>();
Context context;
private Message mLastMessage;
private Handler mHandler = new Handler();
public SessionAdapter(List<SessionInterface> sessions, Context context, OnItemClickListener listener) {
this.sessions = sessions;
this.context = context;
this.listener = listener;
}
public void updateSessions(List<SessionInterface> sessionInterface) {
this.sessions = sessionInterface;
}
public int getCount() {
return sessions.size();
}
public SessionInterface getItem(int position) {
return sessions.get(position);
}
#Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_sessions, null);
return new Holder(v);
}
#Override
public void onBindViewHolder(final Holder holder, int position) {
final SessionInterface session = sessions.get(position);
mLastMessage = session.getMessages().get(session.getMessages().size() - 1);
holder.bind(session, listener);
holder.label.setText("Чат #" + session.getId());
holder.sessionTitle.setText(Helpers.stringLimit(session.getQueue().getName(), 30));
try {
SimpleDateFormat ru = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", new Locale("ru"));
ru.setTimeZone(TimeZone.getTimeZone("GMT+03:00"));
Date jud = ru.parse(mLastMessage.getDate());
String targetFormat = new SimpleDateFormat("d MMMM, HH:mm", new Locale("ru")).format(jud);
final long milliseconds = jud.getTime();
holder.date.setText(targetFormat);
if(session.getClosedTimeAgo() == null) {
startUpdateTimer(new Runnable() {
#Override
public void run() {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Europe/Moscow"));
Date currentDate = calendar.getTime();
holder.updateTimeRemaining(currentDate.getTime(), milliseconds);
}
});
// Log.d(TAG, "Sid: " + session.getId() + " ;\nnow: " + System.currentTimeMillis() + ";\n last date: " + mLastMessage.getDate() + "; \nmill: " + milliseconds );
holder.timeRemaining.setVisibility(View.VISIBLE);
} else {
holder.timeRemaining.setVisibility(View.GONE);
}
} catch (ParseException e) {
e.printStackTrace();
}
holder.message.setText(Helpers.stringLimit(Helpers.stripLineBreaks(mLastMessage.getText(), " "), 50));
if(session.getIs_closed() == 1) {
holder.setClosed();
} else {
if(mLastMessage.getSender_type().equals(Constants.CLIENT_TYPE)) {
holder.setClientWaiting();
} else {
holder.setOperatorWaiting();
}
}
}
#Override
public long getItemId(int position) {
SessionInterface session = sessions.get(position);
return session.getId();
}
#Override
public int getItemCount() {
return sessions.size();
}
public long getPositionById(long id) {
for (int i = 1; i < sessions.size(); i++) {
long sessionId = getItemId(i);
boolean eq = id == sessionId;
if(eq) {
return i;
}
}
return 0;
}
private void startUpdateTimer(final Runnable runnable) {
Timer tmr = new Timer();
tmr.schedule(new TimerTask() {
#Override
public void run() {
mHandler.post(runnable);
}
}, 1000, 1000);
}
public static class Holder extends RecyclerView.ViewHolder {
TextView label;
TextView sessionTitle;
TextView date;
TextView message;
TextView status;
ImageView chatStatusImage;
TextView timeRemaining;
public Holder(View itemView) {
super(itemView);
this.label = (TextView) itemView.findViewById(R.id.label);
this.sessionTitle = (TextView) itemView.findViewById(R.id.ticket_title);
this.date = (TextView) itemView.findViewById(R.id.date);
this.message = (TextView) itemView.findViewById(R.id.comment);
this.status = (TextView) itemView.findViewById(R.id.status);
this.chatStatusImage = (ImageView) itemView.findViewById(R.id.ticket_status);
this.timeRemaining = (TextView) itemView.findViewById(R.id.time_remaining);
}
public void updateTimeRemaining(long currentTime, long timeAgo) {
// Log.d(TAG, "updateTimeRemaining:\n currentTime - " + currentTime + ";\n timeAgo - " + timeAgo + ";\n timeDiff(currentTime - timeAgo) = " + (currentTime - timeAgo));
// Log.d(TAG, "updateTimeRemaining:\n currentTime - " + currentTime + ";\n timeAgo - " + timeAgo + ";\n timeDiff(timeAgo - currentTime) = " + (timeAgo - currentTime));
long timeDiff = currentTime - timeAgo;
long seconds = TimeUnit.MILLISECONDS.toSeconds(timeDiff) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(timeDiff));
String time = String.format("%d:%s",
TimeUnit.MILLISECONDS.toMinutes(timeDiff),
seconds < 10 ? seconds + "0" : String.valueOf(seconds)
);
timeRemaining.setText(time);
}
public void setClosed() {
this.status.setText("closed");
this.status.setTextColor(itemView.getResources().getColor(R.color.closedText));
this.chatStatusImage.setImageDrawable(itemView.getResources().getDrawable(R.drawable.chat_status_closed));
}
public void setOperatorWaiting() {
this.status.setText("some text");
this.status.setTextColor(itemView.getResources().getColor(R.color.clientColor));
this.timeRemaining.setTextColor(itemView.getResources().getColor(R.color.clientColor));
this.chatStatusImage.setImageDrawable(itemView.getResources().getDrawable(R.drawable.chat_status_client));
}
public void setClientWaiting() {
this.status.setText("some text");
this.status.setTextColor(itemView.getResources().getColor(R.color.operatorColor));
this.timeRemaining.setTextColor(itemView.getResources().getColor(R.color.operatorColor));
this.chatStatusImage.setImageDrawable(itemView.getResources().getDrawable(R.drawable.chat_status_operator));
}
public void bind(final SessionInterface item, final OnItemClickListener listener) {
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onItemClick(item);
}
});
}
}
}
I am creating calendar which contains events and I want to show total no of events on particular date. I am using
CalendarAdapter.java class. For showing total no. of events count (like notification bubble) on date I am using
Badge.java class. Now problem is that badge is apply on Calendars dates which current month is showing first,
after changing month then that badge is not remove from next month calendar.
Calendar Adapter:
package vyClean.wemecalendar.adapters;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;
import vyClean.wemecalendar.activity.Event1;
import vyClean.wemecalendar.util.BadgeView;
import vyClean.wemecalendar.util.BadgeView1;
import vyClean.wemecalendar.util.CalendarEvent;
import vyClean.wemecalendar.R;
import vyClean.wemecalendar.util.ToastMessage;
public class CalendarAdapter extends BaseAdapter {
private Context context;
private java.util.Calendar month;
public GregorianCalendar pmonth;
/*-----------calendar instance for previous month for getting complete view-------------------*/
public GregorianCalendar pmonthmaxset;
private GregorianCalendar selectedDate;
int firstDay;
int maxWeeknumber;
int maxP;
int calMaxP;
int mnthlength;
String itemvalue, curentDateString;
DateFormat df;
public static TextView textno;
RelativeLayout cal_item_ll;
private ArrayList<String> items;
public static List<String> day_string;
private View previousView;
private View getView;
public ArrayList<CalendarEvent> event_calendar_arr;
public CalendarAdapter(Context context, GregorianCalendar monthCalendar, ArrayList<CalendarEvent> event_calendar_arr) {
this.event_calendar_arr = event_calendar_arr;
CalendarAdapter.day_string = new ArrayList<>();
Locale.setDefault(Locale.getDefault());
month = monthCalendar;
selectedDate = (GregorianCalendar) monthCalendar.clone();
this.context = context;
month.set(GregorianCalendar.DAY_OF_MONTH, 1);
this.items = new ArrayList<>();
df = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
curentDateString = df.format(selectedDate.getTime());
refreshDays();
}
public int getCount() {
return day_string.size();
}
public Object getItem(int position) {
return day_string.get(position);
}
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) {
getView = convertView;
TextView dayView;
if (convertView == null) { // if it's not recycled, initialize some attributes
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
getView = vi.inflate(R.layout.cal_item, parent, false);
cal_item_ll = (RelativeLayout) getView.findViewById(R.id.cal_item_ll);
//textno = (TextView) getView.findViewById(R.id.textno);
}
dayView = (TextView) getView.findViewById(R.id.date);
String[] separatedTime = day_string.get(position).split("-");
String gridvalue = separatedTime[2].replaceFirst("^0*", "");
if ((Integer.parseInt(gridvalue) > 1) && (position < firstDay)) {
dayView.setTextColor(Color.GRAY);
dayView.setClickable(false);
dayView.setFocusable(false);
} else if ((Integer.parseInt(gridvalue) < 7) && (position > 28)) {
dayView.setTextColor(Color.GRAY);
dayView.setClickable(false);
dayView.setFocusable(false);
} else {
// setting curent month's days in blue color.
dayView.setTextColor(Color.parseColor("#ff69b4"));
}
if (day_string.get(position).equals(curentDateString)) {
getView.setBackgroundColor(Color.CYAN);
} else {
getView.setBackgroundColor(Color.WHITE);
}
dayView.setText(gridvalue);
// create date string for comparison
String date = day_string.get(position);
if (date.length() == 1) {
date = "0" + date;
}
String monthStr = "" + (month.get(GregorianCalendar.MONTH) + 1);
if (monthStr.length() == 1) {
monthStr = "0" + monthStr;
}
int len = CalendarEvent.event_calendar_arr.size();
HashSet<String> eventListSet1 = new HashSet<>();
int flag = 0;
for (int j = 0; j < len; j++) {
//textno.setTextColor(Color.WHITE);
CalendarEvent cal_event = CalendarEvent.event_calendar_arr.get(j);
if (day_string.get(position).equals(cal_event.getEventFromDate())) {
eventListSet1.add(cal_event.getEventCateId());
flag = 1;
}
}
if (flag == 1) {
setEventView(getView, position, dayView, eventListSet1);
/*----------call badgeview here--------*/
/*----------call badgeview on linear layout (cal_item_ll) which is inside getview--------*/
BadgeView badge = new BadgeView(context, cal_item_ll);
badge.setText("1");
badge.show();
}
System.out.println("eventListSet1:" + eventListSet1);
return getView;
}
public View setSelected(View view, int pos) {
if (previousView != null) {
// previousView.setBackgroundColor(Color.CYAN);
previousView.setBackgroundColor(Color.WHITE);
}
view = previousView;
// view.setBackgroundColor(Color.CYAN);
int len = day_string.size();
if (len > pos) {
if (day_string.get(pos).equals(curentDateString)) {
} else {
previousView = view;
}
}
return view;
}
public void refreshDays() {
// clear items
items.clear();
day_string.clear();
Locale.setDefault(Locale.getDefault());
pmonth = (GregorianCalendar) month.clone();
// month start day. ie; sun, mon, etc
firstDay = month.get(GregorianCalendar.DAY_OF_WEEK);
// finding number of weeks in current month.
maxWeeknumber = month.getActualMaximum(GregorianCalendar.WEEK_OF_MONTH);
// allocating maximum row number for the gridview.
mnthlength = maxWeeknumber * 7;
maxP = getMaxP(); // previous month maximum day 31,30....
calMaxP = maxP - (firstDay - 1);// calendar offday starting 24,25 ...
//Calendar instance for getting a complete gridview including the three month's (previous,current,next) dates.
pmonthmaxset = (GregorianCalendar) pmonth.clone();
//setting the start date as previous month's required date.
pmonthmaxset.set(GregorianCalendar.DAY_OF_MONTH, calMaxP + 1);
// filling calendar gridview.
for (int n = 0; n < mnthlength; n++) {
itemvalue = df.format(pmonthmaxset.getTime());
pmonthmaxset.add(GregorianCalendar.DATE, 1);
System.out.println(" 214 itemvale :" + itemvalue);
day_string.add(itemvalue);
}
}
private int getMaxP() {
int maxP;
if (month.get(GregorianCalendar.MONTH) == month
.getActualMinimum(GregorianCalendar.MONTH)) {
pmonth.set((month.get(GregorianCalendar.YEAR) - 1),
month.getActualMaximum(GregorianCalendar.MONTH), 1);
} else {
pmonth.set(GregorianCalendar.MONTH,
month.get(GregorianCalendar.MONTH) - 1);
}
maxP = pmonth.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
return maxP;
}
public void setEventView(View v, int pos, TextView txt, HashSet<String> eventListSet1) {
ArrayList<String> eventList = new ArrayList<>();
int len = CalendarEvent.event_calendar_arr.size();
for (int i = 0; i < len; i++) {
CalendarEvent cal_event = CalendarEvent.event_calendar_arr.get(i);
int len1 = day_string.size();
if (len1 > pos) {
String category = cal_event.getEventCateId();
HashSet<String> eventListSet = new HashSet<String>();
StringTokenizer stR = new StringTokenizer(category, ",");
while (stR.hasMoreTokens()) {
eventListSet.add(stR.nextToken());
}
ArrayList<String> sortedList = new ArrayList(eventListSet1);
Collections.sort(sortedList);
//System.out.println("sortedList:" + sortedList);
StringBuffer CategoryNew = new StringBuffer();
Iterator<String> itr = sortedList.iterator();
while (itr.hasNext()) {
CategoryNew.append(itr.next() + ",");
}
eventList.add(category);
switch (CategoryNew.toString()) {
/* ----------only one category ----------*/
case "1,":
v.setBackgroundResource(R.drawable.gs);
break;
case "2,":
v.setBackgroundResource(R.drawable.se);
break;
case "3,":
v.setBackgroundResource(R.drawable.ge);
break;
case "4,":
v.setBackgroundResource(R.drawable.tuce);
break;
/*----------two category----------*/
case "1,2,":
v.setBackgroundResource(R.drawable.gsse);
break;
case "1,3,":
v.setBackgroundResource(R.drawable.gsge);
break;
case "1,4,":
v.setBackgroundResource(R.drawable.gstuce);
break;
case "2,3,":
v.setBackgroundResource(R.drawable.sege);
break;
case "2,4,":
v.setBackgroundResource(R.drawable.setuce);
break;
case "3,4,":
v.setBackgroundResource(R.drawable.getuce);
break;
/*----------three category----------*/
case "1,2,3,":
v.setBackgroundResource(R.drawable.gssege);
break;
case "1,3,4,":
v.setBackgroundResource(R.drawable.gsgetuce);
break;
case "1,2,4,":
v.setBackgroundResource(R.drawable.gssetuce);
break;
case "2,3,4,":
v.setBackgroundResource(R.drawable.gesetuce);
break;
/*----------four category----------*/
case "1,2,3,4,":
v.setBackgroundResource(R.drawable.gssegetuce);
default:
System.out.println("Invalid event");
break;
}
/*BadgeView1 badge = new BadgeView1(context, cal_item_ll);
badge.setText("1");
badge.show();*/
txt.setTextColor(Color.BLUE);
}
}
}
public void getPositionList(String date, final Activity act) {
final String TAG_EVENT_NAME = "event_name";
final String TAG_EVENT_DESC = "event_desc";
final String TAG_EVENT_FROM_DATE = "event_from_date";
final String TAG_EVENT_TO_DATE = "event_to_date";
final String TAG_EVENT_TIMING = "event_timing";
final String TAG_EVENT_PLACE = "event_place";
final String TAG_EVENT_CATE_ID = "event_cate_id";
String event_name, event_desc, event_from_date;
String event_to_date, event_timing, event_place, event_cate_id;
ArrayList<HashMap<String, String>> event = new ArrayList<>();
int len = CalendarEvent.event_calendar_arr.size();
for (int i = 0; i < len; i++) {
CalendarEvent cal_event = CalendarEvent.event_calendar_arr.get(i);
event_name = cal_event.getEventName();
event_desc = cal_event.getEventDesc();
event_from_date = cal_event.getEventFromDate();
event_to_date = cal_event.getEventToDate();
event_timing = cal_event.getEventTiming();
event_place = cal_event.getEventPlace();
event_cate_id = cal_event.getEventCateId();
if (date.equals(event_from_date)) {
HashMap<String, String> map = new HashMap<>();
map.put(TAG_EVENT_NAME, event_name);
map.put(TAG_EVENT_DESC, event_desc);
map.put(TAG_EVENT_FROM_DATE, event_from_date);
map.put(TAG_EVENT_TO_DATE, event_to_date);
map.put(TAG_EVENT_TIMING, event_timing);
map.put(TAG_EVENT_PLACE, event_place);
if (event_cate_id.equals(1)) {
map.put(TAG_EVENT_CATE_ID, "General Science");
}
if (event_cate_id.equals(2)) {
map.put(TAG_EVENT_CATE_ID, "Scientific Exhibition");
}
if (event_cate_id.equals(3)) {
map.put(TAG_EVENT_CATE_ID, "General Events");
}
if (event_cate_id.equals(4)) {
map.put(TAG_EVENT_CATE_ID, "Tuce Clubs");
}
if (event_cate_id.equals("")) {
map.put(TAG_EVENT_CATE_ID, "");
}
event.add(map);
}
}
if (event.size() > 0) {
Bundle b = new Bundle();
b.putSerializable("EVENT_LIST", event);
Intent in = new Intent(context, Event1.class);
in.putExtras(b);
context.startActivity(in);
} else {
ToastMessage.toastMessage(context, "On this date there is no event");
}
}
BadgeView.class -
package vyClean.wemecalendar.util;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewParent;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
public class BadgeView extends TextView {
private Context context;
protected View target;
private ShapeDrawable badgeBg;
public BadgeView(Context context, View target) {
this(context, null, android.R.attr.textViewStyle, target);
}
public BadgeView(Context context, AttributeSet attrs, int defStyle, View target) {
super(context, attrs, defStyle);
init(context, target);
}
private void init(Context context, View target) {
try {
this.context = context;
this.target = target;
//apply defaults
setTypeface(Typeface.DEFAULT_BOLD);
setPadding(7, 0, 7, 0);
setTextColor(Color.WHITE);
if (this.target != null) {
applyTo(this.target);
} else {
show();
}
} catch (StackOverflowError e) {
e.printStackTrace();
}
}
private void applyTo(View target) {
try {
ViewGroup.LayoutParams lp = target.getLayoutParams();
//ViewParent parent = target.getParent();
FrameLayout container = new FrameLayout(context);
// TODO verify that parent is indeed a ViewGroup
ViewGroup group = (ViewGroup) target;
int index = group.indexOfChild(target);
group.removeView(target);
group.addView(container, index,lp);
container.addView(target);
container.addView(this);
group.invalidate();
} catch (Exception e) {
e.printStackTrace();
}
}
public void show() {
try {
if (getBackground() == null) {
if (badgeBg == null) {
badgeBg = getDefaultBackground();
}
setBackgroundDrawable(badgeBg);
}
applyLayoutParams();
} catch (StackOverflowError e) {
e.printStackTrace();
}
}
private ShapeDrawable getDefaultBackground() {
ShapeDrawable drawable = null;
try {
float[] outerR = new float[]{20, 20, 20, 20, 20, 20, 20, 20};
RoundRectShape rr = new RoundRectShape(outerR, null, null);
drawable = new ShapeDrawable(rr);
drawable.getPaint().setColor(Color.BLACK);
} catch (StackOverflowError e) {
e.printStackTrace();
}
return drawable;
}
private void applyLayoutParams() {
try {
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.RIGHT | Gravity.TOP;
setLayoutParams(lp);
} catch (StackOverflowError e) {
e.printStackTrace();
}
}
}
I have a custom adapter for recyclerview using json webservices. I had to parse the url one by one and show cardview using onscrolllistener(). My question is when I pressed the back button and after I open in recent app (that time onResume called) it will show only which url called at the time of onPause called. So how can I refresh the listview when I call onResume.
Thanks in Advance,
Here my code synepet..
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private GridLayoutManager mGridManager;
private ProgressBar mProgressBar;
private static String url = "https://www.googleapis.com/youtube/v3/playlists?part=snippet&channelId=UCGyZswzm4G-wEfRQHgMSAuw&maxResults=50&key=AIzaSyCi0ApXYk08YpzyEO8jYJanaud-Epti6ks&pageToken=CDIQAQ";
JSONArray contacts = null;
private String mNextToken;
JSONObject jsonObj;
private boolean loading = true;
int visibleItemCount, totalItemCount, pastVisiblesItems;
private List<PlayListItem> mContactList = new ArrayList<PlayListItem>();
private PlayListItem mContact;
private Bundle mbundle;
String name2 = "Arasu";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
// Calling async task to get json
new GetContacts().execute();
mAdapter = new CardAdapter(MainActivity.this, mContactList);
mRecyclerView.setAdapter(mAdapter);
getScreenOrientation();
}
#Override
public void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
System.out.println("Size2---->" + mContactList.size());
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
mProgressBar.setVisibility(View.VISIBLE);
mProgressBar.setMax(100);
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonArray = sh.makeServiceCall(url, ServiceHandler.GET);
//Log.d("Response: ", "> " + jsonArray);
if (jsonArray != null) {
try {
jsonObj = new JSONObject(jsonArray);
if (jsonObj.has("nextPageToken")) {
loading = true;
mNextToken = jsonObj.getString("nextPageToken");
} else {
loading = false;
}
// Getting JSON Array node
contacts = jsonObj.getJSONArray("items");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String title = c.getJSONObject("snippet").getString("title");
String time = c.getJSONObject("snippet").getString("publishedAt");
String playlist_id = c.get("id").toString();
// Find Screen size and set the Image for this size
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
double x = Math.pow(dm.widthPixels / dm.xdpi, 2);
double y = Math.pow(dm.heightPixels / dm.ydpi, 2);
double screenInches = Math.sqrt(x + y);
int inch = (int) Math.round(screenInches);
String image = null;
try {
if (inch <= 4) {
image = c.getJSONObject("snippet").getJSONObject("thumbnails").getJSONObject("medium").getString("url");
} else if (inch > 4 && inch <= 6) {
image = c.getJSONObject("snippet").getJSONObject("thumbnails").getJSONObject("medium").getString("url");
} else if (inch > 6 && inch <= 10) {
image = c.getJSONObject("snippet").getJSONObject("thumbnails").getJSONObject("medium").getString("url");
} else {
image = c.getJSONObject("snippet").getJSONObject("thumbnails").getJSONObject("default").getString("url");
}
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
mContact = new PlayListItem();
mContact.setmTitle(title);
mContact.setmID(playlist_id);
mContact.setmTime(time);
mContact.setmThumbnailURL(image);
mContact.setmNextToken(mNextToken);
mContactList.add(mContact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (mProgressBar.isShown())
mProgressBar.setVisibility(ProgressBar.GONE);
mAdapter.notifyDataSetChanged();
mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
visibleItemCount = mGridManager.getChildCount();
totalItemCount = mGridManager.getItemCount();
pastVisiblesItems = mGridManager.findFirstVisibleItemPosition();
if (loading) {
if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) {
Log.v("...", "Last Item Wow !");
if (jsonObj.has("nextPageToken")) {
url = "https://www.googleapis.com/youtube/v3/playlists?part=snippet&channelId=UCGyZswzm4G-wEfRQHgMSAuw&maxResults=50&key=AIzaSyCi0ApXYk08YpzyEO8jYJanaud-Epti6ks&pageToken=" + mNextToken;
System.out.println("url--->" + url);
new GetContacts().execute();
} else {
url = "https://www.googleapis.com/youtube/v3/playlists?part=snippet&channelId=UCGyZswzm4G-wEfRQHgMSAuw&maxResults=50&key=AIzaSyCi0ApXYk08YpzyEO8jYJanaud-Epti6ks&pageToken=" + mNextToken;
System.out.println("url----else--->" + url);
new GetContacts().execute();
}
loading = false;
}
}
}
});
}
}
}
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
private List<PlayListItem> mItems;
private Activity activity;
public ImageLoader imageLoader;
public CardAdapter(Activity activity, List<PlayListItem> items) {
this.activity = activity;
this.mItems = items;
imageLoader = new ImageLoader(activity.getApplicationContext());
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.recycler_outer_playlist_cardview, viewGroup, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, final int i) {
System.out.println("Title Value is----------->"+mItems.get(0));
PlayListItem nature = mItems.get(i);
Log.d("Title Value is","----------->"+nature.getmTitle());
viewHolder.tvTitle.setText(nature.getmTitle());
final String playListID = nature.getmID();
final String thumnailsURL = nature.getmThumbnailURL();
final Calendar c = Calendar.getInstance();
int cur_year = c.get(Calendar.YEAR);
int cur_month = c.get(Calendar.MONTH) + 1;
int cur_day = c.get(Calendar.DAY_OF_MONTH);
int cur_hour = c.get(Calendar.HOUR_OF_DAY);
int cur_minute = c.get(Calendar.MINUTE);
// Getting updated date from url
String string = nature.getmTime();
String[] parts = string.split("-");
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556
String part3 = parts[2];
String[] part4 = part3.split("T");
String part5 = part4[0];
String part6 = part4[1];
// Toast.makeText(activity, "Given Date is : " + part1 + "/" + part2 + "/" + part3, Toast.LENGTH_LONG).show();
// Log.d("Updated Current Day", part5);
int giv_yr = Integer.parseInt(part1);
int giv_mnt = Integer.parseInt(part2);
int giv_day = Integer.parseInt(part5);
// Difference Two dates
int day_yr = 0, day_mnt = 0, day_day = 0;
if (cur_year >= giv_yr) {
if (cur_year >= giv_yr) {
day_yr = cur_year - giv_yr;
} else {
day_yr = giv_yr - cur_year;
}
if (cur_month >= giv_mnt) {
day_mnt = cur_month - giv_mnt;
} else {
day_mnt = giv_mnt - cur_month;
}
if (cur_day >= giv_day) {
day_day = cur_day - giv_day;
} else {
day_day = giv_day - cur_day;
}
}
String yr = Integer.toString(day_yr);
String mnt = Integer.toString(day_mnt);
String days = Integer.toString(day_day);
if (day_day == 0)
viewHolder.tvTime.setText("Updated Today");
else if (day_day < 7)
viewHolder.tvTime.setText("Updated " + days + " Days ago");
else if (day_day < 30) {
int week = day_day / 7;
String Week = Integer.toString(week);
viewHolder.tvTime.setText("Updated " + Week + " Weeks ago");
} else {
viewHolder.tvTime.setText("Updated " + mnt + " Months ago");
}
//imageLoader.DisplayImage(nature.getmThumbnailURL(), viewHolder.imgThumbnail);
Picasso.with(activity)
.load(nature.getmThumbnailURL())
/*.placeholder(R.drawable.my_thumnail)*/
.into(viewHolder.imgThumbnail);
viewHolder.item_view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(activity, VideoPlayActivity.class);
intent.putExtra("PLAYLIST_ID", playListID);
intent.putExtra("THUMNAIL_URL", thumnailsURL);
v.getContext().startActivity(intent);
}
});
/*System.out.println("URL -------------->"+nature.getmThumbnailURL());
// String img_url = nature.getmThumbnailURL();
try {
URL url = new URL(nature.getmThumbnailURL());
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
System.out.println("Image bmp -------------->"+bmp);
//imageView.setImageBitmap(bmp);
viewHolder.imgThumbnail.setImageBitmap(bmp);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}*/
}
#Override
public int getItemCount() {
return mItems.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public ImageView imgThumbnail;
public TextView tvTitle;
public TextView tvID;
public TextView tvTime;
public View item_view;
public ViewHolder(View itemView) {
super(itemView);
imgThumbnail = (ImageView) itemView.findViewById(R.id.img_thumbnail);
tvTitle = (TextView) itemView.findViewById(R.id.tv_title);
//tvID = (TextView) itemView.findViewById(R.id.tv_id);
tvTime = (TextView) itemView.findViewById(R.id.tv_time);
item_view = itemView;
}
}
}
I made a small mistake declaring String URL as static but it should be final also assign to another String variable. Finally set the adapter and notifyDataSetChanged where placed in onStart().
private final static String URL = "https://www.googleapis.com/youtube/v3/playlists?part=snippet&channelId=UCGyZswzm4G-wEfRQHgMSAuw&maxResults=50&key=AIzaSyCi0ApXYk08YpzyEO8jYJanaud-Epti6ks&pageToken=CDIQAQ";
private String url = URL;
JSONArray contacts = null;
private String mNextToken;
JSONObject jsonObj;
private boolean loading = true;
int visibleItemCount, totalItemCount, pastVisiblesItems;
private List<PlayListItem> mContactList;
private PlayListItem mContact;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
// Calling async task to get json
if (mContactList == null)
mContactList = new ArrayList<PlayListItem>();
System.out.println("onCreate :: Size2---->" + mContactList.size());
}
#Override
protected void onStart() {
super.onStart();
if (mContactList != null)
mContactList.clear();
url = URL;
new GetContacts().execute();
if (mAdapter == null)
mAdapter = new CardAdapter(MainActivity.this, mContactList);
mRecyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
getScreenOrientation();
System.out.println("onStart :: Size2---->" + mContactList.size());
}
#Override
protected void onResume() {
ActivitySwitcher.animationIn(findViewById(R.id.container_first),
getWindowManager());
super.onResume();
System.out.println("onResume :: Size2---->" + mContactList.size());
mAdapter.notifyDataSetChanged();
}