Activity State not saved - android

I want to save my Activity state while I swipe between activities but I cannot. Some things are saved and the others dont. I think it has to do somehow with the gestureListener I'm impementing but I'm not sure.
When I swipe to a different activity and then back to this one - the AsyncTask is still running and the Handler is still updating the GUI, however, the views I have displaying in this activity and the buttons are all in their initial configuration.
what am I doing wrong?
public class Main extends Activity implements OnClickListener,
SimpleGestureListener {
/** Called when the activity is first created. */
static String checkedIN = "";
private int hoursSum;
private int minutesSum;
static int dayIs;
static String madeSoFar = "";
static int hoursCount = 0;
static String formattedSeconds = "";
static String formattedMinutes = "";
public static NumberFormat formatter = new DecimalFormat("#0.00");
static boolean killcheck = false;
static String time = "";
static Handler mHandler;
private boolean clicked = false;
private boolean wasShift = false;
static String startString;
static String finishString;
private SimpleGestureFilter detector;
private Typeface tf, tf2, roboto;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
// **************** Set Fonts **************
roboto = Typeface.createFromAsset(getAssets(), "fonts/robotothin.ttf");
tf = Typeface.createFromAsset(getAssets(), "fonts/Advert.ttf");
tf2 = Typeface.createFromAsset(getAssets(), "fonts/passion.ttf");
// **************** Gesture implementation ************
detector = new SimpleGestureFilter(this, this);
// **************** Date and Time Objects *************
final Date date = new Date();
final Date today = Calendar.getInstance().getTime();
DateFormat DF = new SimpleDateFormat("dd/MM/yyyy");
final String DateInString = DF.format(today);
String myString = DateFormat.getDateInstance().format(date);
final TextView dateDisplay = (TextView) findViewById(R.id.dateDisplay);
dateDisplay.setText(myString);
final DBAdapter DB = new DBAdapter(this);
// ************* Apply custom fonts ***************
TextView Title = (TextView) findViewById(R.id.textView2);
Title.setTypeface(tf);
final TextView Author = (TextView) findViewById(R.id.textView3);
Author.setTypeface(roboto);
TextView Current = (TextView) findViewById(R.id.textView1);
Current.setTypeface(roboto);
DigitalClock DG = (DigitalClock) findViewById(R.id.digitalClock1);
DG.setTypeface(roboto);
TextView dater = (TextView) findViewById(R.id.date);
dater.setTypeface(roboto);
TextView dateDisp = (TextView) findViewById(R.id.dateDisplay);
dateDisp.setTypeface(roboto);
CheckedTextView CV = (CheckedTextView) findViewById(R.id.radioButton1);
CV.setTypeface(roboto);
// *************************************************//
final Button checkIn = (Button) findViewById(R.id.CheckIn);
checkIn.setTypeface(roboto);
CheckedTextView check = (CheckedTextView) findViewById(R.id.radioButton1);
Boolean enable = false;
check.setEnabled(enable);
mHandler = new Handler() {
public void handleMessage(Message msg) {
time = "Time: " + hoursCount + ":" + formattedMinutes + ":"
+ formattedSeconds + " Money: " + madeSoFar;
Author.setText(time);
}
};
// **************** Click Listener for first Check In Button
checkIn.setOnClickListener(new OnClickListener() {
int startHours;
int startMinutes;
int finishHours;
int finishMinutes;
#Override
public void onClick(View v) {
// Check Out
if (clicked == true) {
killcheck = true;
checkedIN = "Check In";
checkIn.setText(checkedIN);
finishHours = Utility.getHoursTime();
finishMinutes = Utility.getMinutesTime();
finishString = Integer.toString(Utility.getHoursTime())
+ ":" + Integer.toString(Utility.getMinutesTime())
+ " -";
clicked = false;
wasShift = true;
hoursSum = finishHours - startHours;
minutesSum = finishMinutes - startMinutes;
// Check In
} else if (clicked == false) {
checkedIN = "Check Out";
checkIn.setText(checkedIN);
killcheck = false;
new ShiftProgress().execute();
startHours = Utility.getHoursTime();
startMinutes = Utility.getMinutesTime();
startString = Integer.toString(Utility.getHoursTime())
+ ":" + Integer.toString(Utility.getMinutesTime())
+ " -";
String s = "In Shift ";
CheckedTextView radio = (CheckedTextView) findViewById(R.id.radioButton1);
radio.setText(s);
clicked = true;
}
}
});
Button addShift = (Button) findViewById(R.id.addShift);
addShift.setTypeface(tf2);
// **************** On click listener for adding a shift
addShift.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (wasShift == true) {
changeDateToString(DateInString);
DB.open();
final Cursor cursor = DB.getAllShifts();
startManagingCursor(cursor);
cursor.moveToLast();
int count = cursor.getPosition();
final int position = count + 2;
cursor.moveToNext();
GregorianCalendar GC = new GregorianCalendar();
DB.addToDBTotal(DateInString, "Money: " + madeSoFar,
hoursSum, minutesSum,
Utility.getDay(GC.get(Calendar.DAY_OF_WEEK)),
position, startString, finishString);
DBAdapter.close();
wasShift = false;
printAny(getApplicationContext(), "Added to Shifts",
Toast.LENGTH_SHORT);
} else {
printAny(getApplicationContext(), "Please Check In First", Toast.LENGTH_SHORT);
}
}
});
}
// **************** METHOD DECLERATIONS ****
public void viewShifts() {
Intent myIntent = new Intent(Main.this, Shifts.class);
startActivity(myIntent);
}
public void changeDateToString(String s) {
Utility.INSTANCE.setDate(s);
}
public void changeDurationToString(String s) {
Utility.INSTANCE.setDuration(s);
}
public void printAny(Context c, CharSequence s, int i) {
Context context = c;
CharSequence text = s;
final int duration = i;
Toast toast = Toast.makeText(context, text, duration);
toast.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER, 0, 0);
toast.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.exit:
System.exit(1);
DBAdapter.close();
return true;
case R.id.view:
viewShifts();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
#Override
public void onSwipe(int direction) {
Intent intent = new Intent();
switch (direction) {
case SimpleGestureFilter.SWIPE_RIGHT:
intent.setClass(this, Shifts.class);
startActivity(intent);
break;
case SimpleGestureFilter.SWIPE_LEFT:
intent.setClass(this, Shifts.class);
startActivity(intent);
break;
}
}
#Override
public boolean dispatchTouchEvent(MotionEvent me) {
this.detector.onTouchEvent(me);
return super.dispatchTouchEvent(me);
}
#Override
public void onDoubleTap() {
// TODO Auto-generated method stub
}
public class ShiftProgress extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
int count = 0;
int seconds = 0;
int minutesTime = 0;
int minutesCount = 1;
for (;;) {
if (seconds % 60 == 0) {
minutesTime = count / 60;
seconds = 0;
}
if (seconds < 10) {
formattedSeconds = String.format("%02d", seconds);
}
else if (seconds >= 10) {
formattedSeconds = String.valueOf(seconds);
}
if (minutesTime < 10) {
formattedMinutes = String.format("%02d", minutesTime);
}
else if (minutesTime >= 10) {
formattedMinutes = String.valueOf(minutesTime);
}
if (minutesTime % 60 == 0) {
hoursCount = minutesCount / 60;
minutesTime = 0;
}
double sal = 40;
double SEC = 3600;
double salper = count * (sal / SEC);
madeSoFar = String.valueOf(formatter.format(salper));
try {
mHandler.obtainMessage(1).sendToTarget();
Thread.sleep(1000);
seconds++;
count++;
} catch (InterruptedException e) {
e.printStackTrace();
}
if (killcheck) {
break;
}
}
// int length = count /360;
return null;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Long result) {
}
}
#Override
public void onSaveInstanceState() {
// TODO Auto-generated method stub
Toast.makeText(this, "Activity state saved", Toast.LENGTH_LONG);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
checkedIN = savedInstanceState.getString("checkIN");
clicked = savedInstanceState.getBoolean("button");
Toast.makeText(this, "Activity state Restored", Toast.LENGTH_LONG);
}
#Override
public void onPause(Bundle b) {
// TODO Auto-generated method stub
b.putString("checkIN", checkedIN);
b.putBoolean("button", clicked);
Toast.makeText(this, "Activity state saved", Toast.LENGTH_LONG);
super.onPause();
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString("checkIN", checkedIN);
outState.putBoolean("button", clicked);
Toast.makeText(this, "Activity state saved", Toast.LENGTH_LONG);
// etc.
super.onSaveInstanceState(outState);
}
#Override
protected void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Activity is getting killed", Toast.LENGTH_LONG)
.show();
}
}

