notifyDataSetChanged not work in my activity - android

in my code when delete row of list view list view don't change.i use adapter.notifyDataSetChange() but it not word.this is my code : code make different position of class.
CustomList adapter;
Integer[] imageId;
public String[] _Data2;
public int positionAll;
ArrayList<ArrayList<String>> _Data = new ArrayList<ArrayList<String>>();
DataBase data = new DataBase(Show_Code.this, "MELK_TBL");
try {
data.open();
_Data = data.GetData();
imageId = new Integer[_Data.size()];
_Data2 = new String[_Data.size()];
for (int i = 0; i < _Data.size(); i++) {
imageId[i] = R.drawable.municipal;
_Data2[i] = _Data.get(i).get(1) + "_" + _Data.get(i).get(2) + "_" + _Data.get(i).get(3) + "_" + _Data.get(i).get(4) + "_" + _Data.get(i).get(5) + "_" + _Data.get(i).get(6) + "_0";
}
adapter = new CustomList(Show_Code.this, _Data2, imageId);
data.close();
} catch (Exception e) {
Toast.makeText(getApplication(), e.toString(), Toast.LENGTH_LONG).show();
}
list.setAdapter(adapter);
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
try {
data.open();
data.Delete(_Data.get(position).get(1), _Data.get(position).get(2), _Data.get(position).get(3), _Data.get(position).get(4), _Data.get(position).get(5), _Data.get(position).get(6), _Data.get(position).get(7));
data.close();
adapter.notifyDataSetChanged();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
return true;
}
});
please help me,i don't any time for it :(

As the size of Array is not changed at run time so u need to create new adapter and set again to list
You have to add this code in onItemLongClick
data.open();
_Data = data.GetData();
imageId = new Integer[_Data.size()];
_Data2 = new String[_Data.size()];
for (int i = 0; i < _Data.size(); i++) {
imageId[i] = R.drawable.municipal;
_Data2[i] = _Data.get(i).get(1) + "_" + _Data.get(i).get(2) + "_" + _Data.get(i).get(3) + "_" + _Data.get(i).get(4) + "_" + _Data.get(i).get(5) + "_" + _Data.get(i).get(6) + "_0";
}
adapter = new CustomList(Show_Code.this, _Data2, imageId);
data.close();
list.setAdapter(adapter)

you are passing _Data2 object in adapter. You should update same object after deleting from data. Try adding this before data.close() in onItemLongClick(AdapterView<?> parent, View view,int position, long id) method:
_Data = data.GetData();
imageId = new Integer[_Data.size()];
_Data2.clear();
for (int i = 0; i < _Data.size(); i++) {
imageId[i] = R.drawable.municipal;
_Data2[i] = _Data.get(i).get(1) + "_" + _Data.get(i).get(2) + "_" + _Data.get(i).get(3) + "_" + _Data.get(i).get(4) + "_" + _Data.get(i).get(5) + "_" + _Data.get(i).get(6) + "_0";
}
Don't create new object of _Data2. Just clear same object and add whole data in it again and after that you can call adapter.notifyDataSetChanged() then this will get updated automatically.

After deleting the values you need to pass the new arraylist in which you had removed all those values and then notify the adapter class. In your case see the below code
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
try {
data.open();
data.Delete(_Data.get(position).get(1));
data.close();
**//Edited code...**
_Data.get(position).remove(1);
adapter.refreshView(_Data);
**//Edited code...**
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
return true;
}
});
And in adapter class refreshview method will be like below,
public void refreshView(String[] _Data) {
this._Data = _Data;
notifyDataSetChanged();
}
By this way you can notify the data. For example I have deleted only one value and notify.
Hope this is helpful :)

You'll need to reorganize your code, using Methods, only for Select you databe again and do the list.setAdapter(adapter); then use adapter.notifyDataSetChanged();

Related

How to uncheck a checkbox in array adapter

