I have list of music that user set time to play. I want to have a button to cancel m count down timer .
I test some way but it doesn't work at all.
here is my code to play and set time to play.
public class Main extends Activity {
public static int hour_device, minute_device;
public static int hour_user, minute_user;
Splash splash;
ListView listView;
Adaptor adaptor;
private MediaPlayer mediaPlayer;
static View lastview = null;
static MyIndexStore indexStore;
List<String> lines1 = new ArrayList<String>();
List<String> lines2 = new ArrayList<String>();
static List<String> array_audio = new ArrayList<String>();
InputStream in;
BufferedReader reader;
String line = "1";
String[] tracks;
String[] names;
String[] infos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
indexStore = new MyIndexStore(getApplicationContext());
setContentView(R.layout.main_activity);
splash = new Splash(this);
splash.set_identity("1");
initiate();
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.a1);
//lastview = null;
listView = (ListView) findViewById(R.id.list);
ReadText1();
names = lines1.toArray(new String[0]);// = {"track one","the seconnd track","a nice track","name name name","the seconnd track","a nice track","name name name"};
ReadText2();
infos = lines2.toArray(new String[0]);
tracks = array_audio.toArray(new String[0]);
adaptor = new Adaptor(getApplicationContext(), tracks, names, infos);
listView.setAdapter(adaptor);
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer arg0) {
if (lastview != null) {
ImageView play = (ImageView) lastview.findViewById(R.id.play_stop);
play.setImageResource(R.drawable.n_btn_play_unselected);
}
}
});
}
private static void initiate() {
Field[] fields = R.raw.class.getFields();
array_audio.clear();
for (int count = 0; count < fields.length; count++) {
array_audio.add("a" + (count + 1));
}
}
private void play(int index) {
mediaPlayer.release();
index++;
String s = "a" + index;
Resources resources = getResources();
final int resourceId = resources.getIdentifier(s, "raw", getPackageName());
try {
mediaPlayer = MediaPlayer.create(this, resourceId);
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onPause() {
mediaPlayer.release();
listView.invalidateViews();
super.onPause();
}
private void ReadText1() {
lines1.clear();
line = "1";
try {
in = this.getAssets().open("names.txt");
reader = new BufferedReader(new InputStreamReader(in));
while (line != null) {
line = reader.readLine();
if (line != null)
lines1.add(line);
else
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void ReadText2() {
lines2.clear();
line = "1";
try {
in = this.getAssets().open("infos.txt");
reader = new BufferedReader(new InputStreamReader(in));
while (line != null) {
line = reader.readLine();
if (line != null)
lines2.add(line);
else
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
public class Adaptor extends ArrayAdapter<String> {
private final Context context;
private final String[] tracks;
private final String[] names;
private final String[] infos;
private HashMap<Integer,String> textMap;
Typeface type_face;
public Adaptor(Context context, String[] tracks, String[] names, String[] infos) {
super(context, R.layout.track, tracks);
this.context = context;
this.tracks = tracks;
this.names = names;
this.infos = infos;
type_face = Typeface.createFromAsset(context.getAssets(), "BTitrBd.ttf");
this.textMap = new HashMap<>();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(R.layout.track, parent, false);
TextView name = (TextView) rowView.findViewById(R.id.track_name);
final TextView time = (TextView) rowView.findViewById(R.id.time);
//populate the textview from map
if(textMap!=null && textMap.get(new Integer(position))!=null){
time.setText(textMap.get(new Integer(position)));
}
name.setText(names[position]);
name.setTypeface(type_face);
name.setTypeface(type_face);
final ImageView ringtone = (ImageView) rowView.findViewById(R.id.ringtone);
if (position == indexStore.getindex())
ringtone.setImageResource(R.drawable.n_btn_ringtone_seted);
final ImageView play = (ImageView) rowView.findViewById(R.id.play_stop);
ringtone.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
LayoutInflater factory = LayoutInflater.from(Main.this);
final View deleteDialogView = factory.inflate(
R.layout.mylayout, null);
final AlertDialog deleteDialog = new AlertDialog.Builder(Main.this).create();
deleteDialog.setView(deleteDialogView);
TextView device_time = (TextView) deleteDialogView.findViewById(R.id.current_time);
Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
hour_device = hour;
minute_device = minute;
device_time.setText(hour_device + ":" + minute_device);
deleteDialogView.findViewById(R.id.set).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TimePicker timePicker = (TimePicker) deleteDialogView.findViewById(R.id.timepicker);
timePicker.setIs24HourView(true);
hour_user = timePicker.getCurrentHour();
minute_user = timePicker.getCurrentMinute();
String time1 = hour_device + ":" + minute_device;
String time2 = hour_user + ":" + minute_user;
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
Date date1 = null;
try {
date1 = format.parse(time1);
} catch (ParseException e) {
e.printStackTrace();
}
Date date2 = null;
try {
date2 = format.parse(time2);
} catch (ParseException e) {
e.printStackTrace();
}
long result = date2.getTime() - date1.getTime();
new CountDownTimer(result, 1000) {
public void onTick(long millisUntilFinished) {
time.setText(("seconds remaining: " + millisUntilFinished / 1000));
//create HashMap<Integer,String> textMap at the constructer of the adapter
//now fill this info int'o it
textMap.put(new Integer(position), "seconds remaining: " + millisUntilFinished / 1000);
//notify about the data change
notifyDataSetChanged();
}
public void onFinish() {
time.setVisibility(View.INVISIBLE);
//create HashMap<Integer,String> textMap at the constructer of the adapter
//now fill this info into it
textMap.put(new Integer(position),null);
//notify about the data change
notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "finish", Toast.LENGTH_LONG).show();
if (rowView != lastview || mediaPlayer == null) {
play(position);
if (lastview != null)
lastview = rowView;
} else {
play.setImageResource(R.drawable.n_btn_play_unselected);
mediaPlayer.release();
lastview = null;
}
}
}.start();
deleteDialog.dismiss();
}
});
deleteDialog.show();
}
});
play.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (rowView != lastview || mediaPlayer == null) {
play(position);
if (lastview != null)
lastview = rowView;
} else {
play.setImageResource(R.drawable.n_btn_play_unselected);
mediaPlayer.release();
lastview = null;
}
}
});
return rowView;
}
}
}
make the count down timer an instance variable;
private CountDownTimer timer;
then delegate your count to this variable:
#Override
public void onClick(View v) {
...
timer = new CountDownTimer(result, 1000) {
...
}
}
now you can stop the timer whenever you want to:
timer.cancel();
Check this code, working Successfull
call class from here
timer = new CounterClass(timeInmilles, 1000);
timer.start();
CounterClass is here
public class CounterClass extends CountDownTimer {
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
}
public void onTick(long millisUntilFinished) {
}
}
use to cancel see below line
timer.cancel()
Related
I make whole video player app but stuck at mediacontroller. I want to show my own mediacontroller with different button, not the default one. It's 4rth day, i'm just trying to make my own mediacontroller but didn't succeed.
I succeed by doing it with surfaceview but i want to use it with videoview.
I try the following code.
public class MyMediaController extends MediaController {
private static final String TAG = "VideoControllerView";
MediaController.MediaPlayerControl mPlayer;
private Context mContext;
private View mAnchor;
private View mRoot;
private ProgressBar mProgress;
private TextView mEndTime, mCurrentTime;
private boolean mShowing;
private boolean mDragging;
private static final int sDefaultTimeout = 3000;
private static final int FADE_OUT = 1;
private static final int SHOW_PROGRESS = 2;
private boolean mUseFastForward;
private boolean mFromXml;
private boolean mListenersSet;
StringBuilder mFormatBuilder;
Formatter mFormatter;
private ImageButton mPauseButton;
private ImageButton mSubtitleButton;
private ImageButton mResizeButton;
private ImageButton mNextButton;
private ImageButton mPrevButton;
private final AccessibilityManager mAccessibilityManager;
public MyMediaController(Context context, AttributeSet attrs) {
super(context, attrs);
mRoot = null;
mContext = context;
mUseFastForward = true;
mFromXml = true;
mAccessibilityManager = (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE);
}
public MyMediaController(Context context, boolean useFastForward) {
super(context, useFastForward);
mUseFastForward = useFastForward;
mAccessibilityManager = (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE);
}
public MyMediaController(Context context) {
this(context, true);
mContext = context;
}
#Override
public void setMediaPlayer(MediaController.MediaPlayerControl player) {
mPlayer = player;
updatePausePlay();
}
#Override
public void setAnchorView(View view) {
mAnchor = view;
FrameLayout.LayoutParams frameParams = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
);
removeAllViews();
View v = makeControllerView();
addView(v, frameParams);
}
protected View makeControllerView() {
LayoutInflater inflate = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mRoot = inflate.inflate(R.layout.media_controller_layout, null);
initControllerView(mRoot);
return mRoot;
}
private void initControllerView(View mRoot) {
mPauseButton = mRoot.findViewById(R.id.pause);
if (mPauseButton != null) {
mPauseButton.requestFocus();
mPauseButton.setOnClickListener(mPauseListener);
}
mResizeButton = mRoot.findViewById(R.id.resize);
if (mResizeButton != null) {
mResizeButton.requestFocus();
mResizeButton.setOnClickListener(mResizeListener);
}
mSubtitleButton = mRoot.findViewById(R.id.subtitle);
if (mSubtitleButton != null)
{
mSubtitleButton.requestFocus();
mSubtitleButton.setOnClickListener(mSubtitleListener);
}
mNextButton = mRoot.findViewById(R.id.next);
if (mNextButton != null ) {
mNextButton.requestFocus();
mNextButton.setOnClickListener(mNextListener);
}
mPrevButton = mRoot.findViewById(R.id.prev);
if (mPrevButton != null ) {
mPrevButton.requestFocus();
mPrevButton.setOnClickListener(mPrevListener);
}
mProgress = mRoot.findViewById(R.id.mediacontroller_progress);
if (mProgress != null) {
if (mProgress instanceof SeekBar) {
SeekBar seeker = (SeekBar) mProgress;
seeker.setOnSeekBarChangeListener(mSeekListener);
}
mProgress.setMax(1000);
}
mEndTime = mRoot.findViewById(R.id.time);
mCurrentTime = mRoot.findViewById(R.id.time_current);
mFormatBuilder = new StringBuilder();
mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());
}
public final View.OnClickListener mPauseListener = new OnClickListener() {
#Override
public void onClick(View v) {
doPauseResume();
show(sDefaultTimeout);
}
};
private void doPauseResume() {
if (mPlayer == null) {
return;
}
if (mPlayer.isPlaying()) {
mPlayer.pause();
} else {
mPlayer.start();
}
updatePausePlay();
}
private void updatePausePlay() {
if (mRoot == null || mPauseButton == null)
return;
if (mPlayer.isPlaying())
mPauseButton.setImageResource(R.drawable.ic_pause);
else
mPauseButton.setImageResource(R.drawable.ic_play);
}
public final View.OnClickListener mResizeListener = new OnClickListener() {
#Override
public void onClick(View v) {
//Todo
Toast.makeText(mContext,"Resize is clicked",Toast.LENGTH_SHORT).show();
}
};
public final View.OnClickListener mNextListener = new OnClickListener() {
#Override
public void onClick(View v) {
//Todo
Toast.makeText(mContext,"NextBtn is clicked",Toast.LENGTH_SHORT).show();
}
};
public final View.OnClickListener mPrevListener = new OnClickListener() {
#Override
public void onClick(View v) {
//Todo
Toast.makeText(mContext,"PreviousBtn is clicked",Toast.LENGTH_SHORT).show();
}
};
public final View.OnClickListener mSubtitleListener = new OnClickListener() {
#Override
public void onClick(View v) {
//Todo
Toast.makeText(mContext,"subtitleBtn is clicked",Toast.LENGTH_SHORT).show();
}
};
private final SeekBar.OnSeekBarChangeListener mSeekListener = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStartTrackingTouch(SeekBar bar) {
show(3600000);
mDragging = true;
// By removing these pending progress messages we make sure
// that a) we won't update the progress while the user adjusts
// the seekbar and b) once the user is done dragging the thumb
// we will post one of these messages to the queue again and
// this ensures that there will be exactly one message queued up.
removeCallbacks(mShowProgress);
}
#Override
public void onProgressChanged(SeekBar bar, int progress, boolean fromuser) {
if (!fromuser) {
// We're not interested in programmatically generated changes to
// the progress bar's position.
return;
}
long duration = mPlayer.getDuration();
long newposition = (duration * progress) / 1000L;
mPlayer.seekTo( (int) newposition);
if (mCurrentTime != null)
mCurrentTime.setText(stringForTime( (int) newposition));
}
#Override
public void onStopTrackingTouch(SeekBar bar) {
mDragging = false;
setProgress();
updatePausePlay();
show(sDefaultTimeout);
// Ensure that progress is properly updated in the future,
// the call to show() does not guarantee this because it is a
// no-op if we are already showing.
post(mShowProgress);
}
};
private int setProgress() {
if (mPlayer == null || mDragging) {
return 0;
}
int position = mPlayer.getCurrentPosition();
int duration = mPlayer.getDuration();
if (mProgress != null) {
if (duration > 0) {
// use long to avoid overflow
long pos = 1000L * position / duration;
mProgress.setProgress( (int) pos);
}
int percent = mPlayer.getBufferPercentage();
mProgress.setSecondaryProgress(percent * 10);
}
if (mEndTime != null)
mEndTime.setText(stringForTime(duration));
if (mCurrentTime != null)
mCurrentTime.setText(stringForTime(position));
return position;
}
private String stringForTime(int timeMs) {
int totalSeconds = timeMs / 1000;
int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
int hours = totalSeconds / 3600;
mFormatBuilder.setLength(0);
if (hours > 0) {
return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
} else {
return mFormatter.format("%02d:%02d", minutes, seconds).toString();
}
}
private final Runnable mShowProgress = new Runnable() {
#Override
public void run() {
int pos = setProgress();
if (!mDragging && mShowing && mPlayer.isPlaying()) {
postDelayed(mShowProgress, 1000 - (pos % 1000));
}
}
};
#Override
public void show(int timeout) {
if (!mShowing && mAnchor != null) {
setProgress();
if (mPauseButton != null) {
mPauseButton.requestFocus();
}
FrameLayout.LayoutParams tlp = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
Gravity.BOTTOM
);
addView(this, tlp);
mShowing = true;
}
updatePausePlay();
// cause the progress bar to be updated even if mShowing
// was already true. This happens, for example, if we're
// paused with the progress bar showing the user hits play.
post(mShowProgress);
if (timeout != 0 && !mAccessibilityManager.isTouchExplorationEnabled()) {
removeCallbacks(mFadeOut);
postDelayed(mFadeOut, timeout);
}
}
#Override
public boolean isShowing() {
return mShowing;
}
/**
* Remove the controller from the screen.
*/
#Override
public void hide() {
if (mAnchor == null)
return;
if (mShowing) {
try {
removeCallbacks(mShowProgress);
removeView(this);
} catch (IllegalArgumentException ex) {
Log.w("MediaController", "already removed");
}
mShowing = false;
}
}
private final Runnable mFadeOut = new Runnable() {
#Override
public void run() {
hide();
}
};
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
show(0);
break;
case MotionEvent.ACTION_UP:
show(sDefaultTimeout);
break;
case MotionEvent.ACTION_CANCEL:
hide();
break;
default:
break;
}
return true;
}
}
Plz someone suggest my the right way to do it. I realy need help.
I am making an android app that shows weather using OWM 5day 3hour forecast API, The ui consists of EditText to input a city name, a button to initiate the call process, a listview that will display 5 entries (five days) and each day entry includes another listview that displays decription and temperature for every 3 hours in a day,
I am able to see the listview for days but cannot see the nested listview for the hourly data. My classes include : MainActivity, WeatherAdapter to show 3hourly weather, DayAdapter to show day entries, and JsonToWeather data class that extracts data out of the Json response and make an Arraylist of data for only one particular day. I tried to log the error and highlighted the error position by a comment.
MainActivity :
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private String responseJSON = null;
ListView listView;
ArrayList<WeatherData> weatherDataArrayList;
WeatherAdapter weatherAdapter = null;
EditText cityName;
String city = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.dayList);
cityName = (EditText) findViewById(R.id.cityName);
Button load = (Button) findViewById(R.id.loadButton);
load.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
city = cityName.getText().toString();
Log.d(TAG, "onClick: city is : " + city);
if(city == null){
Toast toast = null;
toast.makeText(MainActivity.this,"Please Enter a city before continuing",Toast.LENGTH_LONG);
toast.show();
} else {
String url = "http://api.openweathermap.org/data/2.5/forecast?q=" + (city.toLowerCase()) + "&units=metric&appid=8b10912e19fde267f36f6cb785ee7efd";
Log.d(TAG, "onCreate: staring download task");
DownloadJSON downloadJSON = new DownloadJSON();
downloadJSON.execute(url);
Log.d(TAG, "onCreate: after downloadtask");
}
}
});
if(weatherDataArrayList == null){
Log.d(TAG, "onCreate: ArrayList is Still null");
}
}
private class DownloadJSON extends AsyncTask<String, Void, String>{
private static final String TAG = "DownloadJSON";
private String downloadJSON(String url){
StringBuilder jsonResult = new StringBuilder();
try{
URL apiURL = new URL(url);
HttpURLConnection connection = (HttpURLConnection) apiURL.openConnection();
int responseCode = connection.getResponseCode();
Log.d(TAG, "downloadJSON: Response code "+ responseCode);
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
int charReader;
char[] inputBuffer = new char[500];
while(true){
charReader = reader.read(inputBuffer);
if(charReader < 0){
break;
}
if(charReader > 0){
jsonResult.append(String.copyValueOf(inputBuffer, 0, charReader));
}
}
reader.close();
return jsonResult.toString();
}catch (MalformedURLException e){
Log.e(TAG, "downloadJSON: URL is Invalid");
}catch (IOException e){
Log.e(TAG, "downloadJSON: IO Error");
}
return null;
}
#Override
protected String doInBackground(String... strings) {
Log.d(TAG, "doInBackground: url is : " + strings[0]);
String jsonResponse = downloadJSON(strings[0]);
if(jsonResponse == null){
Log.e(TAG, "doInBackground: Error downloading");
}
return jsonResponse;
}
#Override
protected void onPostExecute(String jsonResponse) {
super.onPostExecute(jsonResponse);
Log.d(TAG, "onPostExecute: json received is : " + jsonResponse);
if(jsonResponse != null){
JsonToWeatherData jtwd = new JsonToWeatherData();
weatherDataArrayList = jtwd.extractor(jsonResponse);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
String date1 = simpleDateFormat.format(calendar.getTime());
calendar.add(Calendar.DATE,1);
String date2 = simpleDateFormat.format(calendar.getTime());
calendar.add(Calendar.DATE,1);
String date3 = simpleDateFormat.format(calendar.getTime());
calendar.add(Calendar.DATE,1);
String date4 = simpleDateFormat.format(calendar.getTime());
calendar.add(Calendar.DATE,1);
String date5 = simpleDateFormat.format(calendar.getTime());
ArrayList<String> days = new ArrayList<>();
days.add(date1);
days.add(date2);
days.add(date3);
days.add(date4);
days.add(date5);
DayAdapter day = new DayAdapter(MainActivity.this,R.layout.layout_day_card,days,weatherDataArrayList);
listView.setAdapter(day);
} else {
Log.d(TAG, "onPostExecute: no json recieved, city is Wrong");
Toast toast = Toast.makeText(MainActivity.this,"Please provide a valid city!",Toast.LENGTH_LONG);
toast.show();
}
}
}
}
WeatherAdapter :
public class WeatherAdapter extends ArrayAdapter<WeatherData> {
private static final String TAG = "WeatherAdapter";
private final int layoutResourceID;
private LayoutInflater layoutInflater;
private ArrayList<WeatherData> block;
public WeatherAdapter(#NonNull Context context, int resource, ArrayList<WeatherData> block) {
super(context, resource, block);
this.layoutResourceID = resource;
this.block = block;
this.layoutInflater = LayoutInflater.from(context);
Log.d(TAG, "WeatherAdapter: called constructor");
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
if(convertView == null){
convertView = layoutInflater.inflate(layoutResourceID,parent,false);
}
Log.d(TAG, "getView: entered");
WeatherData weatherData = block.get(position);
TextView temp = (TextView) convertView.findViewById(R.id.temperature);
temp.setText(weatherData.getTemp());
TextView shortDesc = (TextView) convertView.findViewById(R.id.descrip);
shortDesc.setText(weatherData.getShortDesc());
return convertView;
}
}
DayAdapter :
public class DayAdapter extends ArrayAdapter<String> {
private static final String TAG = "DayAdapter";
private ArrayList<String> dayBlock;
private LayoutInflater layoutInflater;
private int layoutresourceID;
private ArrayList<WeatherData> dayWeather, fullBlock;
private Context context;
JsonToWeatherData json = new JsonToWeatherData();
public DayAdapter(#NonNull Context context, int resource, #NonNull ArrayList<String> dayBlock, ArrayList<WeatherData> weatherBlock) {
super(context, resource, dayBlock);
this.context = context;
this.dayBlock = dayBlock;
this.fullBlock = weatherBlock;
layoutInflater = LayoutInflater.from(context);
this.layoutresourceID = resource;
if(fullBlock == null){
Log.e(TAG, "DayAdapter: full block is null");
}
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
if (convertView == null){
convertView = layoutInflater.inflate(layoutresourceID,parent,false);
}
TextView date = (TextView) convertView.findViewById(R.id.date);
TextView minTempFoDay = (TextView) convertView.findViewById(R.id.minTempOfDay);
TextView maxTempFoDay = (TextView) convertView.findViewById(R.id.maxTempOfDay);
ListView weatherHolderListView = (ListView) convertView.findViewById(R.id.wHoldLV);
String dateString = dayBlock.get(position);
dayWeather = json.extractByDate(fullBlock,dateString);
if(fullBlock == null){
Log.d(TAG, "getView: fullblock is null");
}
if(dayWeather == null){
Log.d(TAG, "getView: dayweather array is null");
} else {
Log.d(TAG, "getView: dayweather is not null");
}
String test = dayWeather.get(position).getTemp(); // error occured here
Log.d(TAG, "getView: test string : " + test);
date.setText(dateString);
DecimalFormat df = new DecimalFormat(".##");
float mint = 500, maxt = 0;
String mint1 = "", maxt1 = "";
for(WeatherData data : dayWeather){
if(mint > Float.parseFloat(data.getMinTemp())){
mint = Float.parseFloat(data.getMinTemp());
mint1 = df.format(mint);
Log.d(TAG, "getView: mint : " + mint);
}
if (maxt > Float.parseFloat(data.getMaxTemp())){
maxt = Float.parseFloat(data.getMaxTemp());
maxt1 = df.format(maxt);
}
}
minTempFoDay.setText(mint1);
maxTempFoDay.setText(maxt1);
WeatherAdapter weatherAdapter = new WeatherAdapter(context,R.layout.weather_holder,dayWeather);
weatherHolderListView.setAdapter(weatherAdapter);
return convertView;
}
}
JsonToWeatherData:
public class JsonToWeatherData {
private static final String TAG = "JsonToWeatherData";
public ArrayList<WeatherData> extractor(String jsonData){
Log.d(TAG, "extractor: in the method");
if(jsonData == null){
return null; // if there is no json data is received
} else {
ArrayList<WeatherData> weatherDataArrayList = new ArrayList<WeatherData>();
Log.d(TAG, "extractor: in the else field");
try{
Log.d(TAG, "extractor: in try block");
JSONObject root = new JSONObject(jsonData);
int count = root.getInt("cnt");
JSONArray wList = root.getJSONArray("list");
for (int i = 0; i < count; ++i){
WeatherData weather = new WeatherData();
JSONObject wBlock = wList.getJSONObject(i);
weather.setDate(wBlock.getString("dt_txt"));
JSONObject mainObj = wBlock.getJSONObject("main");
weather.setTemp(String.valueOf(mainObj.getDouble("temp")));
weather.setMinTemp(String.valueOf(mainObj.getDouble("temp_min")));
weather.setMaxTemp(String.valueOf(mainObj.getDouble("temp_max")));
weather.setHumidity(String.valueOf(mainObj.getInt("humidity")));
JSONArray warray = wBlock.getJSONArray("weather");
JSONObject weatherObj = warray.getJSONObject(0);
weather.setDescription(weatherObj.getString("description"));
weather.setShortDesc(weatherObj.getString("main"));
weather.setIconID(weatherObj.getString("icon"));
weatherDataArrayList.add(weather);
Log.d(TAG, "extractor: temp field is :" + weather.getTemp());
}
}catch (JSONException e){
e.printStackTrace();
}
return weatherDataArrayList;
}
}
public ArrayList<WeatherData> extractByDate(ArrayList<WeatherData> fullList,String date){
ArrayList<WeatherData> dayweatherList = new ArrayList<WeatherData>();
for( WeatherData weather : fullList ){
if( ( weather.getDate().substring(0,9) ).equals(date) ){
dayweatherList.add(weather);
}
}
return dayweatherList;
}
}
What should I do?
Error message : (
08-19 23:11:39.914 12148-12148/com.jugalmistry.apps.fivedaysofweather D/DayAdapter: getView: dayweather is not null
08-19 23:11:39.916 12148-12148/com.jugalmistry.apps.fivedaysofweather D/AndroidRuntime: Shutting down VM
08-19 23:11:39.918 12148-12148/com.jugalmistry.apps.fivedaysofweather E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.jugalmistry.apps.fivedaysofweather, PID: 12148
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:411)
at com.jugalmistry.apps.fivedaysofweather.DayAdapter.getView(DayAdapter.java:58)
I have attempted to help you with the full code below.
I would also recommend you implement the ViewHolder pattern ViewHolder pattern example for increased performance.
public class MainActivity extends AppCompatActivity
{
private static final String TAG = "MainActivity";
EditText cityName;
String city = null;
ListView dayListView;
ArrayList<WeatherData> weatherDataArrayList;
DayAdapter dayAdapter;
//private String responseJSON = null;
//WeatherAdapter weatherAdapter = null; // Creating this adapter within the DayAdapter
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cityName = (EditText) findViewById(R.id.cityName);
Button load = (Button) findViewById(R.id.loadButton);
dayListView = (ListView) findViewById(R.id.dayList);
load.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
city = cityName.getText().toString();
Log.d(TAG, "onClick: city is : " + city);
if (city == null)
{
Toast toast = null;
toast.makeText(MainActivity.this,"Please Enter a city before continuing",Toast.LENGTH_LONG);
toast.show();
}
else
{
String url = "http://api.openweathermap.org/data/2.5/forecast?q=" + (city.toLowerCase()) + "&units=metric&appid=8b10912e19fde267f36f6cb785ee7efd";
Log.d(TAG, "onCreate: staring download task");
DownloadJSON downloadJSON = new DownloadJSON();
downloadJSON.execute(url);
Log.d(TAG, "onCreate: after downloadtask");
}
}
});
}
public void SetDayListData(ArrayList<String> dayBlock, ArrayList<WeatherData> weatherBlock)
{
if (dayAdapter == null)
{
dayAdapter = new DayAdapter(MainActivity.this,R.layout.layout_day_card, days, weatherDataArrayList);
dayListView.setAdapter(dayAdapter);
}
else
{
//created a new method "UpdateData" just to update the data in the adapter
dayAdapter.UpdateData(days, weatherDataArrayList);
dayAdapter.notifyDataSetChanged();
}
}
private class DownloadJSON extends AsyncTask<String, Void, String>
{
private static final String TAG = "DownloadJSON";
private String downloadJSON(String url)
{
StringBuilder jsonResult = new StringBuilder();
try
{
URL apiURL = new URL(url);
HttpURLConnection connection = (HttpURLConnection) apiURL.openConnection();
int responseCode = connection.getResponseCode();
Log.d(TAG, "downloadJSON: Response code "+ responseCode);
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
int charReader;
char[] inputBuffer = new char[500];
while (true)
{
charReader = reader.read(inputBuffer);
if (charReader < 0)
{
break;
}
if (charReader > 0)
{
jsonResult.append(String.copyValueOf(inputBuffer, 0, charReader));
}
}
reader.close();
return jsonResult.toString();
}
catch (MalformedURLException e)
{
Log.e(TAG, "downloadJSON: URL is Invalid");
}
catch (IOException e)
{
Log.e(TAG, "downloadJSON: IO Error");
}
return null;
}
#Override
protected String doInBackground(String... strings)
{
Log.d(TAG, "doInBackground: url is : " + strings[0]);
String jsonResponse = downloadJSON(strings[0]);
if (jsonResponse == null)
{
Log.e(TAG, "doInBackground: Error downloading");
}
return jsonResponse;
}
#Override
protected void onPostExecute(String jsonResponse)
{
super.onPostExecute(jsonResponse);
Log.d(TAG, "onPostExecute: json received is : " + jsonResponse);
if (jsonResponse != null)
{
JsonToWeatherData jtwd = new JsonToWeatherData();
weatherDataArrayList = jtwd.extractor(jsonResponse);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
String date1 = simpleDateFormat.format(calendar.getTime());
calendar.add(Calendar.DATE,1);
String date2 = simpleDateFormat.format(calendar.getTime());
calendar.add(Calendar.DATE,1);
String date3 = simpleDateFormat.format(calendar.getTime());
calendar.add(Calendar.DATE,1);
String date4 = simpleDateFormat.format(calendar.getTime());
calendar.add(Calendar.DATE,1);
String date5 = simpleDateFormat.format(calendar.getTime());
ArrayList<String> days = new ArrayList<>();
days.add(date1);
days.add(date2);
days.add(date3);
days.add(date4);
days.add(date5);
SetDayListData(days, weatherDataArrayList);
}
else
{
Log.d(TAG, "onPostExecute: no json recieved, city is Wrong");
Toast toast = Toast.makeText(MainActivity.this,"Please provide a valid city!",Toast.LENGTH_LONG);
toast.show();
}
}
}
}
public class DayAdapter extends ArrayAdapter<String>
{
private static final String TAG = "DayAdapter";
private Context context;
private LayoutInflater layoutInflater;
private int layoutresourceID;
private ArrayList<String> dayBlock;
private ArrayList<WeatherData> dayWeather, weatherBlock;
JsonToWeatherData json = new JsonToWeatherData();
public DayAdapter(#NonNull Context context, int resource, #NonNull ArrayList<String> dayBlock, ArrayList<WeatherData> weatherBlock)
{
super(context, resource, dayBlock);
this.context = context;
this.dayBlock = dayBlock;
this.weatherBlock = weatherBlock;
layoutInflater = LayoutInflater.from(context);
this.layoutresourceID = resource;
if (weatherBlock == null)
{
Log.e(TAG, "DayAdapter: full block is null");
}
}
#Override
public int getCount()
{
return dayBlock.getSize();
}
public void UpdateData(#NonNull ArrayList<String> dayBlock, ArrayList<WeatherData> weatherBlock)
{
this.dayBlock = dayBlock;
this.weatherBlock = weatherBlock;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent)
{
if (convertView == null)
{
convertView = layoutInflater.inflate(layoutresourceID,parent,false);
}
if (weatherBlock == null)
{
Log.d(TAG, "getView: weatherBlock is null");
return convertView;
}
TextView date = (TextView) convertView.findViewById(R.id.date);
TextView minTempFoDay = (TextView) convertView.findViewById(R.id.minTempOfDay);
TextView maxTempFoDay = (TextView) convertView.findViewById(R.id.maxTempOfDay);
ListView weatherHolderListView = (ListView) convertView.findViewById(R.id.wHoldLV);
String dateString = dayBlock.get(position);
dayWeather = json.extractByDate(weatherBlock, dateString);
if (dayWeather == null)
{
Log.d(TAG, "getView: dayweather array is null");
return convertView;
}
if (position > dayWeather.getSize() - 1)
{
Log.d(TAG, "getView: the position is too great for the dayWeather array");
return convertView;
}
String test = dayWeather.get(position).getTemp(); // error occured here
Log.d(TAG, "getView: test string : " + test);
date.setText(dateString);
DecimalFormat df = new DecimalFormat(".##");
float mint = 500, maxt = 0;
String mint1 = "", maxt1 = "";
for (WeatherData data : dayWeather)
{
if (mint > Float.parseFloat(data.getMinTemp()))
{
mint = Float.parseFloat(data.getMinTemp());
mint1 = df.format(mint);
Log.d(TAG, "getView: mint : " + mint);
}
if (maxt > Float.parseFloat(data.getMaxTemp()))
{
maxt = Float.parseFloat(data.getMaxTemp());
maxt1 = df.format(maxt);
}
}
minTempFoDay.setText(mint1);
maxTempFoDay.setText(maxt1);
WeatherAdapter weatherAdapter = new WeatherAdapter(context, R.layout.weather_holder, dayWeather);
weatherHolderListView.setAdapter(weatherAdapter);
return convertView;
}
}
I've created a Listview with a Countdown timer and below is the code :
public class TicketAdapter extends ArrayAdapter<TicketModel> implements View.OnClickListener{
private ArrayList<TicketModel> dataSet;
Context mContext;
long timeLeftMS ;
// View lookup cache
private class ViewHolder {
TextView txtName;
TextView txtType;
TextView txtTempsRestant;
TextView txtDate;
TextView txtSLA;
ImageView info;
RelativeLayout layout;
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
System.out.println("handler");
int hour = (int) ((timeLeftMS / (1000*60*60)) % 24);
int minute = (int) ((timeLeftMS / (60000)) % 60);
int seconde = (int)timeLeftMS % 60000 / 1000;
String timeLeftText = "";
if (hour<10) timeLeftText += "0";
timeLeftText += hour;
timeLeftText += ":";
if (minute<10) timeLeftText += "0";
timeLeftText += minute;
timeLeftText += ":";
if (seconde<10) timeLeftText += "0";
timeLeftText += seconde;
txtTempsRestant.setText(timeLeftText);
}
};
}
public TicketAdapter(ArrayList<TicketModel> data, Context context) {
super(context, R.layout.row_item_ticket, data);
this.dataSet = data;
this.mContext=context;
//startUpdateTimer();
}
#Override
public void onClick(View v) {
int position=(Integer) v.getTag();
Object object= getItem(position);
TicketModel TicketModel=(TicketModel)object;
switch (v.getId())
{
case R.id.item_info:
Snackbar.make(v, "is Late? : " +TicketModel.isTicketEnRetard(), Snackbar.LENGTH_LONG)
.setAction("No action", null).show();
break;
}
}
private int lastPosition = -1;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
TicketModel TicketModel = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
final ViewHolder viewHolder; // view lookup cache stored in tag
final View result;
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.row_item_ticket, parent, false);
viewHolder.txtName = (TextView) convertView.findViewById(R.id.titreTV);
viewHolder.txtDate = (TextView) convertView.findViewById(R.id.dateTV);
viewHolder.txtSLA = (TextView) convertView.findViewById(R.id.slaTV);
viewHolder.txtTempsRestant = (TextView) convertView.findViewById(R.id.SLARestantTV);
viewHolder.info = (ImageView) convertView.findViewById(R.id.item_info);
viewHolder.layout = (RelativeLayout) convertView.findViewById(R.id.backgroundRow);
result=convertView;
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
result=convertView;
}
Animation animation = AnimationUtils.loadAnimation(mContext, (position > lastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top);
result.startAnimation(animation);
lastPosition = position;
viewHolder.txtName.setText(TicketModel.getTitreTicket());
viewHolder.txtDate.setText(TicketModel.getDateTicket());
viewHolder.txtSLA.setText(TicketModel.getSlaTicket());
//viewHolder.txtTempsRestant.setText(TicketModel.getTempsRestantTicket());
viewHolder.info.setImageResource(getIconUrgence(TicketModel.getUrgenceTicket()));
viewHolder.layout.setBackgroundColor(getColorBG(TicketModel.isTicketEnRetard()));
viewHolder.info.setOnClickListener(this);
viewHolder.info.setTag(position);
System.out.println("Here : "+TicketModel.getTitreTicket()); //getting each item's name
System.out.println("Time = "+TicketModel.getTempsRestantTicket()); //getting each item's time left and it's correct
timeLeftMS = Long.valueOf(TicketModel.getTempsRestantTicket());
startTimer(viewHolder.handler);
// Return the completed view to render on screen
return convertView;
}
private void startTimer(final Handler handler) {
CountDownTimer countDownTimer = new CountDownTimer(timeLeftMS, 1000) {
#Override
public void onTick(long l) {
timeLeftMS = l;
handler.sendEmptyMessage(0);
}
#Override
public void onFinish() {
}
}.start();
}
private int getColorBG(boolean ticketEnRetard) {
int color;
if (ticketEnRetard){
color = Color.parseColor("#3caa0000");
}
else{
color = Color.parseColor("#ffffff");
}
return color;
}
private int getIconUrgence(String urgenceTicket) {
int icon;
if((urgenceTicket.equals("Très basse"))||(urgenceTicket.equals("Basse"))){
icon = R.drawable.basse;
}
else if((urgenceTicket.equals("Haute"))||(urgenceTicket.equals("Très haute"))){
icon = R.drawable.haute;
}
else {
icon = R.drawable.moyenne;
}
return icon;
}
}
TicketModel class :
public class TicketModel {
String titreTicket;
String slaTicket;
String DateTicket;
String UrgenceTicket;
boolean ticketEnRetard;
String TempsRestantTicket;
public TicketModel(String titreTicket, String slaTicket, String dateTicket, String tempsRestantTicket) {
this.titreTicket = titreTicket;
this.slaTicket = slaTicket;
DateTicket = dateTicket;
TempsRestantTicket = tempsRestantTicket;
}
public String getTitreTicket() {
return titreTicket;
}
public String getSlaTicket() {
return slaTicket;
}
public String getDateTicket() {
return DateTicket;
}
public String getUrgenceTicket() {
return UrgenceTicket;
}
public void setUrgenceTicket(String urgenceTicket) {
UrgenceTicket = urgenceTicket;
}
public void setTempsRestantTicket(String tempsRestantTicket) {
TempsRestantTicket = tempsRestantTicket;
}
public String getTempsRestantTicket() {
return TempsRestantTicket;
}
public boolean isTicketEnRetard() {
return ticketEnRetard;
}
public void setTicketEnRetard(boolean ticketEnRetard) {
this.ticketEnRetard = ticketEnRetard;
}
}
Where I'm populating my ListView :
public class ListTickets extends AppCompatActivity {
ArrayList<TicketModel> TicketModels;
ListView listView;
private static TicketAdapter adapter;
String session_token, nameUser, idUser, firstnameUser, nbTicket;
RequestQueue queue;
String titreTicket, slaTicket, urgenceTicket,
demandeurTicket, categorieTicket, etatTicket, dateDebutTicket,
dateEchanceTicket, dateClotureTicket, descriptionTicket, lieuTicket;
boolean ticketEnretard;
public static int nbTicketTab = 6;
public static int nbInfoTicket = 12;
public static String[][] ticketTab ;
public static String[][] infoTicket ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_tickets);
queue = Volley.newRequestQueue(this);
Intent i = getIntent();
session_token = i.getStringExtra("session");
nbTicket = i.getStringExtra("nb");
nameUser = i.getStringExtra("nom");
firstnameUser = i.getStringExtra("prenom");
idUser = i.getStringExtra("id");
listView=(ListView)findViewById(R.id.list);
TicketModels = new ArrayList<>();
ticketTab = new String[Integer.valueOf(nbTicket)][nbTicketTab];
infoTicket = new String[Integer.valueOf(nbTicket)][nbInfoTicket];
String url = FirstEverActivity.GLPI_URL+"search/Ticket";
List<KeyValuePair> params = new ArrayList<>();
params.add(new KeyValuePair("criteria[0][field]","5"));
params.add(new KeyValuePair("criteria[0][searchtype]","equals"));
params.add(new KeyValuePair("criteria[0][value]",idUser));
params.add(new KeyValuePair("forcedisplay[0]","4"));
params.add(new KeyValuePair("forcedisplay[1]","10"));
params.add(new KeyValuePair("forcedisplay[2]","7"));
params.add(new KeyValuePair("forcedisplay[3]","12"));
params.add(new KeyValuePair("forcedisplay[4]","15"));
params.add(new KeyValuePair("forcedisplay[5]","30"));
params.add(new KeyValuePair("forcedisplay[6]","18"));
params.add(new KeyValuePair("forcedisplay[7]","21"));
params.add(new KeyValuePair("forcedisplay[8]","83"));
params.add(new KeyValuePair("forcedisplay[9]","82"));
params.add(new KeyValuePair("forcedisplay[10]","16"));
final JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, generateUrl(url, params), null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
try {
JSONArray Jdata = response.getJSONArray("data");
for (int i=0; i < Jdata.length(); i++) {
try {
JSONObject oneTicket = Jdata.getJSONObject(i);
// Récupération des items pour le row_item
titreTicket = oneTicket.getString("1");
slaTicket = oneTicket.getString("30");
dateDebutTicket = oneTicket.getString("15");
urgenceTicket = oneTicket.getString("10");
//Récupération du reste
demandeurTicket = oneTicket.getString("4");
categorieTicket = oneTicket.getString("7");
etatTicket = oneTicket.getString("12");
dateEchanceTicket = oneTicket.getString("18");
descriptionTicket = oneTicket.getString("21");
lieuTicket = oneTicket.getString("83");
dateClotureTicket = oneTicket.getString("16");
ticketEnretard = getBooleanFromSt(oneTicket.getString("82"));
System.out.println("Direct = " + oneTicket.getString("82") + "\n After f(x) = " + getBooleanFromSt(oneTicket.getString("82")));
} catch (JSONException e) {
Log.e("Nb of data: "+Jdata.length()+" || "+"Error JSONArray at "+i+" : ", e.getMessage());
}
ticketTab[i][0] = titreTicket;
ticketTab[i][1] = slaTicket;
ticketTab[i][2] = dateDebutTicket;
ticketTab[i][3] = urgenceText(urgenceTicket);
ticketTab[i][4] = calculTempsRestant(dateDebutTicket, slaTicket); //TimeLeft value here
ticketTab[i][5] = String.valueOf(ticketEnretard);
infoTicket[i][0] = demandeurTicket;
infoTicket[i][1] = urgenceText(urgenceTicket);
infoTicket[i][2] = categorieTicket;
infoTicket[i][3] = etatText(etatTicket);
infoTicket[i][4] = dateDebutTicket;
infoTicket[i][5] = slaTicket;
infoTicket[i][6] = dateEchanceTicket;
infoTicket[i][7] = titreTicket;
infoTicket[i][8] = descriptionTicket;
infoTicket[i][9] = lieuTicket;
infoTicket[i][10] = calculTempsRestant(dateDebutTicket, slaTicket);
infoTicket[i][11] = dateClotureTicket;
System.out.println("Temps restant = "+calculTempsRestant(dateDebutTicket, slaTicket));
System.out.println("SLA = "+slaTicket);
System.out.println("Between : "+getBetweenBrackets(slaTicket));
System.out.println("Minimum : "+getMinTemps(slaTicket));
System.out.println("Maximim : "+getMaxTemps(slaTicket));
}
System.out.println("*** Tab Ticket ***");
System.out.println("isLate: "+ticketTab[0][5]);
System.out.println("\n\n*** Info Ticket ***");
System.out.println("Titre: "+infoTicket[0][7]);
// Populate the ListView
addModelsFromTab(ticketTab);
adapter = new TicketAdapter(TicketModels,getApplicationContext());
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TicketModel TicketModel= TicketModels.get(position);
Snackbar.make(view, "Index = "+position, Snackbar.LENGTH_LONG)
.setAction("No action", null).show();
Intent i = new Intent(getApplicationContext(), InfoTicket.class);
i.putExtra("session",session_token);
i.putExtra("nom",nameUser);
i.putExtra("prenom",firstnameUser);
i.putExtra("id",idUser);
i.putExtra("infoTicket", infoTicket[position]);
startActivity(i);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
//progressBar.setVisibility(View.GONE);
Log.e("Error.Response", error.toString());
}
}
){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("App-Token",FirstEverActivity.App_Token);
params.put("Session-Token",session_token);
return params;
}
};
// add it to the RequestQueue
queue.add(getRequest);
}
private void addModelsFromTab(String[][] ticketTab) {
for (int i = 0; i < ticketTab.length; i++){
TicketModel ticket = new TicketModel(ticketTab[i][0], ticketTab[i][1], ticketTab[i][2], ticketTab[i][4]);
ticket.setUrgenceTicket(ticketTab[i][3]);
ticket.setTicketEnRetard(Boolean.parseBoolean(ticketTab[i][5]));
//ticket.setTempsRestantTicket(ticketTab[i][4]);
TicketModels.add(ticket);
}
}
private String calculTempsRestant(String dateDebutTicket, String slaTicket) {
String minTemps = getMinTemps(slaTicket);
String maxTemps = getMaxTemps(slaTicket);
long dateDebutMS = getDateDebutMS(dateDebutTicket);
long currentTimeMS = CurrentTimeMS();
long minTempsMS = hourToMSConvert(minTemps);
long differenceCurrentDebut = currentTimeMS - dateDebutMS;
long tempsRestant = minTempsMS - differenceCurrentDebut;
return String.valueOf(tempsRestant);
}
}
The issue I have is that I want to display the timer (the timeLeftText String) in the txtTempsRestant TextView, but I can't access it. Can anyone give me advice?
When I print in the console and the output is correct, but I'm not able to display it. Should I change the way I'm working?
Modified Adapter class to make the count down work properly.
public class TicketAdapter extends ArrayAdapter<TicketModel> implements View.OnClickListener{
private ArrayList<TicketModel> dataSet;
Context mContext;
// View lookup cache
private class ViewHolder {
TextView txtName;
TextView txtType;
TextView txtTempsRestant;
TextView txtDate;
TextView txtSLA;
ImageView info;
RelativeLayout layout;
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
System.out.println("handler");
Bundle bundle = msg.getData();
long timeLeftMS = bundle.getLong("time");
int hour = (int) ((timeLeftMS / (1000*60*60)) % 24);
int minute = (int) ((timeLeftMS / (60000)) % 60);
int seconde = (int)timeLeftMS % 60000 / 1000;
String timeLeftText = "";
if (hour<10) timeLeftText += "0";
timeLeftText += hour;
timeLeftText += ":";
if (minute<10) timeLeftText += "0";
timeLeftText += minute;
timeLeftText += ":";
if (seconde<10) timeLeftText += "0";
timeLeftText += seconde;
txtTempsRestant.setText(timeLeftText);
}
};
public void startTimer(long timeLeftMS) {
CountDownTimer countDownTimer = new CountDownTimer(timeLeftMS, 1000) {
#Override
public void onTick(long l) {
Bundle bundle = new Bundle();
bundle.putLong("time", l);
Message message = new Message();
message.setData(bundle);
handler.sendMessage(message);
}
#Override
public void onFinish() {
}
}.start();
}
}
public TicketAdapter(ArrayList<TicketModel> data, Context context) {
super(context, R.layout.row_item_ticket, data);
this.dataSet = data;
this.mContext=context;
//startUpdateTimer();
}
#Override
public void onClick(View v) {
int position=(Integer) v.getTag();
Object object= getItem(position);
TicketModel TicketModel=(TicketModel)object;
switch (v.getId())
{
case R.id.item_info:
Snackbar.make(v, "is Late? : " +TicketModel.isTicketEnRetard(), Snackbar.LENGTH_LONG)
.setAction("No action", null).show();
break;
}
}
private int lastPosition = -1;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
TicketModel TicketModel = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
final ViewHolder viewHolder; // view lookup cache stored in tag
final View result;
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.row_item_ticket, parent, false);
viewHolder.txtName = (TextView) convertView.findViewById(R.id.titreTV);
viewHolder.txtDate = (TextView) convertView.findViewById(R.id.dateTV);
viewHolder.txtSLA = (TextView) convertView.findViewById(R.id.slaTV);
viewHolder.txtTempsRestant = (TextView) convertView.findViewById(R.id.SLARestantTV);
viewHolder.info = (ImageView) convertView.findViewById(R.id.item_info);
viewHolder.layout = (RelativeLayout) convertView.findViewById(R.id.backgroundRow);
result=convertView;
viewHolder.startTimer(Long.valueOf(TicketModel.getTempsRestantTicket()));
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
result=convertView;
}
Animation animation = AnimationUtils.loadAnimation(mContext, (position > lastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top);
result.startAnimation(animation);
lastPosition = position;
viewHolder.txtName.setText(TicketModel.getTitreTicket());
viewHolder.txtDate.setText(TicketModel.getDateTicket());
viewHolder.txtSLA.setText(TicketModel.getSlaTicket());
//viewHolder.txtTempsRestant.setText(TicketModel.getTempsRestantTicket());
viewHolder.info.setImageResource(getIconUrgence(TicketModel.getUrgenceTicket()));
viewHolder.layout.setBackgroundColor(getColorBG(TicketModel.isTicketEnRetard()));
viewHolder.info.setOnClickListener(this);
viewHolder.info.setTag(position);
System.out.println("Here : "+TicketModel.getTitreTicket()); //getting each item's name
System.out.println("Time = "+TicketModel.getTempsRestantTicket()); //getting each item's time left and it's correct
// Return the completed view to render on screen
return convertView;
}
private int getColorBG(boolean ticketEnRetard) {
int color;
if (ticketEnRetard){
color = Color.parseColor("#3caa0000");
}
else{
color = Color.parseColor("#ffffff");
}
return color;
}
private int getIconUrgence(String urgenceTicket) {
int icon;
if((urgenceTicket.equals("Très basse"))||(urgenceTicket.equals("Basse"))){
icon = R.drawable.basse;
}
else if((urgenceTicket.equals("Haute"))||(urgenceTicket.equals("Très haute"))){
icon = R.drawable.haute;
}
else {
icon = R.drawable.moyenne;
}
return icon;
}
}
You don't want to declare the TextView static if you'll be changing the value.
Try declaring it outside the method here:
public class TicketAdapter extends ArrayAdapter<TicketModel> implements View.OnClickListener{
private ArrayList<TicketModel> dataSet;
Context mContext;
static long timeLeftMS = Long.valueOf(TicketModel.getTempsRestantTicket());
private TextView txtTempsRestant ;
// View lookup cache
private static class ViewHolder {
TextView txtName;
TextView txtType;
TextView txtDate;
TextView txtSLA;
ImageView info;
RelativeLayout layout;
TextView txtTempsRestant ;
}
Hi i have a code its good
beucse u dont need definination 3 textview for right and left ,....
You will create one TextView and use this code for create
private void Time() {
mCountTimer = new CountDownTimer(aTime, 1000) {
#Override
public void onTick(long millisUntilFinished) {
aMinute = (int) (millisUntilFinished / 1000) / 60;
mSecond = (int) (millisUntilFinished / 1000) % 60;
mTimer.setText(String.format(Locale.getDefault(), "%d:%02d", aMinute, mSecond));
}
#Override
public void onFinish() {
mTimer.setText(String.format(Locale.getDefault(), "%d:%02d", 0, 0));
mSend_Again.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Your EVENT
}
});
}
}.start();
}
When am set Count down timer for single progress circle its work perfectly but when am using it for Listview my Progress Circle not work perfectly. Please tell me How to implement count down timer for listview in android.
private ListView lvHomeItems;
private List<HomeContent> homeListContent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
lvHomeItems = (ListView) findViewById(R.id.lv_home_activity);
homeListContent = new ArrayList<>();
homeListContent.add(new HomeContent("3","22-10-2016","BDOI501",System.currentTimeMillis() + 10000));
homeListContent.add(new HomeContent("2","21-10-2016","BDOI502",System.currentTimeMillis() + 22000));
homeListContent.add(new HomeContent("4","20-10-2016","BDOI503",System.currentTimeMillis() + 34000));
homeListContent.add(new HomeContent("1","19-10-2016","BDOI504",System.currentTimeMillis() + 46000));
lvHomeItems.setAdapter(new CountdownAdapter(HomeActivity.this, homeListContent));
}
private class HomeContent {
long expirationTime;
String Date;
String Id;
String PrescriptionNo;
public HomeContent(String PrescriptionNo,String Date,String Id,long expirationTime) {
this.expirationTime = expirationTime;
this.PrescriptionNo = PrescriptionNo;
this.Date = Date;
this.Id = Id;
}
}
public class CountdownAdapter extends ArrayAdapter<HomeContent> {
private LayoutInflater layoutInflater;
private List<ViewHolder> homeListContent;
private Handler mHandler = new Handler();
private Runnable updateRemainingTimeRunnable = new Runnable() {
#Override
public void run() {
synchronized (homeListContent) {
long currentTime = System.currentTimeMillis();
for (ViewHolder holder : homeListContent) {
holder.updateTimeRemaining(currentTime);
}
}
}
};
public CountdownAdapter(Context context, List<HomeContent> objects) {
super(context, 0, objects);
layoutInflater = LayoutInflater.from(context);
homeListContent = new ArrayList<>();
startUpdateTimer();
}
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) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = layoutInflater.inflate(R.layout.home_list_content, parent, false);
holder.tvCountDownTimer = (TextView) convertView.findViewById(R.id.tv_home_countTimeDown);
holder.tvDate = (TextView) convertView.findViewById(R.id.tv_home_date);
holder.tvOrderId = (TextView) convertView.findViewById(R.id.tv_home_order_id);
holder.tvPrescriptionNo = (TextView) convertView.findViewById(R.id.tv_priscription_no);
holder.tvViewDetails = (TextView) convertView.findViewById(R.id.tv_view);
holder.btnSelectBid = (Button) convertView.findViewById(R.id.btn_select_bid);
holder.mRingProgressBar = (RingProgressBar) convertView.findViewById(R.id.progress_bar_1);
//doSomeThing();
holder.tvViewDetails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(HomeActivity.this,PrescriptionListActivity.class);
startActivity(intent);
}
});
holder.btnSelectBid.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// bidVenderList();
Intent intent = new Intent(HomeActivity.this,SelectBidActivity.class);
startActivity(intent);
}
});
convertView.setTag(holder);
synchronized (homeListContent) {
homeListContent.add(holder);
}
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.setData(getItem(position));
return convertView;
}
}
private class ViewHolder {
TextView tvViewDetails, tvCountDownTimer, tvDate, tvOrderId, tvPrescriptionNo;
Button btnSelectBid;
HomeContent mProduct;
RingProgressBar mRingProgressBar;
public void setData(HomeContent item) {
mProduct = item;
tvOrderId.setText("Order Id : " + item.Id);
tvDate.setText("Date : " + item.Date);
tvPrescriptionNo.setText("No of Prescription : " + item.PrescriptionNo);
updateTimeRemaining(System.currentTimeMillis());
}
public void updateTimeRemaining(long currentTime) {
final long timeDiff = mProduct.expirationTime - currentTime;
new Thread(new Runnable() {
public void run() {
while (mProgressStatus < 100) {
mProgressStatus += 1;
// Update the progress bar
mHandler.post(new Runnable() {
public void run() {
mRingProgressBar.setProgress(mProgressStatus);
mRingProgressBar.setMax(60);
if (timeDiff > 0) {
final int seconds = (int) (timeDiff / 1000) % 60;
final int minutes = (int) ((timeDiff / (1000 * 60)) % 60);
tvCountDownTimer.setText(minutes + " : " + seconds);
}
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
When am start my activity it not work perfectly... please tell me solution
I'm working with fragments and flipview but I'm having some problems with this.
When my app opens the first screen show my feed with the FlipView. When I choose another tab of my fragments the fragment of the feed didn't hide or detach. I debugged many times and the code arrives in the detached line but didn't work.
Here is my code
MainActivity class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FontManager.getInstance().initialize(this, R.xml.fonts);
setContentView(R.layout.activity_main);
mFBSession = new FBSessionsManager();
mActionBar = getActionBar();
fm = getFragmentManager();
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.setup();
TabHost.OnTabChangeListener mTabChangeListener = new TabHost.OnTabChangeListener() {
#Override
public void onTabChanged(String tabId) {
ft = fm.beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_ENTER_MASK);
FeedPrincipalList mFeedFragment = (FeedPrincipalList) fm.findFragmentByTag(TAB_TAG_FEED);
EverythingFragmentList mEverythingFragment = (EverythingFragmentList) fm.findFragmentByTag(TAB_TAG_ALL_EVERYTHING);
PaymentFragment mPaymentFragment = (PaymentFragment) fm.findFragmentByTag(TAB_TAG_PAYMENT);
ConsultFragmentList mConsultFragmentList = (ConsultFragmentList) fm.findFragmentByTag(TAB_TAG_M_CONSULT);
ProfileFragmentList mProfileFragmentList = (ProfileFragmentList) fm.findFragmentByTag(TAB_TAG_M_PROFILE);
if (mFeedFragment != null){
ft.detach(mFeedFragment);
// ft.commit();
}
if (mEverythingFragment != null)
ft.detach(mEverythingFragment);
if (mPaymentFragment != null)
ft.detach(mPaymentFragment);
if (mConsultFragmentList != null)
ft.detach(mConsultFragmentList);
if (mProfileFragmentList != null){
ft.detach(mProfileFragmentList);
// ft.commit();
}
if (tabId.equalsIgnoreCase(TAB_TAG_FEED)) {
manageContextualActions(true, false);
if (mFeedFragment == null) {
mFeedFragment = new FeedPrincipalList();
ft.add(R.id.realTabContent, mFeedFragment, TAB_TAG_FEED);
} else {
mFeedFragment = new FeedPrincipalList();
ft.attach(mFeedFragment);
}
}
if (tabId.equalsIgnoreCase(TAB_TAG_ALL_EVERYTHING)) {
manageContextualActions(false, true);
if (mEverythingFragment == null) {
mEverythingFragment = new EverythingFragmentList();
ft.replace(R.id.realTabContent, mEverythingFragment, TAB_TAG_ALL_EVERYTHING);
} else {
ft.attach(mEverythingFragment);
}
}
if (tabId.equalsIgnoreCase(TAB_TAG_PAYMENT)) {
manageContextualActions(false, true);
if (mPaymentFragment == null) {
mPaymentFragment = new PaymentFragment();
ft.replace(R.id.realTabContent, mPaymentFragment, TAB_TAG_PAYMENT);
} else {
ft.attach(mPaymentFragment);
}
}
if (tabId.equalsIgnoreCase(TAB_TAG_M_CONSULT)) {
manageContextualActions(false, true);
if (mConsultFragmentList == null) {
mConsultFragmentList = new ConsultFragmentList();
ft.replace(R.id.realTabContent, mConsultFragmentList, TAB_TAG_M_CONSULT);
} else {
ft.attach(mConsultFragmentList);
}
}
if (tabId.equalsIgnoreCase(TAB_TAG_M_PROFILE)) {
manageContextualActions(false, false);
if (mProfileFragmentList == null) {
mProfileFragmentList = new ProfileFragmentList();
ft.replace(R.id.realTabContent, mProfileFragmentList, TAB_TAG_M_PROFILE);
} else {
mProfileFragmentList = new ProfileFragmentList();
ft.attach(mProfileFragmentList);
}
}
ft.commit();
}
};
mTabHost.setOnTabChangedListener(mTabChangeListener);
createAndConfigureTabs();
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
}
public void setupActionBar(int stringTitleID) {
mActionBar.setDisplayShowCustomEnabled(true);
mActionBar.setDisplayShowTitleEnabled(false);
mActionBar.setDisplayUseLogoEnabled(false);
final LayoutInflater inflater = LayoutInflater.from(this);
final View customTitle = inflater.inflate(R.layout.custom_title, null);
((TextView) customTitle.findViewById(R.id.customTitleActionbar)).setText(getResources().getString(stringTitleID));
mActionBar.setCustomView(customTitle);
}
private void createAndConfigureTabs() {
mTabFeed = mTabHost.newTabSpec(TAB_TAG_FEED);
mTabFeed.setIndicator(null, getResources().getDrawable(R.drawable.custom_btn_feed));
mTabFeed.setContent(new TabContentCreator(this));
mTabHost.addTab(mTabFeed);
mTabAllEverything = mTabHost.newTabSpec(TAB_TAG_ALL_EVERYTHING);
mTabAllEverything.setIndicator(null, getResources().getDrawable(R.drawable.custom_btn_all_everything));
mTabAllEverything.setContent(new TabContentCreator(this));
mTabHost.addTab(mTabAllEverything);
mTabCameraAndPayment = mTabHost.newTabSpec(TAB_TAG_PAYMENT);
mTabCameraAndPayment.setIndicator(null, getResources().getDrawable(R.drawable.btn_camera));
mTabCameraAndPayment.setContent(new TabContentCreator(this));
mTabHost.addTab(mTabCameraAndPayment);
mTabConsult = mTabHost.newTabSpec(TAB_TAG_M_CONSULT);
mTabConsult.setIndicator(null, getResources().getDrawable(R.drawable.custom_btn_consult));
mTabConsult.setContent(new TabContentCreator(this));
mTabHost.addTab(mTabConsult);
mTabMyProfile = mTabHost.newTabSpec(TAB_TAG_M_PROFILE);
mTabMyProfile.setIndicator(null, getResources().getDrawable(R.drawable.custom_btn_profile));
mTabMyProfile.setContent(new TabContentCreator(this));
mTabHost.addTab(mTabMyProfile);
mTabWidget = mTabHost.getTabWidget();
for (int i = 0; i minor 5; i++) {
View v = mTabWidget.getChildAt(i);
v.setBackgroundResource(android.R.drawable.screen_background_light_transparent);
if (i == 4)
v.setPadding(0, 0, 0, 12);
}
}
private class TabContentCreator implements TabHost.TabContentFactory {
private Context mContext;
public TabContentCreator(Context context) {
mContext = context;
}
#Override
public View createTabContent(String tag) {
View v = new View(mContext);
return v;
}
}
FeedFragment class
public class FeedPrincipalList extends android.app.Fragment implements FlipView.OnFlipListener, FlipView.OnOverFlipListener, FlipView.OnClickListener {
private static int timelinePage = 1, mPageCount = 0;
private FlipView mFlipView;
private FeedPrincipalAdapter mAdapter;
private FBSessionsManager fbSessionsManager;
private List mList;
private Context context;
private int posicaoTela;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
context = getActivity().getApplicationContext();
View view = inflater.inflate(R.layout.feed_flipview, container);
((MainFragmentActivity) getActivity()).setupActionBar(R.string.title_fragment_feed);
mFlipView = (FlipView) view.findViewById(R.id.fv_feedFlipView_FlipView);
mFlipView.setOnFlipListener(this);
mFlipView.setOverFlipMode(OverFlipMode.RUBBER_BAND);
mFlipView.setEmptyView(view.findViewById(R.id.empty_view));
mFlipView.setOnOverFlipListener(this);
mFlipView.setOnClickListener(this);
fbSessionsManager = new FBSessionsManager(getActivity());
if (mList == null)
new LoadFeedPrincipalData().execute();
return super.onCreateView(inflater,container,savedInstanceState);
}
#Override
public void onFlippedToPage(FlipView v, int position, long id) {
Log.i("pageflip", "Page: " + position);
posicaoTela = position;
if(position > mFlipView.getPageCount()-3 && mFlipView.getPageCount() {
private UtilWS ws;
private JSONObject toSend;
private JsonArray rsArray;
private JsonParser parser;
public LoadFeedPrincipalData() {
ws = new UtilWS();
toSend = new JSONObject();
parser = new JsonParser();
}
#Override
protected Void doInBackground(Void... params) {
try {
toSend.put("token", fbSessionsManager.getStoredPrivateSession()[0]);
toSend.put("userId", fbSessionsManager.getStoredPrivateSession()[1]);
toSend.put("page", timelinePage);
String[] jsonResult = ws.post(UtilWS.URL_TIMELINE, toSend.toString());
if (jsonResult[0].equals("200")) {
JsonObject temp = parser.parse(jsonResult[1]).getAsJsonObject();
Log.i("JSON",": "+temp.toString());
if (temp.get("success").getAsBoolean()) {
rsArray = temp.get("looks").getAsJsonArray();
if (mPageCount == 0)
mPageCount = temp.get("pageCount").getAsInt();
for (JsonElement el : rsArray) {
if (mList == null)
mList = new ArrayList();
temp = (JsonObject) el;
FeedPrincipalTO tempTudo = new FeedPrincipalTO(temp.get("lookId").getAsString(), temp.get("photoUrl1").getAsString(), temp.get("photoUrl2").getAsString(), temp.get("jaVotou").getAsBoolean(),temp.get("photoVoted").getAsInt() ,temp.get("photo1Total").getAsString(), temp.get("photo2Total").getAsString());
mList.add(tempTudo);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
if (mList != null) {
Log.i("mList","mLista");
mAdapter = new FeedPrincipalAdapter(context,mList);
mAdapter.setCallback(new FeedPrincipalAdapter.Callback() {
#Override
public void onPageRequested(int page) {
mFlipView.smoothFlipTo(page);
}
#Override
public void voteUp(int position) {
Log.i("TESTE","position = " + posicaoTela);
mAdapter.getView(position, null, null).postInvalidate();
// mAdapter.notifyDataSetChanged();
}
});
if (timelinePage == 1) {
mFlipView.setAdapter(mAdapter);
// initListenerList();
} else {
((FeedPrincipalAdapter) mFlipView.getAdapter()).updateList(mList);
((FeedPrincipalAdapter) mFlipView.getAdapter()).notifyDataSetChanged();
}
} else {
mFlipView.setAdapter(new FeedPrincipalAdapter(context,null));
}
}
// private void initListenerList() {
// getListView().setOnScrollListener(new AbsListView.OnScrollListener() {
// #Override
// public void onScrollStateChanged(AbsListView view, int scrollState) {
//
// }
//
// #Override
// public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
// if (firstVisibleItem + visibleItemCount == totalItemCount && totalItemCount != 0) {
// if (timelinePage minor mPageCount) {
// timelinePage++;
// new LoadFeedPrincipalData().execute();
// }
// }
// }
// });
// }
}
}
Please, help me with this!!!
I'm using the FlipView https://github.com/emilsjolander/android-FlipView
Thanks!!!
Finally I solved this problem.
First I changed my Main Class a little.
I changed this two ifs (this fragments uses FlipView) in the MainActivity class.
if (tabId.equalsIgnoreCase(TAB_TAG_FEED)) {
manageContextualActions(true, false);
if (mFeedFragment == null) {
mFeedFragment = new FeedPrincipalList();
ft.add(R.id.realTabContent, mFeedFragment, TAB_TAG_FEED);
} else {
// mFeedFragment = new FeedPrincipalList();
ft.attach(mFeedFragment);
}
}
if (tabId.equalsIgnoreCase(TAB_TAG_M_PROFILE)) {
manageContextualActions(false, false);
if (mProfileFragmentList == null) {
mProfileFragmentList = new ProfileFragmentList();
ft.add(R.id.realTabContent, mProfileFragmentList, TAB_TAG_M_PROFILE);
} else {
// mProfileFragmentList = new ProfileFragmentList();
ft.attach(mProfileFragmentList);
}
}
Second I changed my method onCreateView of my FeedFragment class.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
context = getActivity().getApplicationContext();
((MainFragmentActivity) getActivity()).setupActionBar(R.string.title_fragment_feed);
fbSessionsManager = new FBSessionsManager(getActivity());
if (mList == null){
view = inflater.inflate(R.layout.feed_flipview, container,true);
mFlipView = (FlipView) view.findViewById(R.id.fv_feedFlipView_FlipView);
mFlipView.setOnFlipListener(this);
mFlipView.setOverFlipMode(OverFlipMode.RUBBER_BAND);
mFlipView.setEmptyView(view.findViewById(R.id.empty_view));
mFlipView.setOnOverFlipListener(this);
new LoadFeedPrincipalData().execute();
}
return super.onCreateView(inflater,container,savedInstanceState);
}
You can see the difference. I only inflate the view in the first time. After this my mList(it's a List of MyGetSetClass) it's not null anymore.
And to finish I Override this two methods on my FeedFragment class.
#Override
public void onDetach() {
super.onDetach();
// Log.i("onDetach", "FeedPrincipalList");
mList = null;
timelinePage = 1;
mPageCount = 0;
}
#Override
public void onStart() {
super.onStart();
// Log.i("onStart", "FeedPrincipalList");
this.mFlipView.setVisibility(View.VISIBLE);
}
#Override
public void onStop() {
super.onStop();
// Log.i("onStop","FeedPrincipalList");
this.mFlipView.setVisibility(View.INVISIBLE);
}
In the detach method I clean all my static variables that I will use when I start the app again.
The onStart and the onStop I use to change the Visibility of my FlipView.
That's it.
I hope this help everyone!!!