You should not keep your Async task running in the background when your activity is send to the background. Your activity can be quit at any time so that you wouldn't have a reference to your activity anymore.
Regarding the preservation of state you could have a look at Activity.onRetainNonConfigurationInstance()

Related

Getting ArrayIndexOutofBoundsException in android listview

I am using listview to load data from sqlite when i open the app i could see the following error can anyone tell me what i am doing wrong in the adapter.Even when the app gets started it shows the following error
Database:
public ArrayList<Daybook> getAlldaybookentriesdatewise(int s) {
ArrayList<Daybook> daybookDetails = new ArrayList<Daybook>();
String selectquery = "SELECT date,IFNULL(SUM(amountin),0) as amountin,IFNULL(SUM(amountout),0) as amountout,daybookusertype FROM daybookdetails GROUP BY strftime('%Y-%m-%d',date) ORDER BY strftime('%Y-%m-%d',date) DESC LIMIT " + s + "";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectquery, null);
if (cursor.moveToFirst()) {
do {
Daybook daybookentries = new Daybook();
daybookentries.setDate(cursor.getString(0));
daybookentries.setCashin(cursor.getString(1));
daybookentries.setCashout(cursor.getString(2));
daybookDetails.add(daybookentries);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return daybookDetails;
}
Activity:
public class NewDaybook_Activity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
ListView listview;
FloatingActionButton fabaddnew;
LinearLayout emptyy;
DatabaseHandler databasehandler;
ArrayList<Daybook> daybookcashentries;
Daybook_adapter dadapter;
LoginSession loginSession;
boolean loadingMore = false;
String totaldaybookcount;
int olimit = 2;
int totalcount;
String s;
private Locale mLocale;
private final String[] language = {"en", "ta"};
LinearLayout li_farmer, li_worker, li_vehicle, li_otherexpense, li_buyer, li_general;
RadioGroup rg_filtering;
RadioButton rbtn_farmertrade, rbtn_farmeradvance, rbtn_work, rbtn_workadvance, rbtn_groupwork, rbtn_groupadvance, rbtn_vehicle, rbtn_otherexpense;
AlertDialog alert;
ImageView img_farm, img_buy, img_work, img_veh, img_expense;
TextView tv_farm, tv_buy, tv_work, tv_veh, tv_expense;
public static final int progress_bar_type = 0;
private ProgressDialog pDialog;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav_daybooks);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(R.string.daybook);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View header = navigationView.getHeaderView(0);
TextView tv_balanceamt = (TextView) header.findViewById(R.id.nav_name);
TextView tv_timedate = (TextView) header.findViewById(R.id.tv_dateandtime);
tv_balanceamt.setTextSize(22);
long date = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy ");
String dateString = sdf.format(date);
tv_timedate.setText(dateString);
databasehandler = new DatabaseHandler(getApplicationContext());
String balanceamount = String.valueOf(databasehandler.getdaybookbalanceamt());
Log.e("daybookbalanceamt", String.valueOf(balanceamount));
balanceamount = balanceamount.replaceAll("[\\[\\](){}]", "");
tv_balanceamt.setText("\u20B9" + balanceamount);
initalize();
}
private void initalize() {
loginSession = new LoginSession(getApplicationContext());
loginSession.checkLogin();
databasehandler = new DatabaseHandler(getApplicationContext());
listview = (ListView) findViewById(R.id.list_daybook);
li_general = (LinearLayout) findViewById(R.id.linearLayout2);
li_farmer = (LinearLayout) findViewById(R.id.linear_farmer);
li_worker = (LinearLayout) findViewById(R.id.linear_worker);
li_vehicle = (LinearLayout) findViewById(R.id.linear_vehicle);
li_otherexpense = (LinearLayout) findViewById(R.id.linear_otherexpense);
li_buyer = (LinearLayout) findViewById(R.id.linear_buyers);
fabaddnew = (FloatingActionButton) findViewById(R.id.addnewtransaction);
emptyy = (LinearLayout) findViewById(R.id.empty);
rg_filtering = (RadioGroup) findViewById(R.id.rg_sortdata);
rbtn_farmertrade = (RadioButton) findViewById(R.id.rbtn_farmers);
rbtn_farmeradvance = (RadioButton) findViewById(R.id.rbtn_fadvance);
rbtn_work = (RadioButton) findViewById(R.id.rbtn_work);
rbtn_workadvance = (RadioButton) findViewById(R.id.rbtn_workadvance);
rbtn_groupwork = (RadioButton) findViewById(R.id.rbtn_groupwork);
rbtn_groupadvance = (RadioButton) findViewById(R.id.rbtn_groupadvance);
rbtn_vehicle = (RadioButton) findViewById(R.id.rbtn_vehicle);
rbtn_otherexpense = (RadioButton) findViewById(R.id.rbtn_otherexpense);
img_farm = (ImageView) findViewById(R.id.img_farmer);
img_buy = (ImageView) findViewById(R.id.img_buyer);
img_work = (ImageView) findViewById(R.id.img_worker);
img_veh = (ImageView) findViewById(R.id.img_vehicle);
img_expense = (ImageView) findViewById(R.id.img_otherexpense);
tv_farm = (TextView) findViewById(R.id.tv_farmer);
tv_buy = (TextView) findViewById(R.id.tv_buyer);
tv_work = (TextView) findViewById(R.id.tv_worker);
tv_veh = (TextView) findViewById(R.id.tv_vehicle);
tv_expense = (TextView) findViewById(R.id.tv_otherexpense);
listview.setFastScrollEnabled(true);
new Daybooklistloader().execute();
li_buyer.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
// When you Touch Down
// U can change Text and Image As per your Functionality
li_buyer.setBackgroundColor(Color.parseColor("#FF4081"));
tv_buy.setTextColor(Color.parseColor("#FFFFFF"));
img_buy.setColorFilter(ContextCompat.getColor(NewDaybook_Activity.this, R.color.white));
break;
case MotionEvent.ACTION_UP:
//When you Release the touch
// U can change Text and Image As per your Functionality
startActivity(new Intent(NewDaybook_Activity.this, Activity_BuyerTransaction.class));
NewDaybook_Activity.this.finish();
break;
}
return true;
}
});
li_farmer.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
// When you Touch Down
// U can change Text and Image As per your Functionality
li_farmer.setBackgroundColor(Color.parseColor("#FF4081"));
tv_farm.setTextColor(Color.parseColor("#FFFFFF"));
img_farm.setColorFilter(ContextCompat.getColor(NewDaybook_Activity.this, R.color.white));
startActivity(new Intent(NewDaybook_Activity.this, Farmertrade_Activity.class));
NewDaybook_Activity.this.finish();
break;
case MotionEvent.ACTION_UP:
//When you Release the touch
// U can change Text and Image As per your Functionality
startActivity(new Intent(NewDaybook_Activity.this, Farmertrade_Activity.class));
NewDaybook_Activity.this.finish();
break;
}
return true;
}
});
fabaddnew.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
fabaddnew.setRippleColor(R.drawable.ripple_effect);
startActivity(new Intent(NewDaybook_Activity.this, Activity_AddFastEntryDaybook.class));
NewDaybook_Activity.this.finish();
return true;
}
});
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
startActivity(new Intent(NewDaybook_Activity.this, NewDaybook_Activity.class));
NewDaybook_Activity.this.finish();
} else if (id == R.id.nav_dashboard) {
startActivity(new Intent(NewDaybook_Activity.this, DashboardActivity.class));
NewDaybook_Activity.this.finish();
} else if (id == R.id.nav_buyer) {
startActivity(new Intent(NewDaybook_Activity.this, BuyerListActivity.class));
NewDaybook_Activity.this.finish();
} else if (id == R.id.nav_farmer) {
startActivity(new Intent(NewDaybook_Activity.this, FarmerlistActivity.class));
NewDaybook_Activity.this.finish();
} else if (id == R.id.nav_workers) {
startActivity(new Intent(NewDaybook_Activity.this, WorkerListActivity.class));
NewDaybook_Activity.this.finish();
} else if (id == R.id.nav_vehicles) {
startActivity(new Intent(NewDaybook_Activity.this, VehicleList_activity.class));
NewDaybook_Activity.this.finish();
} else if (id == R.id.nav_otherexpense) {
startActivity(new Intent(NewDaybook_Activity.this, OtherExpenseList.class));
NewDaybook_Activity.this.finish();
} else if (id == R.id.nav_report) {
startActivity(new Intent(NewDaybook_Activity.this, BillBookActivity.class));
NewDaybook_Activity.this.finish();
} else if (id == R.id.nav_settings) {
// startActivity(new Intent(NewDaybook_Activity.this, SettingsActivity.class));
// NewDaybook_Activity.this.finish();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.language)
.setItems(R.array.language, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
setLocale(language[i]);
}
});
AlertDialog dialog = builder.create();
dialog.show();
} else if (id == R.id.nav_logout) {
loginSession.logoutUser();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void setLocale(String lang) {
Log.d("Selected Language is ", lang);
SharedPreferences preferences = getSharedPreferences(MyApplication.PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(MyApplication.PREF_USER_LANGUAGE_KEY, lang).apply();
mLocale = new Locale(lang);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
conf.setLocale(mLocale);
}
res.updateConfiguration(conf, dm);
recreate();
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type:
pDialog = new ProgressDialog(this);
pDialog.setMessage("Processing...");
pDialog.setIndeterminate(true);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setProgressNumberFormat(null);
pDialog.setProgressPercentFormat(null);
pDialog.setCancelable(false);
pDialog.show();
return pDialog;
default:
return null;
}
}
private class Daybooklistloader extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
#Override
protected String doInBackground(String... strings) {
daybookcashentries = new ArrayList<Daybook>();
daybookcashentries = databasehandler.getAlldaybookentriesdatewise(olimit);
return null;
}
#Override
protected void onPostExecute(String j) {
dismissDialog(progress_bar_type);
View footerView = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.activity_footer, null, false);
listview.addFooterView(footerView);
dadapter = new Daybook_adapter(NewDaybook_Activity.this, daybookcashentries);
if (dadapter != null) {
if (dadapter.getCount() > 0) {
emptyy.setVisibility(View.INVISIBLE);
listview.setAdapter(dadapter);
}
} else {
emptyy.setVisibility(View.VISIBLE);
}
final List<String> labels = databasehandler.getTotaldaybookrecord();
for (String s : labels) {
totaldaybookcount = s;
}
totalcount = Integer.parseInt(totaldaybookcount);
listview.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
int btn_initPosY = fabaddnew.getScrollY();
int li_initPosY = li_general.getScrollY();
if (scrollState == SCROLL_STATE_TOUCH_SCROLL) {
dadapter.isScrolling(true);
fabaddnew.animate().cancel();
li_general.animate().cancel();
fabaddnew.animate().translationYBy(150);
li_general.animate().translationYBy(150);
} else {
dadapter.isScrolling(false);
fabaddnew.animate().cancel();
li_general.animate().cancel();
fabaddnew.animate().translationY(btn_initPosY);
li_general.animate().translationY(li_initPosY);
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
dadapter.isScrolling(true);
//what is the bottom item that is visible
int lastInScreen = firstVisibleItem + visibleItemCount;
//is the bottom item visible & not loading more already? Load more!
if ((lastInScreen == totalItemCount) && !(loadingMore)) {
new LoadDataTask().execute();
}
}
});
}
}
private class LoadDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingMore = true;
// showDialog(progress_bar_type);
}
#Override
protected Void doInBackground(Void... params) {
if (isCancelled()) {
return null;
}
Log.e("test2", "reached");
// Simulates a background task
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
Log.e("test3", "starting");
databasehandler = new DatabaseHandler(getApplicationContext());
if (olimit > totalcount) {
// olimit = 1;
// olimit = 2;
} else {
olimit = olimit + 1;
}
daybookcashentries = new ArrayList<Daybook>();
databasehandler = new DatabaseHandler(getApplicationContext());
daybookcashentries = new ArrayList<Daybook>();
String selectquery = "SELECT date,IFNULL(SUM(amountin),0) as amountin,IFNULL(SUM(amountout),0),daybookusertype as amountout FROM daybookdetails GROUP BY strftime('%Y-%m-%d',date) ORDER BY strftime('%Y-%m-%d',date) DESC LIMIT '" + olimit + "'";
SQLiteDatabase db = databasehandler.getReadableDatabase();
Cursor cursor = db.rawQuery(selectquery, null);
if (cursor.moveToFirst()) {
do {
Daybook daybookentries = new Daybook();
daybookentries.setDate(cursor.getString(0));
daybookentries.setCashin(cursor.getString(1));
daybookentries.setCashout(cursor.getString(2));
daybookcashentries.add(daybookentries);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return null;
}
#Override
protected void onPostExecute(Void result) {
dadapter.setTransactionList(daybookcashentries);
loadingMore = false;
// dismissDialog(progress_bar_type);
super.onPostExecute(result);
}
#Override
protected void onCancelled() {
// Notify the loading more operation has finished
loadingMore = false;
}
}
}
Adapter:
public class Daybook_adapter extends BaseAdapter {
Context context;
private ArrayList<Daybook> entriesdaybook;
private ArrayList<Daybooklist> daybooklists = new ArrayList<Daybooklist>();
private boolean isListScrolling;
private LayoutInflater inflater;
public Daybook_adapter(Context context, ArrayList<Daybook> entriesdaybook) {
this.context = context;
this.entriesdaybook = entriesdaybook;
}
#Override
public int getCount() {
return entriesdaybook.size();
}
#Override
public Object getItem(int i) {
return entriesdaybook.get(i);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.model_daybook, null);
final TextView tv_date = (TextView) convertView.findViewById(R.id.tv_daybook_date);
final TextView tv_cashin = (TextView) convertView.findViewById(R.id.tv_daybook_cashin);
final TextView tv_cashout = (TextView) convertView.findViewById(R.id.tv_daybook_cashout);
final TextView tv_totalamt = (TextView) convertView.findViewById(R.id.daybook_total_amt);
final ImageView img_pdf = (ImageView) convertView.findViewById(R.id.img_printpdf);
LinearLayout emptyy = (LinearLayout) convertView.findViewById(R.id.empty);
ExpandableHeightListView daybookdetailviewlist = (ExpandableHeightListView) convertView.findViewById(R.id.detaillist_daybook);
final Daybook m = entriesdaybook.get(position);
String s = m.getDate();
String[] spiliter = s.split("-");
String year = spiliter[0];
String month = spiliter[1];
String date = spiliter[2];
if (month.startsWith("01")) {
tv_date.setText(date + "Jan" + year);
} else if (month.startsWith("02")) {
tv_date.setText(date + "Feb" + year);
} else if (month.startsWith("03")) {
tv_date.setText(date + "Mar" + year);
} else if (month.startsWith("04")) {
tv_date.setText(date + "Apr" + year);
} else if (month.startsWith("05")) {
tv_date.setText(date + "May" + year);
} else if (month.startsWith("06")) {
tv_date.setText(date + "Jun" + year);
} else if (month.startsWith("07")) {
tv_date.setText(date + "Jul" + year);
} else if (month.startsWith("08")) {
tv_date.setText(date + "Aug" + year);
} else if (month.startsWith("09")) {
tv_date.setText(date + "Sep" + year);
} else if (month.startsWith("10")) {
tv_date.setText(date + "Oct" + year);
} else if (month.startsWith("11")) {
tv_date.setText(date + "Nov" + year);
} else if (month.startsWith("12")) {
tv_date.setText(date + "Dec" + year);
}
tv_cashin.setText("\u20B9" + m.getCashin());
tv_cashout.setText("\u20B9" + m.getCashout());
double one = Double.parseDouble(m.getCashin());
double two = Double.parseDouble(m.getCashout());
double three = one + two;
tv_totalamt.setText("\u20B9" + String.valueOf(three));
/* DatabaseHandler databaseHandler = new DatabaseHandler(context);
daybooklists = databaseHandler.getAllDaywisedaybookdetails(s);
for (int i = 0; i < daybooklists.size(); i++) {
try {
Daybooklist_adapter adapter = new Daybooklist_adapter(context, daybooklists);
if (adapter != null) {
if (adapter.getCount() > 0) {
emptyy.setVisibility(View.GONE);
daybookdetailviewlist.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
} else {
daybookdetailviewlist.setEmptyView(emptyy);
}
daybookdetailviewlist.setExpanded(true);
daybookdetailviewlist.setFastScrollEnabled(true);
if (!isListScrolling) {
img_pdf.setEnabled(false);
adapter.isScrolling(true);
} else {
img_pdf.setEnabled(true);
adapter.isScrolling(false);
}
} catch (Exception e) {
e.printStackTrace();
}
}*/
img_pdf.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set title
alertDialogBuilder.setTitle(R.string.app_name);
// set dialog message
alertDialogBuilder
.setMessage("Click yes to Print Report for : " + m.getDate())
.setCancelable(true)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, close
// current activity
Intent pdfreport = new Intent(context, Activity_Daybookpdf.class);
pdfreport.putExtra("date", m.getDate());
context.startActivity(pdfreport);
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
Button nbutton = alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE);
nbutton.setTextColor(context.getResources().getColor(R.color.colorAccent));
Button pbutton = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
pbutton.setBackgroundColor(context.getResources().getColor(R.color.colorAccent));
pbutton.setPadding(0, 10, 10, 0);
pbutton.setTextColor(Color.WHITE);
return false;
}
});
return convertView;
}
public void setTransactionList(ArrayList<Daybook> newList) {
entriesdaybook = newList;
notifyDataSetChanged();
}
public void isScrolling(boolean isScroll) {
isListScrolling = isScroll;
Log.e("scrollcheck", String.valueOf(isListScrolling));
}
Error:
*** Uncaught remote exception! (Exceptions are not yet supported across processes.)
java.lang.ArrayIndexOutOfBoundsException: length=5; index=5
at com.android.internal.os.BatteryStatsImpl.updateAllPhoneStateLocked(BatteryStatsImpl.java:3321)
at com.android.internal.os.BatteryStatsImpl.notePhoneSignalStrengthLocked(BatteryStatsImpl.java:3351)
at com.android.server.am.BatteryStatsService.notePhoneSignalStrength(BatteryStatsService.java:395)
at com.android.server.TelephonyRegistry.broadcastSignalStrengthChanged(TelephonyRegistry.java:1448)
at com.android.server.TelephonyRegistry.notifySignalStrengthForSubscriber(TelephonyRegistry.java:869)
at com.android.internal.telephony.ITelephonyRegistry$Stub.onTransact(ITelephonyRegistry.java:184)
at android.os.Binder.execTransact(Binder.java:451)
The crash logs doesn't seems to be the reason for the crash.
Try cleaning the project and run.
If the issue still exists do disable instant run from the settings and run.
Hope this should get fixes and start running.