I am trying to uncheck checkbox in listview array adapter on onItemClickListener.
its remain checked all the time.If i again click on it to uncheck it is not getting unchecked.
Can anyone over here please suggest me how to do it?
pagesresult = new JSONArray(getIntent().getStringExtra("pageResult"));
for (int i = 0; i < pagesresult.length(); i++) {
JSONObject json = pagesresult.getJSONObject(i);
Iterator<String> keys = json.keys();
while (keys.hasNext()) {
key = keys.next();
//pageValue = );
pageKeyArray.add(key);
pageArray.add(String.valueOf(json.get(key)));
System.out.println("Key :" + key + " Value :" + json.get(key));
Log.d(TAG, "pageKeyArray Check :" + pageKeyArray);
Log.d(TAG, "currentKey Check :" + pageArray);
}
}
alreadyBookedByUser = new JSONArray(getIntent().getStringExtra("alreadyBookedByUser"));
Log.d(TAG, "compositionCount Check :" + pagesresult);
Log.d(TAG, "compositionCount Check :" + alreadyBookedByUser);
} catch (JSONException e) {
e.printStackTrace();
}
done = (Button) findViewById(R.id.done);
findViewsById();
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice,pageArray);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
#Override
public void onClick(View v) {
if (v == done) {
SparseBooleanArray checked = listView.getCheckedItemPositions();
ArrayList<String> selectedItems = new ArrayList<String>();
for (int i = 0; i < checked.size(); i++) {
// Item position in adapter
position = checked.keyAt(i);
listView.setItemChecked(position, true);
Log.d(TAG, "Position check :" + position);
// Add sport if it is checked i.e.) == TRUE!
if (checked.valueAt(i)) {
selectedItems.add(adapter.getItem(position));
}
}
Log.d(TAG, "Page key array show :" + this.pageKeyArray);
Log.d(TAG, "selectedItems show :" + selectedItems);
int max = -1;
for(String value: selectedItems) {
int selectedIndex= this.pageArray.indexOf(value);
this.selectedPageIems.add(this.pageKeyArray.get(selectedIndex));
if(selectedIndex > max) {
max = selectedIndex;
}
}
String firstPageNumber = getFirstPageNumber(this.pageKeyArray.get(0));
String currentPageNumber = firstPageNumber;
String lastPageNumber = getLastPageNumber(this.pageKeyArray.get(max));
Log.d(TAG, "First Page Number :" + firstPageNumber);
Log.d(TAG, "Last Page Number :" + lastPageNumber);
Log.d(TAG, "selectedPageIndexes show :" + selectedPageIndexes);
Log.d(TAG, "selectedPageIems show :" + selectedPageIems);
String[] outputStrArr = new String[selectedItems.size()];
for (int i = 0; i < selectedItems.size(); i++) {
outputStrArr[i] = selectedItems.get(i);
}
try {
selectPages();
} catch (JSONException e) {
e.printStackTrace();
}
Intent intent = new Intent(getApplicationContext(),MyBookings.class);
session.setPageNumbers(firstPageNumber,currentPageNumber,lastPageNumber);
startActivity(intent);
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "First Page Number :" + position);
for (int i=0; i<=position; i++){
listView.setItemChecked(i,true);
}
}
You check the checkboxes each time you press an item ?
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
Log.d(TAG, "First Page Number :" + position);
for (int i=0; i<=position; i++){
listView.setItemChecked(i,true);
}
}
I don't see setItemChecked(i,false) anywhere

Android ListView not refreshing after notifyDataSetChanged is called