Countdown Timer sometime, counts 2 seconds before the actual time

I have tried to make an countdown timer in a list veiw implementation. Each list item has a separate countdown timer that can be started or stopped. However I have noticed that if I add the first timer in list and set its time. When I start the timer it starts two seconds less than the actual time. e.g If I added a count down of 12 seconds. Then it will start counting from 10. But when the countdown is taking place and I add another new timer and set its time, it starts on the exact given time. The new counter starts at the wrong time only when either there is no other counter in the list or when all counters are already stopped and not counting down. Similarly it will only start the right time only when other timers are counting down. Would really appreciate if someone can help me figure out where is the problem. I have been looking at the code for days.
Here's my Adapter class
public class CustomAdapterCounter extends ArrayAdapter<CounterData> {
private final LayoutInflater mInflater;
Context context;
Uri sound = Uri.parse("android.resource://com.tattooalarmclock.free/" + R.raw.counter);
String counterString = "";
private List<ViewHolder> lstHolders;
private List<CounterData> list = new ArrayList<CounterData>();
private Handler mHandler = new Handler();
private Runnable updateRemainingTimeRunnable = new Runnable() {
#Override
public void run() {
synchronized (lstHolders) {
long currentTime = System.currentTimeMillis();
for (ViewHolder holder : lstHolders) {
// if(!holder.counterData.isStopped)
holder.updateTimeRemaining(System.currentTimeMillis());
}
}
}
};
public CustomAdapterCounter(Context context, List<CounterData> l) {
super(context, 0, l);
this.context = context;
lstHolders = new ArrayList<>();
list = l;
mInflater = LayoutInflater.from(context);
for(int i=0; i<list.size(); i++) {
CounterData[] array = list.toArray(new CounterData[list.size()]);
if(!array[i].isStopped)
startUpdateTimer();
}
}
public double getScreenSize() {
DisplayMetrics dm = new DisplayMetrics();
WindowManager windowManager = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
windowManager.getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
int dens = dm.densityDpi;
double wi = (double) width / (double) dens;
double hi = (double) height / (double) dens;
double x = Math.pow(wi, 2);
double y = Math.pow(hi, 2);
double screenInches = Math.sqrt(x + y);
return screenInches;
}
private void startUpdateTimer() {
Timer tmr = new Timer();
tmr.schedule(new TimerTask() {
#Override
public void run() {
mHandler.post(updateRemainingTimeRunnable);
}
}, 1000, 1000);
}
public static <T> List<T> stringToArray(String s, Class<T[]> clazz) {
T[] arr = new Gson().fromJson(s, clazz);
return Arrays.asList(arr); //or return Arrays.asList(new Gson().fromJson(s, clazz)); for a one-liner
}
public boolean getListSharedPreferences() {
SharedPreferences sharedPreferences = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
if (sharedPreferences.getString("CL", null) != null) {
counterString = sharedPreferences.getString("CL", null);
Gson gson = new Gson();
TypeToken<List<CounterData>> token = new TypeToken<List<CounterData>>() {};
list = gson.fromJson(counterString, token.getType());
return true;
}
else
return false;
}
public void saveListSharedPreferences(List counterList) {
Gson gson = new Gson();
counterString = gson.toJson(counterList);
SharedPreferences sharedPreferences = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
sharedPreferences.edit().putString("CL", counterString).commit();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
if(getScreenSize() <= 4 )
convertView = mInflater.inflate(R.layout.list_view_counter_small, parent, false);
else
convertView = mInflater.inflate(R.layout.list_view_item_counter, parent, false);
holder.counterTextView = (TextView) convertView.findViewById(R.id.counterTextView);
holder.stopCounter = (Button) convertView.findViewById(R.id.counterStopInList);
holder.startCounter = (Button) convertView.findViewById(R.id.counterStartInList);
holder.deleteCounter = (Button) convertView.findViewById(R.id.deleteCounter);
convertView.setTag(holder);
synchronized (lstHolders) {
lstHolders.add(holder);
}
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.setData2(getItem(position));
final ViewHolder finalHolder = holder;
holder.stopCounter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
long store = finalHolder.counterData.expirationTime - System.currentTimeMillis();
finalHolder.counterData.isStopped = true;
finalHolder.counterData.expirationTime = store;
finalHolder.stopCounter.setEnabled(false);
finalHolder.stopCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
finalHolder.startCounter.setEnabled(true);
finalHolder.startCounter.getBackground().setColorFilter(null);
list.set(position, finalHolder.counterData);
saveListSharedPreferences(list);
/* if(getListSharedPreferences()) {
System.out.println("List before change in stop button " + list.toString());
list = stringToArray(counterString, CounterData[].class);
list.set(position, finalHolder.counterData);
System.out.println("List before change in stop button " + list.toString());
saveListSharedPreferences(list);
}
else {
System.out.println(list.toString());
list.set(position, finalHolder.counterData);
System.out.println(list.toString());
saveListSharedPreferences(list);
}
*/
}
});
holder.startCounter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finalHolder.counterData.expirationTime = System.currentTimeMillis() + finalHolder.counterData.expirationTime;
finalHolder.counterData.isStopped = false;
//finalHolder.counterData.expirationTime = System.currentTimeMillis() + finalHolder.counterData.expirationTime;
//finalHolder.setData(finalHolder.counterData);
finalHolder.startCounter.setEnabled(true);
finalHolder.startCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
finalHolder.stopCounter.setEnabled(true);
finalHolder.stopCounter.getBackground().setColorFilter(null);
list.set(position, finalHolder.counterData);
saveListSharedPreferences(list);
startUpdateTimer();
/* if(getListSharedPreferences()) {
list = stringToArray(counterString, CounterData[].class);
System.out.println("List before change in start button " + list.toString());
list.set(position, finalHolder.counterData);
System.out.println("List after change in start button " + list.toString());
saveListSharedPreferences(list);
}
else {
list.set(position, finalHolder.counterData);
saveListSharedPreferences(list);
} */
}
});
final ViewHolder finalHolder1 = holder;
holder.deleteCounter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* if(finalHolder1.mediaPlayer.isPlaying()) {
finalHolder.mediaPlayer.stop();
// finalHolder.counterData.isSoundPlayedBefore = true;
} */
list.remove(position);
notifyDataSetChanged();
saveListSharedPreferences(list);
}
});
return convertView;
}
}
class ViewHolder {
public TextView counterTextView;
//public List<Long> l;
CounterData counterData;
Button startCounter;
Button stopCounter;
Button deleteCounter;
boolean stop = false;
long timeDiff;
// Context context;
// MediaPlayer mediaPlayer;
// List<CounterData> counterDataList;
public void setData(CounterData item) {
counterData = item;
updateTimeRemaining(System.currentTimeMillis());
}
public void setData2(CounterData item) {
counterData = item;
updateTimeRemaining(System.currentTimeMillis());
}
public void updateTimeRemaining(long currentTime) {
if (!counterData.isStopped) {
timeDiff = counterData.expirationTime - currentTime;
//System.out.println("Time Diff Inside Method " + timeDiff);
if (timeDiff > 0) {
int seconds = (int) (timeDiff / 1000) % 60;
int minutes = (int) ((timeDiff / (1000 * 60)) % 60);
int hours = (int) TimeUnit.MILLISECONDS.toHours(timeDiff);
counterTextView.setText(hours + "H " + minutes + "M " + seconds + "S");
stopCounter.setEnabled(true);
stopCounter.getBackground().setColorFilter(null);
startCounter.setEnabled(false);
startCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
} else {
counterTextView.setText("Times Up");
startCounter.setEnabled(false);
startCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
stopCounter.setEnabled(false);
stopCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
// Vibrator v = (Vibrator) this.context.getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
// v.vibrate(5000);
/* if(!counterData.isSoundPlayedBefore) {
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayer.stop();
}
});
counterData.isSoundPlayedBefore = true;
if(findIndex(counterData) != -1) {
int index = findIndex(counterData);
counterDataList.set(index,counterData);
saveListSharedPreferences(counterDataList);
}
} */
}
}
else {
long store = counterData.expirationTime + System.currentTimeMillis() - currentTime;
int seconds = (int) (store / 1000) % 60;
int minutes = (int) ((store / (1000 * 60)) % 60);
int hours = (int) TimeUnit.MILLISECONDS.toHours(store);
counterTextView.setText(hours + "H " + minutes + "M " + seconds + "S");
startCounter.setEnabled(true);
startCounter.getBackground().setColorFilter(null);
stopCounter.setEnabled(false);
stopCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
}
}
}
And here's my CounterData class
class CounterData {
long expirationTime;
boolean isStopped;
boolean isSoundPlayedBefore;
int id;
public CounterData(long expirationTime, int id) {
this.expirationTime = expirationTime;
isStopped = true;
isSoundPlayedBefore = false;
this.id = id;
}
public String toString() {
return String.valueOf("Remaining Time: " + TimeUnit.MILLISECONDS.toMinutes(this.expirationTime) + ":" + TimeUnit.MILLISECONDS.toSeconds(this.expirationTime));
}
public void setCounterID(int id) {
this.id = id;
}
public int getCounterID() {
return this.id;
}
}
And I add the time from number pickers of Hour, Minute and Second.
case R.id.counterStartStopButton:
long hour = TimeUnit.HOURS.toMillis(numberPickerHour.getValue());
long minute = TimeUnit.MINUTES.toMillis(numberPickerMinute.getValue());
long second = TimeUnit.SECONDS.toMillis(numberPickerSecond.getValue());
// if(getListSharedPreferences()) {
if(getCounterIDSharedPreferences()) {
counterID = counterID + 1;
list.add(new CounterData(hour + minute + second, counterID));
saveCounterIDSharedPreferences(counterID);
}
else {
counterID = 1;
list.add(new CounterData(hour + minute + second, counterID));
saveCounterIDSharedPreferences(counterID);
}
UPDATE
Here's the shared preferences code
public void saveCounterIDSharedPreferences(int id) {
SharedPreferences sharedPreferences = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
sharedPreferences.edit().putInt("Counter ID123", id).commit();
}
public boolean getCounterIDSharedPreferences() {
SharedPreferences sharedPreferences = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
if (sharedPreferences.getInt("Counter ID123", -1) != -1) {
counterID = sharedPreferences.getInt("Counter ID123", -1);
return true;
}
else
return false;
}
What turned out to work for me was changing the timer task as following:
private void startUpdateTimer() {
Timer tmr = new Timer();
tmr.schedule(new TimerTask() {
#Override
public void run() {
mHandler.post(updateRemainingTimeRunnable);
}
}, 500, 500);
}

Not able to see files while opening file browser using AndroidFileBrowser Library

I am trying to make a File browser for which I am taking help of this library.
Now according their code I am trying to implement, it's opening the desired location in the cell, however I am only able to see directories not files. As instructed I have chosen the option to choose Files only still I am not able to see Files there. Below is the code I am using
Intent fileExploreIntent = new Intent(FileBrowserActivity.INTENT_ACTION_SELECT_DIR,
null, getActivity(), FileBrowserActivity.class
);
startActivityForResult(fileExploreIntent,1);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (requestCode == 1) {
if(resultCode == getActivity().RESULT_OK) {
String newDir = data.getStringExtra(FileBrowserActivity.returnDirectoryParameter);
Toast.makeText( getActivity(), "Received path from file browser:"+newDir, Toast.LENGTH_LONG).show();
} else {//if(resultCode == this.RESULT_OK) {
Toast.makeText( getActivity(),"Received NO result from file browser",Toast.LENGTH_LONG).show();
}//END } else {//if(resultCode == this.RESULT_OK) {
}//if (requestCode == REQUEST_CODE_PICK_FILE_TO_SAVE_INTERNAL) {
super.onActivityResult(requestCode, resultCode, data);
}
Code for FileBrowserActivity is
public class FileBrowserActivity extends Activity {
// Intent Action Constants
public static final String INTENT_ACTION_SELECT_DIR = "com.afixi.xmppclientandroid.SELECT_DIRECTORY_ACTION";
public static final String INTENT_ACTION_SELECT_FILE = "com.afixi.xmppclientandroid.SELECT_FILE_ACTION";
// Intent parameters names constants
public static final String startDirectoryParameter = "com.afixi.xmppclientandroid.directoryPath";
public static final String returnDirectoryParameter = "com.afixi.xmppclientandroid.directoryPathRet";
public static final String returnFileParameter = "com.afixi.xmppclientandroid.filePathRet";
public static final String showCannotReadParameter = "com.afixi.xmppclientandroid.showCannotRead";
public static final String filterExtension = "com.afixi.xmppclientandroid.filterExtension";
// Stores names of traversed directories
ArrayList<String> pathDirsList = new ArrayList<String>();
// Check if the first level of the directory structure is the one showing
// private Boolean firstLvl = true;
private static final String LOGTAG = "F_PATH";
private List<Item> fileList = new ArrayList<Item>();
private File path = null;
private String chosenFile;
// private static final int DIALOG_LOAD_FILE = 1000;
ArrayAdapter<Item> adapter;
private boolean showHiddenFilesAndDirs = true;
private boolean directoryShownIsEmpty = false;
private String filterFileExtension = null;
// Action constants
private static int currentAction = -1;
private static final int SELECT_DIRECTORY = 1;
private static final int SELECT_FILE = 2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// In case of
// ua.com.vassiliev.androidfilebrowser.SELECT_DIRECTORY_ACTION
// Expects com.mburman.fileexplore.directoryPath parameter to
// point to the start folder.
// If empty or null, will start from SDcard root.
setContentView(R.layout.ua_com_vassiliev_filebrowser_layout);
// Set action for this activity
Intent thisInt = this.getIntent();
currentAction = SELECT_DIRECTORY;// This would be a default action in
// case not set by intent
if (thisInt.getAction().equalsIgnoreCase(INTENT_ACTION_SELECT_FILE)) {
Log.d(LOGTAG, "SELECT ACTION - SELECT FILE");
currentAction = SELECT_FILE;
}
showHiddenFilesAndDirs = thisInt.getBooleanExtra(
showCannotReadParameter, true);
filterFileExtension = thisInt.getStringExtra(filterExtension);
setInitialDirectory();
parseDirectoryPath();
loadFileList();
this.createFileListAdapter();
this.initializeButtons();
this.initializeFileListView();
updateCurrentDirectoryTextView();
Log.d(LOGTAG, path.getAbsolutePath());
}
private void setInitialDirectory() {
Intent thisInt = this.getIntent();
String requestedStartDir = thisInt
.getStringExtra(startDirectoryParameter);
if (requestedStartDir != null && requestedStartDir.length() > 0) {// if(requestedStartDir!=null
File tempFile = new File(requestedStartDir);
if (tempFile.isDirectory())
this.path = tempFile;
}// if(requestedStartDir!=null
if (this.path == null) {// No or invalid directory supplied in intent
// parameter
if (Environment.getExternalStorageDirectory().isDirectory()
&& Environment.getExternalStorageDirectory().canRead())
path = Environment.getExternalStorageDirectory();
else
path = new File("/");
}// if(this.path==null) {//No or invalid directory supplied in intent
// parameter
}// private void setInitialDirectory() {
private void parseDirectoryPath() {
pathDirsList.clear();
String pathString = path.getAbsolutePath();
String[] parts = pathString.split("/");
int i = 0;
while (i < parts.length) {
pathDirsList.add(parts[i]);
i++;
}
}
private void initializeButtons() {
Button upDirButton = (Button) this.findViewById(R.id.upDirectoryButton);
upDirButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.d(LOGTAG, "onclick for upDirButton");
loadDirectoryUp();
loadFileList();
adapter.notifyDataSetChanged();
updateCurrentDirectoryTextView();
}
});// upDirButton.setOnClickListener(
Button selectFolderButton = (Button) this
.findViewById(R.id.selectCurrentDirectoryButton);
if (currentAction == SELECT_DIRECTORY) {
selectFolderButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.d(LOGTAG, "onclick for selectFolderButton");
returnDirectoryFinishActivity();
}
});
} else {// if(currentAction == this.SELECT_DIRECTORY) {
selectFolderButton.setVisibility(View.GONE);
}// } else {//if(currentAction == this.SELECT_DIRECTORY) {
}// private void initializeButtons() {
private void loadDirectoryUp() {
// present directory removed from list
String s = pathDirsList.remove(pathDirsList.size() - 1);
// path modified to exclude present directory
path = new File(path.toString().substring(0,
path.toString().lastIndexOf(s)));
fileList.clear();
}
private void updateCurrentDirectoryTextView() {
int i = 0;
String curDirString = "";
while (i < pathDirsList.size()) {
curDirString += pathDirsList.get(i) + "/";
i++;
}
if (pathDirsList.size() == 0) {
((Button) this.findViewById(R.id.upDirectoryButton))
.setEnabled(false);
curDirString = "/";
} else
((Button) this.findViewById(R.id.upDirectoryButton))
.setEnabled(true);
long freeSpace = getFreeSpace(curDirString);
String formattedSpaceString = formatBytes(freeSpace);
if (freeSpace == 0) {
Log.d(LOGTAG, "NO FREE SPACE");
File currentDir = new File(curDirString);
if(!currentDir.canWrite())
formattedSpaceString = "NON Writable";
}
((Button) this.findViewById(R.id.selectCurrentDirectoryButton))
.setText("Select\n[" + formattedSpaceString
+ "]");
((TextView) this.findViewById(R.id.currentDirectoryTextView))
.setText("Current directory: " + curDirString);
}// END private void updateCurrentDirectoryTextView() {
private void showToast(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
private void initializeFileListView() {
ListView lView = (ListView) this.findViewById(R.id.fileListView);
lView.setBackgroundColor(Color.LTGRAY);
LinearLayout.LayoutParams lParam = new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
lParam.setMargins(15, 5, 15, 5);
lView.setAdapter(this.adapter);
lView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
chosenFile = fileList.get(position).file;
File sel = new File(path + "/" + chosenFile);
Log.d(LOGTAG, "Clicked:" + chosenFile);
if (sel.isDirectory()) {
if (sel.canRead()) {
// Adds chosen directory to list
pathDirsList.add(chosenFile);
path = new File(sel + "");
Log.d(LOGTAG, "Just reloading the list");
loadFileList();
adapter.notifyDataSetChanged();
updateCurrentDirectoryTextView();
Log.d(LOGTAG, path.getAbsolutePath());
} else {// if(sel.canRead()) {
showToast("Path does not exist or cannot be read");
}// } else {//if(sel.canRead()) {
}// if (sel.isDirectory()) {
// File picked or an empty directory message clicked
else {// if (sel.isDirectory()) {
Log.d(LOGTAG, "item clicked");
if (!directoryShownIsEmpty) {
Log.d(LOGTAG, "File selected:" + chosenFile);
returnFileFinishActivity(sel.getAbsolutePath());
}
}// else {//if (sel.isDirectory()) {
}// public void onClick(DialogInterface dialog, int which) {
});// lView.setOnClickListener(
}// private void initializeFileListView() {
private void returnDirectoryFinishActivity() {
Intent retIntent = new Intent();
retIntent.putExtra(returnDirectoryParameter, path.getAbsolutePath());
this.setResult(RESULT_OK, retIntent);
this.finish();
}// END private void returnDirectoryFinishActivity() {
private void returnFileFinishActivity(String filePath) {
Intent retIntent = new Intent();
retIntent.putExtra(returnFileParameter, filePath);
this.setResult(RESULT_OK, retIntent);
this.finish();
}// END private void returnDirectoryFinishActivity() {
private void loadFileList() {
try {
path.mkdirs();
} catch (SecurityException e) {
Log.e(LOGTAG, "unable to write on the sd card ");
}
fileList.clear();
if (path.exists() && path.canRead()) {
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String filename) {
File sel = new File(dir, filename);
boolean showReadableFile = showHiddenFilesAndDirs
|| sel.canRead();
// Filters based on whether the file is hidden or not
if (currentAction == SELECT_DIRECTORY) {
return (sel.isDirectory() && showReadableFile);
}
if (currentAction == SELECT_FILE) {
// If it is a file check the extension if provided
if (sel.isFile() && filterFileExtension != null) {
return (showReadableFile && sel.getName().endsWith(
filterFileExtension));
}
return (showReadableFile);
}
return true;
}// public boolean accept(File dir, String filename) {
};// FilenameFilter filter = new FilenameFilter() {
String[] fList = path.list(filter);
this.directoryShownIsEmpty = false;
for (int i = 0; i < fList.length; i++) {
// Convert into file path
File sel = new File(path, fList[i]);
Log.d(LOGTAG,
"File:" + fList[i] + " readable:"
+ (Boolean.valueOf(sel.canRead())).toString());
int drawableID = R.drawable.file_icon;
boolean canRead = sel.canRead();
// Set drawables
if (sel.isDirectory()) {
if (canRead) {
drawableID = R.drawable.folder_icon;
} else {
drawableID = R.drawable.folder_icon_light;
}
}
fileList.add(i, new Item(fList[i], drawableID, canRead));
}// for (int i = 0; i < fList.length; i++) {
if (fileList.size() == 0) {
// Log.d(LOGTAG, "This directory is empty");
this.directoryShownIsEmpty = true;
fileList.add(0, new Item("Directory is empty", -1, true));
} else {// sort non empty list
Collections.sort(fileList, new ItemFileNameComparator());
}
} else {
Log.e(LOGTAG, "path does not exist or cannot be read");
}
// Log.d(TAG, "loadFileList finished");
}// private void loadFileList() {
private void createFileListAdapter() {
adapter = new ArrayAdapter<Item>(this,
android.R.layout.select_dialog_item, android.R.id.text1,
fileList) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// creates view
View view = super.getView(position, convertView, parent);
TextView textView = (TextView) view
.findViewById(android.R.id.text1);
// put the image on the text view
int drawableID = 0;
if (fileList.get(position).icon != -1) {
// If icon == -1, then directory is empty
drawableID = fileList.get(position).icon;
}
textView.setCompoundDrawablesWithIntrinsicBounds(drawableID, 0,
0, 0);
textView.setEllipsize(null);
// add margin between image and text (support various screen
// densities)
// int dp5 = (int) (5 *
// getResources().getDisplayMetrics().density + 0.5f);
int dp3 = (int) (3 * getResources().getDisplayMetrics().density + 0.5f);
// TODO: change next line for empty directory, so text will be
// centered
textView.setCompoundDrawablePadding(dp3);
textView.setBackgroundColor(Color.LTGRAY);
return view;
}// public View getView(int position, View convertView, ViewGroup
};// adapter = new ArrayAdapter<Item>(this,
}// private createFileListAdapter(){
private class Item {
public String file;
public int icon;
public boolean canRead;
public Item(String file, Integer icon, boolean canRead) {
this.file = file;
this.icon = icon;
}
#Override
public String toString() {
return file;
}
}// END private class Item {
private class ItemFileNameComparator implements Comparator<Item> {
public int compare(Item lhs, Item rhs) {
return lhs.file.toLowerCase().compareTo(rhs.file.toLowerCase());
}
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Log.d(LOGTAG, "ORIENTATION_LANDSCAPE");
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
Log.d(LOGTAG, "ORIENTATION_PORTRAIT");
}
// Layout apparently changes itself, only have to provide good onMeasure
// in custom components
// TODO: check with keyboard
// if(newConfig.keyboard == Configuration.KEYBOARDHIDDEN_YES)
}// END public void onConfigurationChanged(Configuration newConfig) {
public static long getFreeSpace(String path) {
StatFs stat = new StatFs(path);
long availSize = (long) stat.getAvailableBlocks()
* (long) stat.getBlockSize();
return availSize;
}// END public static long getFreeSpace(String path) {
public static String formatBytes(long bytes) {
// TODO: add flag to which part is needed (e.g. GB, MB, KB or bytes)
String retStr = "";
// One binary gigabyte equals 1,073,741,824 bytes.
if (bytes > 1073741824) {// Add GB
long gbs = bytes / 1073741824;
retStr += (new Long(gbs)).toString() + "GB ";
bytes = bytes - (gbs * 1073741824);
}
// One MB - 1048576 bytes
if (bytes > 1048576) {// Add GB
long mbs = bytes / 1048576;
retStr += (new Long(mbs)).toString() + "MB ";
bytes = bytes - (mbs * 1048576);
}
if (bytes > 1024) {
long kbs = bytes / 1024;
retStr += (new Long(kbs)).toString() + "KB";
bytes = bytes - (kbs * 1024);
} else
retStr += (new Long(bytes)).toString() + " bytes";
return retStr;
}// public static String formatBytes(long bytes){
}// END public class FileBrowserActivity extends Activity {