I have struggled to load more items on listview after calling notifyDataSetChanged() method
Here is the code block for setting user scroll action on listview
lv = (ListView) getActivity().findViewById(R.id.list);
adapter = new ItemListAdapter(getActivity(), getList(), 2);
progressDialog.show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
lv.setAdapter(adapter);
progressDialog.dismiss();
adapter.notifyDataSetChanged();
}
}, SPLASH_TIME_OUT);
lv.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
userScrolled = true;
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (userScrolled) {
userScrolled = false;
progressDialog.getWindow().setGravity(Gravity.BOTTOM);
progressDialog.show();
updateListView();
}
}
});
And here is my updateListView method:
private void updateListView() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (appPreference.getLoadStatus().equals("0")) {
for (int i = 0; i < getListMore().size(); i++) {
Log.i("MORE VALUES", "" + getListMore().get(i));
getList().add(getListMore().get(i));
}
appPreference.saveLoadStatus("1");
}
progressDialog.dismiss();
adapter.notifyDataSetChanged();
}
}, 100);
}
Here is my getList() method
public List<ItemList> getList() {
ContentResolver cr = getActivity().getContentResolver();
String where = Products.SYNCSTATUS + " != 3";
Cursor c = cr.query(Products.BASEURI, null, where, null, Products.ID + " DESC");
list = new ArrayList<ItemList>();
try {
if (c.getCount() > 0) {
c.moveToFirst();
do {
int colN = c.getColumnIndex(Products.PRODUCT);
int colP = c.getColumnIndex(Products.ON_HAND);
int colI = c.getColumnIndex(Products.ID);
int colD = c.getColumnIndex(Products.SKU);
int colPr = c.getColumnIndex(Products.PRICE);
int colUp = c.getColumnIndex(Products.UPDATE);
String n = c.getString(colNad);
String p = c.getString(colPle);
long i = c.getLong(colIMEI);
String d = c.getString(colDec);
String pr = c.getString(colProd);
String upd = c.getString(colUpdated);
if (!Validating.areSet(upd))
upd = getString(R.string.strnever);
if (tabletsize) {
list.add(new ItemList(n.toUpperCase(Locale.getDefault()), pr, p, i,
d, upd));
} else {
list.add(new ItemList(getString(R.string.strproduct).toUpperCase(Locale.getDefault()) + ": " +
n.toUpperCase(Locale.getDefault()),
getString(R.string.strprice).toUpperCase(Locale.getDefault()) + ": " +
pr.toUpperCase(Locale.getDefault()),
getString(R.string.strtotalqty).toUpperCase(Locale.getDefault()) + ": " + p, i,
getString(R.string.strsku).toUpperCase(Locale.getDefault()) + ": " + d,
getString(R.string.strlastsell).toUpperCase(Locale.getDefault()) + ": " + upd));
}
} while (c.moveToNext());
} else {
String n = getString(R.string.strnodata).toUpperCase(Locale.getDefault());
String p = " ";
long i = 0;
String d = null;
list.add(new ItemList(n, "", p, i, d));
}
} finally {
if (c != null) {
c.close();
}
}
return list;
}
My intention is to load more items using getListMore() method which load data from database, add them into getList() method which returns List<ItemList>
The problem comes when i scroll the listview there is no new data loaded onto it ,the logs shows the
Log.i("MORE VALUES", "" + getListMore().get(i)); returned the data from database but no data has been shown on listview.
Can anyone help with the issue as why the data is not loaded and how to fix it?
Thanks
Can you try changing:
new Handler().postDelayed(new Runnable() {
to:
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
The method adapter.notifyDataSetChanged(); needs to be called from the main thread only.
You are actually fetching the data, adding it into list with getList() but not setting that list. you probably need to setlist() with new values.
Something like, setList(new updated list here) and then adapter.notifyDataSetChanged()
you need to make getList() more clear, see every time you get getList() and add new item in it, it reinstanitate the list, add the old items in it which you have added veru first time. better to make a change the method something like this.
public List<ItemList> getList() {
if(list != null || list.size() > 0) {
return list;
}
ContentResolver cr = getActivity().getContentResolver();
String where = Products.SYNCSTATUS + " != 3";
Cursor c = cr.query(Products.BASEURI, null, where, null, Products.ID + " DESC");
list = new ArrayList<ItemList>();
try {
if (c.getCount() > 0) {
c.moveToFirst();
do {
int colN = c.getColumnIndex(Products.PRODUCT);
int colP = c.getColumnIndex(Products.ON_HAND);
int colI = c.getColumnIndex(Products.ID);
int colD = c.getColumnIndex(Products.SKU);
int colPr = c.getColumnIndex(Products.PRICE);
int colUp = c.getColumnIndex(Products.UPDATE);
String n = c.getString(colNad);
String p = c.getString(colPle);
long i = c.getLong(colIMEI);
String d = c.getString(colDec);
String pr = c.getString(colProd);
String upd = c.getString(colUpdated);
if (!Validating.areSet(upd))
upd = getString(R.string.strnever);
if (tabletsize) {
list.add(new ItemList(n.toUpperCase(Locale.getDefault()), pr, p, i,
d, upd));
} else {
list.add(new ItemList(getString(R.string.strproduct).toUpperCase(Locale.getDefault()) + ": " +
n.toUpperCase(Locale.getDefault()),
getString(R.string.strprice).toUpperCase(Locale.getDefault()) + ": " +
pr.toUpperCase(Locale.getDefault()),
getString(R.string.strtotalqty).toUpperCase(Locale.getDefault()) + ": " + p, i,
getString(R.string.strsku).toUpperCase(Locale.getDefault()) + ": " + d,
getString(R.string.strlastsell).toUpperCase(Locale.getDefault()) + ": " + upd));
}
} while (c.moveToNext());
} else {
String n = getString(R.string.strnodata).toUpperCase(Locale.getDefault());
String p = " ";
long i = 0;
String d = null;
list.add(new ItemList(n, "", p, i, d));
}
} finally {
if (c != null) {
c.close();
}
}
return list;
}

NotifyDataSetChanged not working in arraylist using autocompletetextview in android

I want to update State list according to the country type in autocompletetextview. I have used the below code .It is working fine for the first time .I write country but once i edit the country name .It is not updating the state list(used notifyDataSetChanged but its not working).Please check the code .Thanks!
AutoCompleteTextView country_edit,state_edit;
for (int i = 1; i < global.getExcel().length; i++) {
String[] separated = global.getExcel()[i].split(",");
code = separated[0]; // this will contain "Fruit"
country = separated[1];
Log.e("length", code + "==" + country);
Log.e("sep", separated + "====" + global.getExcel()[i]);
countrylist.add(country);
codelist.add(code);
Log.e("countrylist", countrylist + "==");
}
//==============================================ArrayAdapter Country & state
final ArrayAdapter<String> country_adapter = new ArrayAdapter<String>
(this, R.layout.custom_autolistview_list, R.id.text1, countrylist);
country_edit.setThreshold(1);
country_edit.setAdapter(country_adapter);
final ArrayAdapter<String> state_adapter = new ArrayAdapter<String>
(this, R.layout.custom_autolistview_list, R.id.text1, State_array);
state_edit.setThreshold(1);
state_edit.setAdapter(state_adapter);
state_edit.setDropDownHeight(WRAP_CONTENT);
state_adapter.notifyDataSetChanged();
country_edit.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Log.e("country", country_edit.getText().toString());
country_str = country_edit.getText().toString();
// Log.e("country", country_str);
int index = countrylist.indexOf(country_str);
Log.e("index", index + "");
String code_index = codelist.get(index);
Log.e("code", code_index);
State_list.clear();
State_array.clear();
for (int i = 0; i < global.getState().length; i++) {
if (global.getState()[i].contains("," + code_index + ",")) {
String statelist = global.getState()[i];
Log.e("statelist", statelist);
State_list.add(statelist);
Log.e("State", State_list + "");
state_name = "";
for (int j = 0; j < State_list.size(); j++) {
String[] statelist_array = State_list.get(j).split(",");
state_name = statelist_array[0];
String state_code = statelist_array[1];
Log.e("state_code", state_code);
Log.e("state_name", state_name);
}
Log.e("Stateeeeeeeee", State_array + "");
State_array.add(state_name);
Log.e("Stateeeeeeeeeeeeeeee", State_array + "");
}
state_ll.setVisibility(View.VISIBLE);
}
state_adapter.notifyDataSetChanged();
}
});

After rotating screen, always first timer beginning a count

Half month i trying fix this problem, its my second solution and i get old error.
My goal is to write a listView with timer in every row with Start and Stop buttons, after rotating screen all timers should work correctly, but how in pre-solution after rotation screen, first position in listview get time last/lower position.
As for link with these two solution i see just logic of getView() method, and i'm on 100% sure that is the main problem.
Can anybody help me with this, i am at an impasse. Problematic piace of code:
if(isItStart.get(position)){
holder.stop.setEnabled(true);
holder.start.setEnabled(false);
handler.postDelayed(updateTimeThread,0);
}
Here is full class.
ListView listView;
MyAdapter adapter;
Handler handler;
SQLiteDatabase db;
List<Tracker> trackerList;
Tracker tracker;
List<Boolean> isItStart,historyIsItStart;
List<Long> startTime,historyStartTime;
List<Long> lastPauseList,historyLastPauseList;
List<Long> updateTimeList, historyUpdateTimeList;
List<Long> daysList,historyDayList;
List<Long> hoursList,historyHoursList;
List<Long> minutesList,historyMinutes;
List<Long> secondsList,historySecondsList;
int trackerCount;
static final String LOG_TAG = "myTag";
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler();
db = RemindMe.db;
trackerList = Tracker.getListAll(db);
trackerCount=trackerList.size();
initLists();
for (int i = 0; i < trackerCount; i++) {
startTime.add(0L);
lastPauseList.add(0L);
updateTimeList.add(0L);
daysList.add(0L);
hoursList.add(0L);
minutesList.add(0L);
secondsList.add(0L);
isItStart.add(false);
historyStartTime.add(startTime.get(i));
historyLastPauseList.add(lastPauseList.get(i));
historyUpdateTimeList.add(updateTimeList.get(i));
historyDayList.add(daysList.get(i));
historyHoursList.add(hoursList.get(i));
historyMinutes.add(minutesList.get(i));
historySecondsList.add(secondsList.get(i));
historyIsItStart.add(isItStart.get(i));
}
listView = (ListView)findViewById(R.id.listView);
String[] from = {Tracker.COL_NAME,Tracker.COL_ELAPSED_TIME,Tracker.COL_ELAPSED_TIME,Tracker.COL_ELAPSED_TIME,Tracker.COL_ELAPSED_TIME};
int[] to = {R.id.tvName,R.id.tvDays,R.id.tvHours,R.id.tvMinutes,R.id.tvSeconds};
adapter = new MyAdapter(this,R.layout.list_item,Tracker.getAll(db),from,to,0);
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
long day,hour,min,sec;
long time = cursor.getLong(columnIndex);
switch(view.getId()){
case R.id.tvDays:
TextView days = (TextView)view;
days.setText("days");
return true;
case R.id.tvHours:
TextView hours = (TextView)view;
hours.setText("hours");
return true;
case R.id.tvMinutes:
TextView minutes = (TextView)view;
minutes.setText("min");
return true;
case R.id.tvSeconds:
TextView seconds = (TextView)view;
if(time!=0){
sec = time/1000;
seconds.setText(String.valueOf(sec));
}else{
seconds.setText("null");
}
return true;
}
return false;
}
});
listView.setAdapter(adapter);
getSupportLoaderManager().initLoader(1,null,this).forceLoad();
}
void initLists(){
startTime = new ArrayList<Long>(trackerCount);
lastPauseList = new ArrayList<Long>(trackerCount);
updateTimeList = new ArrayList<Long>(trackerCount);
daysList = new ArrayList<Long>(trackerCount);
hoursList = new ArrayList<Long>(trackerCount);
minutesList = new ArrayList<Long>(trackerCount);
secondsList = new ArrayList<Long>(trackerCount);
isItStart = new ArrayList<Boolean>(trackerCount);
historySecondsList = new ArrayList<Long>(trackerCount);
historyMinutes = new ArrayList<Long>(trackerCount);
historyHoursList = new ArrayList<Long>(trackerCount);
historyDayList = new ArrayList<Long>(trackerCount);
historyUpdateTimeList = new ArrayList<Long>(trackerCount);
historyLastPauseList = new ArrayList<Long>(trackerCount);
historyStartTime = new ArrayList<Long>(trackerCount);
historyIsItStart = new ArrayList<Boolean>(trackerCount);
}
#Override
public void onClick(View v) {
Intent intent = new Intent(this,AddTrack.class);
startActivity(intent);
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
return new TrackerLoader(this,db);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
adapter.swapCursor(cursor);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}
static class TrackerLoader extends android.support.v4.content.CursorLoader{
SQLiteDatabase db;
TrackerLoader(Context context,SQLiteDatabase db){
super(context);
this.db=db;
}
#Override
public Cursor loadInBackground() {
return Tracker.getAll(db);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.d(LOG_TAG, "onSavedInstanceState---------------------------------------------------------------!");
for (int i = 0; i <trackerCount ; i++) {
historyStartTime.set(i,startTime.get(i));
historyLastPauseList.set(i, lastPauseList.get(i));
historyUpdateTimeList.set(i,updateTimeList.get(i));
historyDayList.set(i, daysList.get(i));
historyHoursList.set(i,hoursList.get(i));
historyMinutes.set(i, minutesList.get(i));
historySecondsList.set(i,secondsList.get(i));
historyIsItStart.set(i, isItStart.get(i));
outState.putSerializable("startTime " + i, historyStartTime.get(i));
outState.putSerializable("lastPause " + i, historyLastPauseList.get(i));
outState.putSerializable("updateTime " + i, historyUpdateTimeList.get(i));
outState.putSerializable("dayList " + i, historyDayList.get(i));
outState.putSerializable("hoursList " + i, historyHoursList.get(i));
outState.putSerializable("minutesList " + i, historyMinutes.get(i));
outState.putSerializable("secondsList " + i, historySecondsList.get(i));
outState.putSerializable("isItStart " + i, historyIsItStart.get(i));
Log.d(LOG_TAG, "startTime " + getTime((Long) outState.getSerializable("startTime " + i)));
Log.d(LOG_TAG, "lastPause " + getTime((Long) outState.getSerializable("lastPause " + i)));
Log.d(LOG_TAG, "updateTime " + getTime((Long) outState.getSerializable("updateTime " + i)));
Log.d(LOG_TAG, "dayList " + getTime((Long) outState.getSerializable("dayList " + i)));
Log.d(LOG_TAG, "hoursList " + getTime((Long) outState.getSerializable("hoursList " + i)));
Log.d(LOG_TAG, "minutesList " + getTime((Long) outState.getSerializable("minutesList " + i)));
Log.d(LOG_TAG, "secondsList " + outState.getSerializable("secondsList " + i));
Log.d(LOG_TAG, "isItStart " + outState.getSerializable("isItStart " + i));
Log.d(LOG_TAG, "position " + i);
Log.d(LOG_TAG,"-----------------------------------!");
}
Log.d(LOG_TAG,"END onSavedInstanceState-------------------------------------------------------------!");
for (int i = 0; i < trackerCount; i++) {
Log.d(LOG_TAG,"secondsList "+i+ " "+secondsList.get(i));
}
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Log.d(LOG_TAG, "onRestoreInstanceState-------------------------------------------------------!");
for (int i = 0; i <trackerCount ; i++) {
historyStartTime.set(i,(Long)savedInstanceState.getSerializable("startTime "+i));
historyLastPauseList.set(i,(Long)savedInstanceState.getSerializable("lastPause "+i));
historyUpdateTimeList.set(i,(Long)savedInstanceState.getSerializable("updateTime "+i));
historyDayList.set(i,(Long)savedInstanceState.getSerializable("dayList "+i));
historyHoursList.set(i,(Long)savedInstanceState.getSerializable("hoursList "+i));
historyMinutes.set(i,(Long)savedInstanceState.getSerializable("minutesList "+i));
historySecondsList.set(i,(Long)savedInstanceState.getSerializable("secondsList "+i));
historyIsItStart.set(i,(Boolean)savedInstanceState.getSerializable("isItStart "+i));
startTime.set(i,historyStartTime.get(i));
lastPauseList.set(i,historyLastPauseList.get(i));
updateTimeList.set(i,historyUpdateTimeList.get(i));
daysList.set(i,historyDayList.get(i));
hoursList.set(i,historyHoursList.get(i));
minutesList.set(i,historyMinutes.get(i));
secondsList.set(i,historySecondsList.get(i));
isItStart.set(i, historyIsItStart.get(i));
Log.d(LOG_TAG, "startTime " + getTime((Long) savedInstanceState.getSerializable("startTime " + i)));
Log.d(LOG_TAG,"lastPause " + getTime((Long) savedInstanceState.getSerializable("lastPause " + i)));
Log.d(LOG_TAG,"updateTime " + getTime((Long) savedInstanceState.getSerializable("updateTime " + i)));
Log.d(LOG_TAG,"dayList " + getTime((Long) savedInstanceState.getSerializable("dayList " + i)));
Log.d(LOG_TAG,"hoursList " + getTime((Long) savedInstanceState.getSerializable("hoursList " + i)));
Log.d(LOG_TAG,"minutesList " + getTime((Long) savedInstanceState.getSerializable("minutesList " + i)));
Log.d(LOG_TAG, "secondsList " + savedInstanceState.getSerializable("secondsList " + i));
Log.d(LOG_TAG,"isItStart "+savedInstanceState.getSerializable("isItStart " + i));
Log.d(LOG_TAG,"position "+i);
Log.d(LOG_TAG,"----------------------------------------------------------------");
}
Log.d(LOG_TAG,"END onRestoreIntstanceState-------------------------------------------------------------!");
}
private class MyAdapter extends SimpleCursorAdapter{
Context context;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
MyAdapter(Context context,int resourceID,Cursor cursor,String[] from,int[]to,int flags){
super(context, resourceID, cursor, from, to, flags);
this.context = context;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View row = convertView;
final ViewHolder holder;
tracker = trackerList.get(position);
if(row==null){
holder = new ViewHolder();
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(R.layout.list_item,parent,false);
holder.name= (TextView)row.findViewById(R.id.tvName);
holder.days = (TextView)row.findViewById(R.id.tvDays);
holder.hours = (TextView)row.findViewById(R.id.tvHours);
holder.minutes = (TextView)row.findViewById(R.id.tvMinutes);
holder.seconds = (TextView)row.findViewById(R.id.tvSeconds);
holder.start = (Button)row.findViewById(R.id.btStart);
holder.stop = (Button)row.findViewById(R.id.btStop);
row.setTag(holder);
}else{
holder = (ViewHolder)row.getTag();
}
holder.start.setEnabled(true);
holder.stop.setEnabled(false);
holder.name.setText(tracker.getName());
final Runnable updateTimeThread = new Runnable() {
#Override
public void run() {
updateTimeList.set(position, (System.currentTimeMillis() - startTime.get(position)) + lastPauseList.get(position));
secondsList.set(position, updateTimeList.get(position) / 1000);
minutesList.set(position, secondsList.get(position) / 60);
hoursList.set(position, minutesList.get(position) / 60);
secondsList.set(position, (secondsList.get(position) % 60));
minutesList.set(position, (minutesList.get(position) % 60));
hoursList.set(position, (hoursList.get(position) % 24));
holder.days.setText(String.format("%04d", daysList.get(position)));
holder.hours.setText(String.format("%02d", hoursList.get(position)));
holder.minutes.setText(String.format("%02d", minutesList.get(position)));
holder.seconds.setText(String.format("%02d", secondsList.get(position)));
handler.postDelayed(this, 0);
}
};
if(isItStart.get(position)){
holder.stop.setEnabled(true);
holder.start.setEnabled(false);
handler.postDelayed(updateTimeThread,0);
}
View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btStart:
startTime.set(position,System.currentTimeMillis());
handler.post(updateTimeThread);
holder.start.setEnabled(false);
holder.stop.setEnabled(true);
isItStart.set(position,true);
break;
case R.id.btStop:
lastPauseList.set(position, updateTimeList.get(position));
handler.removeCallbacks(updateTimeThread);
holder.stop.setEnabled(false);
holder.start.setEnabled(true);
isItStart.set(position,false);
break;
}
}
};
holder.start.setOnClickListener(onClickListener);
holder.stop.setOnClickListener(onClickListener);
return row;
}
class ViewHolder{
TextView name,days,hours,minutes,seconds;
Button start,stop;
}
}
String getTime(long time){
int hours = (int)(time/3600000);
int minutes = (int)(time -hours*3600000)/60000;
int seconds = (int)(time-hours*3600000-minutes*60000)/1000;
String hour = (hours<9?"0"+hours:hours).toString();
String min = (minutes<9?"0"+minutes:minutes).toString();
String sec = (seconds<9?"0"+seconds:seconds).toString();
return ""+hour+":"+min+":"+sec;
}
}
Add android:configChanges="orientation|screenSize" in manifest.xml and delete your onRestore and onSaved.
When you rotating the screen the application refresh the activity i had the same kind of problem so i just locked the screen for one way in the android mainifest by
android:screenOrientation="portrait"
found this great answer by:Xion
"you could distinguish the cases of your activity being created for the first time and being restored from savedInstanceState. This is done by overriding onSaveInstanceState and checking the parameter of onCreate.
You could lock the activity in one orientation by adding android:screenOrientation="portrait" (or "landscape") to in your manifest.
You could tell the system that you meant to handle screen changes for yourself by specifying android:configChanges="orientation" in the tag. This way the activity will not be recreated, but will receive a callback instead (which you can ignore as it's not useful for you)."

Android - When we select checkbox , Spinner need to change

I have checkBox and Spinner. If the checkbox is checked, then spinner should call the database and get the values from there, otherwise default value.
My Problem is :
If CheckBox is checked, Spinner should be called. How to implement this?
My code is :
private HashMap<Integer,ReturnProduct> retrunTypes =new HashMap<Integer, ReturnProduct>();
checkBox1=(CheckBox)findViewById(R.id.checkBox1);
checkBox1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked) {
rtnStatus =true;
retrunTypes = getReturnRason();
}else {
rtnStatus =false;
}
}
});
Spinner:
retrunTypes = getReturnRason();
ArrayList<String> returnTypeList = new ArrayList<String>();
for (Map.Entry<Integer, ReturnProduct> entry : retrunTypes.entrySet()) {
ReturnProduct myProduct = entry.getValue();
returnTypeList.add(myProduct.getDescription());
}
retuReason = (Spinner) findViewById(R.id.retuReason);
reTypeAdapter = new ArrayAdapter<String>(SalesActivityGroup.group.getApplicationContext(),android.R.layout.simple_spinner_item, returnTypeList);
reTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
retuReason.setAdapter(reTypeAdapter);
retuReason.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,int arg2, long arg3) {
//selectedReType = parent.getSelectedItem().toString();
selectedReTypeId= arg2;
selectedReType = retrunTypes.get(selectedReTypeId).getReturnReason();
//ReturnProduct rProduct = findReturnType(selectedReType);
processingRequird = retrunTypes.get(selectedReTypeId).getProcessingRequired();
selectedReTypeCode = selectedReType;
selectedRetCategory = retrunTypes.get(selectedReTypeId).getReturnCategory();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
private HashMap<Integer,ReturnProduct> getReturnRason(){
DBAdapter dbAdapter = DBAdapter.getDBAdapterInstance(this);
HashMap<Integer,ReturnProduct> returnType = new HashMap<Integer, ReturnProduct>();
try {
dbAdapter.openDataBase();
String query ="";
if(rtnStatus) {
query = "SELECT rs.ReturnReasonCode,rs.ReturnType,rs.Description,rt.ProcessingRequired,rt.ReturnCategory " +
" FROM WMReturnReason rs,WMReturnType rt" +
" WHERE rs.ReturnType =rt.ReturnType AND rs.BusinessUnit=? AND Status ='1' AND rt.ProcessingRequired ='1' ";
}else {
query = "SELECT rs.ReturnReasonCode,rs.ReturnType,rs.Description,rt.ProcessingRequired,rt.ReturnCategory " +
" FROM WMReturnReason rs,WMReturnType rt" +
" WHERE rs.ReturnType =rt.ReturnType AND rs.BusinessUnit=? AND Status ='1' ";
}
String[] d = new String[]{strBusinessUnit};
ArrayList<?> stringList = dbAdapter.selectRecordsFromDBList(query, d);
dbAdapter.close();
//System.out.println("===getReturnType=="+stringList.size());
if(stringList.size() > 0){
for (int i = 0; i < stringList.size(); i++) {
ArrayList<?> arrayList = (ArrayList<?>) stringList.get(i);
ArrayList<?> list = arrayList;
ReturnProduct returnProduct = new ReturnProduct();
returnProduct.setReturnReason((String) list.get(0));
returnProduct.setReturnType((String) list.get(1));
returnProduct.setDescription((String) list.get(2));
returnProduct.setProcessingRequired((String) list.get(3));
returnProduct.setReturnCategory((String) list.get(4));
returnType.put(i, returnProduct);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return returnType;
}
You can use spinner.setSelection(pos) inside the setOnCheckedChangeListener. I can see that you have rolled out your own method to get the value from the database. Now based on the value returned just make the selection of your spinner.

Categories

Resources