xml not showing checkbox prechecked

i have create an app in which,i want to show the checkbox prechecked with the help of xml,and after that user can checked or uncheked the checkbox,but xaml is not showing it checked on start of the app in device,what is the problem.please advise.
MainActivity
public class File_Selecter extends Activity implements OnItemClickListener {
EditText edDelimiter, edqualifier, edcolumn, edrow;
ListView list;
StringBuilder addition = new StringBuilder();
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();
ArrayList<String> list3 = new ArrayList<String>();
ArrayList<String> phno0 = new ArrayList<String>();
private Button btnsave;
String str;
int t;
int count = 0;
String[] BreakData, roz;
TextView textnum;
static String fileinfo;
static StringBuilder conct = new StringBuilder();
static int ResultCode = 12;
String name = "", number = "";
MyAdapter ma;
String fin = "";
String[] cellArray;
String[] art = null;;
String pathname = Environment.getExternalStorageDirectory()
.getAbsolutePath();
static String contacts = "";
static String mixer;
static String delimiter, qulifier;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_file);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
ColorDrawable colorDrawable = new ColorDrawable(
Color.parseColor("#00aef0"));
actionBar.setBackgroundDrawable(colorDrawable);
Intent itadd = new Intent();
// edittext name
// final String name=itadd.getStringExtra("name").toString();
textnum = (TextView) findViewById(R.id.textnum1);
list = (ListView) findViewById(R.id.listview);
ma = new MyAdapter();
list.setAdapter(ma);
// list.setOnItemClickListener(this);
// list.setItemsCanFocus(false);
// list.setTextFilterEnabled(true);
edDelimiter = (EditText) findViewById(R.id.edDelimiter);
edcolumn = (EditText) findViewById(R.id.edcoloumns);
edrow = (EditText) findViewById(R.id.edrow);
edqualifier = (EditText) findViewById(R.id.edqualifier);
// edittext number
// final String number=itadd.getStringExtra("number").toString();
edDelimiter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
edDelimiter.setError(null);
}
});
if(fileinfo!=null){
//Toast.makeText(getApplication(),
//fileinfo.toString(), Toast.LENGTH_LONG)
//.show();
if (delimiter != null){
edDelimiter.setText( SmsSend
.delim1.toString());
qulifier= SmsSend
.qulifier.toString(); }
ToRead(fileinfo);
// contacts from smssend
contacts = SmsSend.contacts1;
if (SmsSend.contacts1 != null) {
cellArray = contacts.split(";");
if(list2.size() != 0){
for (int i = 0; i < cellArray.length; i++) {
for (int j = 0; j < list2.size(); j++) {
if (list2.get(j).contains(cellArray[i])) {
//ma.setChecked(j, true);
break;
}}}}
else{
for (int i = 0; i < cellArray.length; i++) {
for (int j = 0; j < list1.size(); j++) {
if (list1.get(j).contains(cellArray[i])) {
//ma.setChecked(j, true);
break;
}
}
}
}
}
}
// button1
btnsave = (Button) findViewById(R.id.btnsave);
btnsave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(edDelimiter.getText().toString().length()== 0){
edDelimiter.setError("Delimiter ir required");
}
if(File_Explorer.fileSizeInMB <= 1){
ToRead(fileinfo);
//finish();
}else{
Toast.makeText(getApplication(), "file size is too large", Toast.LENGTH_LONG).show();
}
}
});
}
public void ToRead(String fileinfo) {
if (fileinfo != null) {
delimiter = edDelimiter.getText().toString();
// Toast.makeText(getApplication(), delimiter, Toast.LENGTH_LONG).show();
//delim=":";
qulifier = edqualifier.getText().toString();
//Toast.makeText(getApplication(), qulifier.toString(), Toast.LENGTH_LONG).show();
// qulifier="\\";
// finish();
mixer = qulifier + delimiter;
BreakData = fileinfo.split(mixer);
str = edrow.getText().toString().trim();
try {
t = Integer.parseInt(str);
} catch (NumberFormatException nfe) {
// Handle parse error.
}
if (BreakData != null) {
// String t2= (String.valueOf(t));
if (File_Explorer.fileExtension.equals("vcf")) {
if (!(String.valueOf(t)).equals("0")) {
if (t > BreakData.length) {
Toast.makeText(getApplication(),
"Data is less then entered rows",
Toast.LENGTH_LONG).show();
Arrays.fill(BreakData, null);
Toast.makeText(getApplication(),
"empty.................", Toast.LENGTH_LONG)
.show();
} else {
for (int i = 0; i < BreakData.length; i++) {
if (BreakData[i].contains("FN")) {
art = BreakData[i + 1].split("\n");
name = art[0].toString();
} else if (BreakData[i].contains("TEL;CELL")) {
roz = BreakData[i + 1].split("\n");
number = roz[0].toString();
fin = name.toString() + "\n" + "\n"
+ number.toString();
list2.add(fin.toString());
}
}
for (int a = 0; a < list2.size() && a < t; a++) {
list1.add(list2.get(a).toString());
}
}
textnum.setText(Integer.toString(list1.size()));
}
else {
for (int i = 0; i < BreakData.length; i++) {
if (BreakData[i].contains("FN")) {
art = BreakData[i + 1].split("\n");
name = art[0].toString();
} else if (BreakData[i].contains("TEL;CELL")) {
roz = BreakData[i + 1].split("\n");
number = roz[0].toString();
fin = name.toString() + "\n" + "\n"
+ number.toString();
list1.add(fin.toString());
}
}
textnum.setText(Integer.toString(list1.size()));
}
} else {
if (!(String.valueOf(t)).equals("0")) {
if (t > BreakData.length) {
Toast.makeText(getApplication(),
"Data is less then entered rows",
Toast.LENGTH_LONG).show();
Arrays.fill(BreakData, null);
Toast.makeText(getApplication(),
"empty.................", Toast.LENGTH_LONG)
.show();
} else {
for (int i = 0; i < BreakData.length && i < t; i++) {
list1.add(BreakData[i].toString());
}
textnum.setText(Integer.toString(t));
}
}
else {
for (int i = 0; i < BreakData.length; i++) {
list1.add(BreakData[i].toString());
//t = i;
}
textnum.setText(Integer.toString(BreakData.length));
}
}
}
}
list.setAdapter(ma);
// fileinfo= null;
//edDelimiter.setText(null);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
StringBuilder checkedcontacts = new StringBuilder();
System.out.println(".............." + ma.mCheckStates.size());
for (int i = 0; i < list1.size(); i++)
{
if (ma.mCheckStates.get(i) == false) {
// Toast.makeText(getApplication(), "hiii",
// Toast.LENGTH_LONG).show();
StringTokenizer st1 = new StringTokenizer(list1.get(i)
.toString(), "\n");
String first = st1.nextToken();
String second = st1.nextToken();
phno0.add(second.toString());
checkedcontacts.append(list1.get(i).toString());
checkedcontacts.append("\n");
} else {
System.out.println("..Not Checked......"
+ list1.get(i).toString());
}
}
//Toast.makeText(getApplication(), phno0.toString(), Toast.LENGTH_LONG).show();
Intent returnIntent = new Intent();
returnIntent.putStringArrayListExtra("extermal_name", phno0);
setResult(RESULT_OK, returnIntent);
finish();
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
ma.toggle(arg2);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.add_button, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.attachments:
fileinfo = null;
Intent i = new Intent(File_Selecter.this, File_Explorer.class);
startActivityForResult(i, ResultCode);
break;
case android.R.id.home:
// app icon in action bar clicked; go home
StringBuilder checkedcontacts = new StringBuilder();
System.out.println(".............." + ma.mCheckStates.size());
for (int j = 0; j < list1.size(); j++)
{
if (ma.mCheckStates.get(j) == true) {
StringTokenizer st1 = new StringTokenizer(list1.get(j)
.toString(), "\n");
String first = st1.nextToken();
String second = st1.nextToken();
phno0.add(second.toString());
checkedcontacts.append(list1.get(j).toString());
checkedcontacts.append("\n");
} else {
System.out.println("..Not Checked......"
+ list1.get(j).toString());
}
}
Intent returnIntent = new Intent();
returnIntent.putStringArrayListExtra("extermal_name", phno0);
setResult(RESULT_OK, returnIntent);
finish();
break;
}
return super.onOptionsItemSelected(item);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ResultCode) {
if (resultCode == RESULT_OK) {
fileinfo = data.getStringExtra("name");
}
// list.setAdapter(ma);
}
if (resultCode == RESULT_CANCELED) {
}
}
AdapterCLass
class MyAdapter extends BaseAdapter implements
CompoundButton.OnCheckedChangeListener {
public SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView tv1, tv;
CheckBox cb;
MyAdapter() {
mCheckStates = new SparseBooleanArray(list1.size());
mInflater = (LayoutInflater) File_Selecter.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
// Save ListView state
#Override
public int getCount() {
// TODO Auto-generated method stub
return list1.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
View vi = convertView;
if (convertView == null)
vi = mInflater.inflate(R.layout.row, null);
tv = (TextView) vi.findViewById(R.id.textView1);
// tv1 = (TextView) vi.findViewById(R.id.textView2);
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
tv.setText(list1.get(position));
// tv1.setText(phno1.get(position));
cb.setTag(position);
//cb.setChecked(mCheckStates.get(position, true));
cb.setOnCheckedChangeListener(this);
return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
notifyDataSetChanged();
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
}
row.layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="15dp"
android:ems="20"
android:text="TextView"
android:textColor="#0082e6" />
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:checked="true"
android:layout_marginBottom="5dp"
android:layout_marginRight="22dp"
android:layout_marginTop="5dp" />
</RelativeLayout>

ListView button at position not clicked proper click in android

I displayed the list item using a custom Baseadapter class. My problem is, when I click on the listview button at the position 1, the button at position other is also clicked.but i downloaded video in back progress completelty.but listview display not properly . How do I overcome this problem?
Here is my code:
public class TestHopeListNew extends Activity {
ListView lv;
ArrayList<Url_Dto> list = new ArrayList<Url_Dto>();
MyListAdapter adtf;
public static String prf_date_view = "";
String str_start;
Button all_detail;
Button accepted_all, mainDownloadBtn;
public static SQLiteDatabase db;
String name;
File download;
int i = 0;
private ArrayList<ProgressBarSeek> progreeSeekList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_hope_list_new);
progreeSeekList = new ArrayList<ProgressBarSeek>();
list = DBAdapter.getUrl_Detail();
Log.v("log_tag", "list :: " + list.size());
lv = (ListView) findViewById(R.id.main_list_meet);
mainDownloadBtn = (Button) findViewById(R.id.not_shown);
adtf = new MyListAdapter(this);
lv.setAdapter(adtf);
adtf.notifyDataSetChanged();
SqliteAdpter dba = SqliteAdpter
.getAdapterInstance(getApplicationContext());
dba.createdatabase();
db = dba.openDataBase();
mainDownloadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
adtf.setAllDownload();
}
});
}
public class MyListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
ProgressBar pr;
ProgressBar[] prArray = new ProgressBar[list.size()];
Button cl, dl;
ImageView im;
DownloadFileFromURL downloadFileFromURL;
ViewHolder holder = null;
public MyListAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return list.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public void setAllDownload() {
if (prArray.length > 0) {
for (int i = 0; i < prArray.length; i++) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.v("log_tag", "list.get(i).url_video "
+ list.get(i).url_video);
downloadFileFromURL = new DownloadFileFromURL(dl, cl);
downloadFileFromURL.execute(pr, list.get(i).url_video, i);
}
}
}
private class ViewHolder {
public Button cl;
public Button dl;
public ProgressBar pr;
public ImageView im;
};
public View getView(final int position, View convertView,
ViewGroup parent) {
/*convertView = mInflater.inflate(R.layout.custome_list_view, null);
cl = (Button) convertView.findViewById(R.id.cancle_sedual);
dl = (Button) convertView.findViewById(R.id.download_sedual);
pr = (ProgressBar) convertView.findViewById(R.id.listprogressbar);
prArray[position] = pr;
im = (ImageView) convertView.findViewById(R.id.list_image);
im.setImageResource(list.get(position).images[position]);*/
//final ViewHolder holder = null;
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.custome_list_view,
null);
holder = new ViewHolder();
prArray[position] = pr;
holder.cl = (Button) convertView
.findViewById(R.id.cancle_sedual);
holder.dl = (Button) convertView
.findViewById(R.id.download_sedual);
holder.pr = (ProgressBar) convertView
.findViewById(R.id.listprogressbar);
holder.im = (ImageView) convertView
.findViewById(R.id.list_image);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.im.setImageResource(list.get(position).images[position]);
// pr.setProgress(getItem(position));
holder.cl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v("log_tag", "Cancle Button Click");
holder.dl.setVisibility(View.VISIBLE);
holder.cl.setVisibility(View.GONE);
//downloadFileFromURL = new DownloadFileFromURL(dl, cl);
downloadFileFromURL.cancel(true);
downloadFileFromURL.downloadFile();
holder.pr.setProgress(0);
notifyDataSetChanged();
}
});
holder.dl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.dl.setFocusable(false);
str_start = list.get(position).url_video;
holder.dl.setVisibility(View.GONE);
holder.cl.setVisibility(View.VISIBLE);
Log.v("log_tag", "Start Button Click ");
// new DownloadFileFromURL().execute(str_start);
downloadFileFromURL = new DownloadFileFromURL(holder.dl, holder.cl);
downloadFileFromURL.execute(holder.pr, str_start, position);
notifyDataSetChanged();
}
});
getProgress(holder.pr, position, holder.dl, holder.cl);
// convertView.setTag(holder);
return convertView;
}
}
class DownloadFileFromURL extends AsyncTask<Object, String, Integer> {
int count = 0;
ProgressDialog dialog;
ProgressBar progressBar;
int myProgress;
int position;
Button start, cancel;
boolean download1 = false;
public DownloadFileFromURL(Button start, Button cancel) {
this.start = start;
this.cancel = cancel;
}
/**
* Before starting background thread Show Progress Bar Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
ProgressBar progressBar;
download1 = true;
}
public void downloadFile() {
this.download1 = false;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
/**
* Downloading file in background thread
* */
#Override
protected Integer doInBackground(Object... params) {
int count;
progressBar = (ProgressBar) params[0];
position = (Integer) params[2];
try {
URL url = new URL((String) params[1]);
name = ((String) params[1]).substring(((String) params[1])
.lastIndexOf("/") + 1);
// Log.v("log_tag", "name Substring ::: " + name);
URLConnection conection = url.openConnection();
conection.setConnectTimeout(2000);
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(),
8192);
download = new File(Environment.getExternalStorageDirectory()
+ "/download/");
if (!download.exists()) {
download.mkdir();
}
String strDownloaDuRL = download + "/" + name;
Log.v("log_tag", " down url " + strDownloaDuRL);
FileOutputStream output = new FileOutputStream(strDownloaDuRL);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
if (this.download1) {
if(isCancelled()){
break;
}
total += count;
// writing data to file
progressBar
.setProgress((int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
setProgress(progressBar, position, start, cancel, this);
} else {
File delete = new File(strDownloaDuRL);
delete.delete();
}
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return 0;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
// Log.v("log_tag", "progress :: " + values);
// setting progress percentage
// pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
Log.v("log", "login ::: 4::: " + download);
String videoPath = download + "/" + name;
String chpName = name;
Log.v("log_tag", "chpName ::::" + chpName + " videoPath "
+ videoPath);
db.execSQL("insert into videoStatus (chapterNo,videoPath) values(\""
+ chpName + "\",\"" + videoPath + "\" )");
}
}
private void setProgress(final ProgressBar pr, final int position,
final Button Start, final Button cancel,
final DownloadFileFromURL downloadFileFromURL) {
ProgressBarSeek pbarSeek = new ProgressBarSeek();
pbarSeek.setPosition(position);
pbarSeek.setProgressValue(pr.getProgress());
// Log.v("log_tag", position + " progress " + pr.getProgress());
progreeSeekList.add(pbarSeek);
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v("log_tag", "Cancle Button Click Set progress");
Start.setVisibility(View.VISIBLE);
cancel.setVisibility(View.GONE);
downloadFileFromURL.cancel(true);
downloadFileFromURL.downloadFile();
pr.setProgress(0);
}
});
Start.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v("log_tag", "Start Button Click set Progress");
str_start = list.get(position).url_video;
Start.setVisibility(View.GONE);
cancel.setVisibility(View.VISIBLE);
Log.v("log_tag", "str_start " + str_start);
//
// new DownloadFileFromURL().execute(str_start);
DownloadFileFromURL downloadFileFromU = new DownloadFileFromURL(
Start, cancel);
downloadFileFromU.execute(pr, str_start, position);
}
});
}
private void getProgress(ProgressBar pr, int position, Button dl, Button cl) {
if (progreeSeekList.size() > 0) {
for (int j = 0; j < progreeSeekList.size(); j++) {
if (position == progreeSeekList.get(j).getPosition()) {
pr.setProgress(progreeSeekList.get(j).getProgressValue());
dl.setVisibility(View.GONE);
cl.setVisibility(View.VISIBLE);
}
}
}
}
}
i click second button but display other button clickeble but second button background downloading in sd card but display not properly .how to solve it and what is wrong in my code,please helpme!!!

Categories

Resources