getting duplicate objects in json in android - android

I am putting objects in Json but I want only 1 key to be update.Right now it is creating new object every time function is called I want only quantity should get updated if it is already there in json. Please help
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductViewHolder> {
private List<ProductBean> productList ;
static int qtyValues;
static int itemRem = -1;
static int addItem = 1;
static boolean isSKU1;
static boolean isSKU2;
static boolean isSKU;
static int value;
static int totalAmount = 0;
static int totalItems = 0;
SharedPreferences myPrefs;
SharedPreferences.Editor editor;
private final Activity context;
private AQuery aq;
JSONObject jsonObject = new JSONObject();
JSONArray obj = new JSONArray();
ArrayList list = new ArrayList();
public ProductAdapter(Activity context,List<ProductBean> productList){
this.productList = productList;
this.context = context;
isSKU = true;
}
#Override
public int getItemCount() {
return productList.size();
}
#Override
public void onBindViewHolder(final ProductViewHolder holder, final int position) {
myPrefs = context.getSharedPreferences("qty", Context.MODE_PRIVATE);
editor = myPrefs.edit();
aq = new AQuery(context.getApplicationContext());
final ProductBean productBean = productList.get(position);
holder.extratxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.extratxt.setTextColor(Color.BLACK);
holder.extratxt2.setTextColor(Color.GRAY);
holder.extratxt3.setTextColor(Color.GRAY);
holder.extratxt1.setText(productBean.getProductPrice() + "");
isSKU = true;
isSKU1 = false;
isSKU2 = false;
holder.qtyCounter.setText(myPrefs.getInt("product"+productBean.getProductId()+productBean.getSkuId1(),0)+"");
}
});
holder.extratxt2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.extratxt.setTextColor(Color.GRAY);
holder.extratxt2.setTextColor(Color.BLACK);
holder.extratxt3.setTextColor(Color.GRAY);
holder.extratxt1.setText(productBean.getProductPrice2() + "");
isSKU1 = true;
isSKU = false;
isSKU2 = false;
holder.qtyCounter.setText(myPrefs.getInt("product"+productBean.getProductId()+productBean.getSkuId2(),0)+"");
}
});
holder.extratxt3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.extratxt.setTextColor(Color.GRAY);
holder.extratxt2.setTextColor(Color.GRAY);
holder.extratxt3.setTextColor(Color.BLACK);
holder.extratxt1.setText(productBean.getProductPrice3() + "");
isSKU2 = true;
isSKU = false;
isSKU1 = false;
holder.qtyCounter.setText(myPrefs.getInt("product"+productBean.getProductId()+productBean.getSkuId3(),0)+"");
}
});
holder.decreaseQty.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
if(isSKU1 == true) {
if(myPrefs.getInt("product"+productBean.getProductId()+productBean.getSkuId2(),0)>0) {
qtyValues = myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId2(), 0);
qtyValues = qtyValues - 1;
editor.putInt("product" + productBean.getProductId() + productBean.getSkuId2(), qtyValues);
editor.commit();
holder.qtyCounter.setText(myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId2(), 0) + "");
value = 0 - productBean.getProductPrice2();
add(itemRem);
amount(value);
}
}
else if (isSKU2 == true){
if(myPrefs.getInt("product"+productBean.getProductId()+productBean.getSkuId3(),0)>0) {
qtyValues = myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId3(), 0);
qtyValues = qtyValues - 1;
editor.putInt("product" + productBean.getProductId() + productBean.getSkuId3(), qtyValues);
editor.commit();
holder.qtyCounter.setText(myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId3(), 0) + "");
value = 0 - productBean.getProductPrice3();
add(itemRem);
amount(value);
}
}
else{
if(myPrefs.getInt("product"+productBean.getProductId()+productBean.getSkuId1(),0)>0) {
qtyValues = myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId1(), 0);
qtyValues = qtyValues - 1;
editor.putInt("product" + productBean.getProductId() + productBean.getSkuId1(), qtyValues);
editor.commit();
holder.qtyCounter.setText(myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId1(), 0) + "");
value = 0 - productBean.getProductPrice();
add(itemRem);
amount(value);
}
}
}
});
holder.increaseQty.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
if(isSKU1 == true) {
if(myPrefs.getInt("product"+productBean.getProductId() + productBean.getSkuId2(),0)<10) {
qtyValues = myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId2(), 0);
qtyValues = qtyValues + 1;
editor.putInt("product" + productBean.getProductId() + productBean.getSkuId2(), qtyValues);
editor.commit();
holder.qtyCounter.setText(myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId2(), 0) + "");
value = productBean.getProductPrice2();
add(addItem);
amount(value);
setCartItem(productBean.getSkuId2(),myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId2(), 0),productBean.getProductId(),productBean.getDescription() , productBean.getProductName() , productBean.getProductPrice2());
}
}
else if (isSKU2 == true){
if(myPrefs.getInt("product"+productBean.getProductId() + productBean.getSkuId3(),0)<10) {
qtyValues = myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId3(), 0);
qtyValues = qtyValues + 1;
editor.putInt("product" + productBean.getProductId() + productBean.getSkuId3(), qtyValues);
editor.commit();
holder.qtyCounter.setText(myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId3(), 0) + "");
value = productBean.getProductPrice3();
add(addItem);
amount(value);
setCartItem(productBean.getSkuId3(),myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId3(), 0),productBean.getProductId(),productBean.getDescription() , productBean.getProductName() , productBean.getProductPrice3());
}
}
else{
if(myPrefs.getInt("product"+productBean.getProductId() + productBean.getSkuId1(),0)<10) {
qtyValues = myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId1(), 0);
qtyValues = qtyValues + 1;
editor.putInt("product" + productBean.getProductId() + productBean.getSkuId1(), qtyValues);
editor.commit();
holder.qtyCounter.setText(myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId1(), 0) + "");
value = productBean.getProductPrice();
add(addItem);
amount(value);
setCartItem(productBean.getSkuId1(),myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId1(), 0),productBean.getProductId(),productBean.getDescription() , productBean.getProductName() , productBean.getProductPrice());
}
}
}
});
holder.txtTitle.setText(productBean.getProductName());
holder.extratxt.setText(productBean.getSkuId1() + "");
holder.extratxt2.setText(productBean.getSkuId2() + "");
holder.extratxt3.setText(productBean.getSkuId3() + "");
holder.extratxt1.setText(productBean.getProductPrice() + "");
holder.imageView1.setImageResource(R.drawable.rupee);
if(myPrefs.getInt("totalItems", 0)>0){
BeveragesMainActivity.cartTotal.setVisibility(View.VISIBLE);
BeveragesMainActivity.totalPrice.setText("Rs " + myPrefs.getInt("totalAmount", 0) + "");
}
BeveragesMainActivity.cartTotal.setText(myPrefs.getInt("totalItems", 0) + "");
holder.qtyCounter.setText(myPrefs.getInt("product"+productBean.getProductId()+productBean.getSkuId1(),0) + "");
}
#Override
public ProductViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View itemView = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.list_beverages_item, viewGroup, false);
return new ProductViewHolder(itemView);
}
public class ProductViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView extratxt;
TextView extratxt2;
TextView extratxt3;
ImageView imageView1;
TextView extratxt1;
TextView qtyCounter;
ImageView decreaseQty;
ImageView increaseQty;
/**
* Instantiates a new card view holder.
*
* #param v the v
*/
public ProductViewHolder(View v) {
super(v);
imageView = (ImageView) v.findViewById(R.id.drinks);
txtTitle = (TextView) v.findViewById(R.id.drinkTitle);
extratxt = (TextView) v.findViewById(R.id.drinkQuantity);
extratxt2 = (TextView) v.findViewById(R.id.drinkQuantity1);
extratxt3 = (TextView) v.findViewById(R.id.drinkQuantity2);
imageView1 = (ImageView) v.findViewById(R.id.rupee);
extratxt1 = (TextView) v.findViewById(R.id.drinkPrice);
qtyCounter = (TextView) v.findViewById(R.id.drinkCounter);
decreaseQty = (ImageView) v.findViewById(R.id.decreaseCounter);
increaseQty = (ImageView) v.findViewById(R.id.increaseCounter);
extratxt.setTextColor(Color.BLACK);
}
}
public void setCartItem(final int skuId ,final int qty , final long productId , String description , String productName , int price) {
try {
jsonObject.put("skuId",skuId);
jsonObject.put("quantity",qty);
jsonObject.put("productId",productId);
jsonObject.put("price",price);
jsonObject.put("productName",productName);
jsonObject.put("description",description);
obj.put(jsonObject);
editor.putString("data",obj.toString());
editor.commit();
}catch (JSONException e){
e.printStackTrace();
}
}
public void add(int items){
totalItems = totalItems + items;
editor.putInt("totalItems",totalItems);
editor.commit();
if(myPrefs.getInt("totalItems", 0)>0){
BeveragesMainActivity.cartTotal.setVisibility(View.VISIBLE);
}
else{
BeveragesMainActivity.cartTotal.setVisibility(View.INVISIBLE);
}
BeveragesMainActivity.cartTotal.setText(myPrefs.getInt("totalItems", 0) + "");
}
public void amount(int price){
totalAmount = totalAmount+price;
editor.putInt("totalAmount", totalAmount);
editor.commit();
BeveragesMainActivity.totalPrice.setText("Rs " + myPrefs.getInt("totalAmount", 0) + "");
}
}

Use this code inside setCartItem(...) method
// loop through each object
for (int i = 0; i < obj.length(); i++) {
try {
JSONObject item = obj.getJSONObject(i);
int itemId = item.getInt("skuId ");
if (itemId == skuId) {// object already exists update quantity
item.put("quantity", qty);
// update other keys if you want to
// do other stuff
return;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
JSONObject jsonObject = new JSONObject();
// If skudId does not exits in the array list add new one
try {
jsonObject.put("skuId", skuId);
jsonObject.put("quantity", qty);
jsonObject.put("productId", productId);
jsonObject.put("price", price);
jsonObject.put("productName", productName);
jsonObject.put("description", description);
obj.put(jsonObject);
editor.putString("data", obj.toString());
editor.commit();
} catch (JSONException e) {
e.printStackTrace();
}

Related

How to stop the running timer with EditText?

I'm trying to create an app that shows some questions and EditText fields in front of the each of the question for an answer with CountDownTimer, the problem I have is I'm trying to stop the running CountDownTimer on the last entered answer and save those seconds next to user's name but not sure how? I know questionTimer.cancel() would stop the timer but it has to be done on the last entered answer in last EditText.
This is the MainActivity.java file:
public class MainActivity extends AppCompatActivity {
CountDownTimer questionTimer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStart = (Button) findViewById(R.id.start);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setQuestions();
timer();
}
});
}//End of create()
public void timer() {
questionTimer = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
timer = (TextView) findViewById(R.id.timer);
timer.setText("Seconds Remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
timer.setText("Done!");
}
}.start();
}
public void setQuestions() {
ArrayList<Questions> qArrList = new ArrayList<>();
for (int i = 0; i < 5; i++) {
ques = new Questions();
ques.setQuestion("");
qArrList.add(ques);
}
adapter = new AdapterListView(getBaseContext(), R.layout.item_listview, qArrList);
questListView.setAdapter(adapter);
}
}//End of Class
This is the AdapterListView.java file:
public class AdapterListView extends ArrayAdapter<Questions> {
Context mContext;
LayoutInflater inflater;
private ArrayList<Questions> questionsArrayList;
private Questions quesObject;
private ArrayList<String> quesList = new ArrayList<String>();
private int a, b, ab, c, d, cd, e, f, ef, g, h, gh, i, j, ij;
private ArrayList<Integer> answersList = new ArrayList<Integer>();
public AdapterListView(Context context, int resource, ArrayList<Questions> questionsArrayList) {
super(context, resource);
this.mContext = context;
this.setQuestionsArrayList(questionsArrayList);
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_listview, null);
holder = new ViewHolder();
holder.questionTextView = convertView.findViewById(R.id.question);
holder.editText = convertView.findViewById(R.id.ans_edit_text);
holder.imgTrue = convertView.findViewById(R.id.ans_true);
holder.imgFalse = convertView.findViewById(R.id.ans_false);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
quesObject = getQuestionsArrayList().get(position);
int count = 0;
if (position == 0) count = 1;
else if (position == 1) count = 2;
else if (position == 2) count = 3;
else if (position == 3) count = 4;
else if (position == 4) count = 5;
Random rand = new Random();
a = (rand.nextInt(15) + 1);
b = (rand.nextInt(10) + 1);
ab = a + b;
c = (rand.nextInt(15) + 1);
d = (rand.nextInt(10) + 1);
cd = c + d;
e = (rand.nextInt(15) + 1);
f = (rand.nextInt(10) + 1);
ef = e + f;
g = (rand.nextInt(15) + 1);
h = (rand.nextInt(10) + 1);
gh = g + h;
i = (rand.nextInt(15) + 1);
j = (rand.nextInt(10) + 10);
ij = i + j;
quesList.add(a + " + " + b);
quesList.add(c + " + " + d);
quesList.add(e + " + " + f);
quesList.add(g + " + " + h);
quesList.add(i + " + " + j);
getAnswersList().add(ab);
getAnswersList().add(cd);
getAnswersList().add(ef);
getAnswersList().add(gh);
getAnswersList().add(ij);
holder.questionTextView.setText("Q " + count + ": \t" + quesList.get(position));
holder.editText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
if (holder.editText.getText().toString().trim().length() > 0) {
int inputNum = Integer.parseInt(String.valueOf(holder.editText.getText().toString().trim()));
if (getAnswersList().get(position) != inputNum) {
holder.imgFalse.setVisibility(View.VISIBLE);
holder.imgTrue.setVisibility(View.GONE);
} else {
holder.imgTrue.setVisibility(View.VISIBLE);
holder.imgFalse.setVisibility(View.GONE);
}
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
return convertView;
}
#Override
public int getCount() {
return getQuestionsArrayList().size();
}
static class ViewHolder {
TextView questionTextView;
EditText editText;
ImageView imgTrue, imgFalse;
}
}
I have manged to sort this out by setting an int variable against Position and calling this in MainActivity class inside the running Timer. Please see the code below.
public class MainActivity extends AppCompatActivity {
CountDownTimer questionTimer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStart = (Button) findViewById(R.id.start);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setQuestions();
timer();
}
});
}//End of create()
public void timer() {
questionTimer = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
timer = (TextView) findViewById(R.id.timer);
timer.setText("Seconds Remaining: " + millisUntilFinished / 1000);
if (adapter.getEndQuiz() == 5) {
questionTimer.cancel();
}
}
public void onFinish() {
timer.setText("Done!");
}
}.start();
}
public void setQuestions() {
ArrayList<Questions> qArrList = new ArrayList<>();
for (int i = 0; i < 5; i++) {
ques = new Questions();
ques.setQuestion("");
qArrList.add(ques);
}
adapter = new AdapterListView(getBaseContext(), R.layout.item_listview, qArrList);
questListView.setAdapter(adapter);
}
}//End of Class
Adapter
public class AdapterListView extends ArrayAdapter<Questions> {
Context mContext;
LayoutInflater inflater;
private ArrayList<Questions> questionsArrayList;
private Questions quesObject;
private ArrayList<String> quesList = new ArrayList<String>();
private int a, b, ab, c, d, cd, e, f, ef, g, h, gh, i, j, ij;
private ArrayList<Integer> answersList = new ArrayList<Integer>();
private int endQuiz = 0;
public AdapterListView(Context context, int resource, ArrayList<Questions> questionsArrayList) {
super(context, resource);
this.mContext = context;
this.setQuestionsArrayList(questionsArrayList);
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_listview, null);
holder = new ViewHolder();
holder.questionTextView = convertView.findViewById(R.id.question);
holder.editText = convertView.findViewById(R.id.ans_edit_text);
holder.imgTrue = convertView.findViewById(R.id.ans_true);
holder.imgFalse = convertView.findViewById(R.id.ans_false);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
quesObject = getQuestionsArrayList().get(position);
int count = 0;
if (position == 0) count = 1;
else if (position == 1) count = 2;
else if (position == 2) count = 3;
else if (position == 3) count = 4;
else if (position == 4) count = 5;
Random rand = new Random();
a = (rand.nextInt(15) + 1);
b = (rand.nextInt(10) + 1);
ab = a + b;
c = (rand.nextInt(15) + 1);
d = (rand.nextInt(10) + 1);
cd = c + d;
e = (rand.nextInt(15) + 1);
f = (rand.nextInt(10) + 1);
ef = e + f;
g = (rand.nextInt(15) + 1);
h = (rand.nextInt(10) + 1);
gh = g + h;
i = (rand.nextInt(15) + 1);
j = (rand.nextInt(10) + 10);
ij = i + j;
quesList.add(a + " + " + b);
quesList.add(c + " + " + d);
quesList.add(e + " + " + f);
quesList.add(g + " + " + h);
quesList.add(i + " + " + j);
getAnswersList().add(ab);
getAnswersList().add(cd);
getAnswersList().add(ef);
getAnswersList().add(gh);
getAnswersList().add(ij);
holder.questionTextView.setText("Q " + count + ": \t" + quesList.get(position));
holder.editText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
if (holder.editText.getText().toString().trim().length() > 0) {
int inputNum = Integer.parseInt(String.valueOf(holder.editText.getText().toString().trim()));
if (getAnswersList().get(position) != inputNum) {
holder.imgFalse.setVisibility(View.VISIBLE);
holder.imgTrue.setVisibility(View.GONE);
} else {
holder.imgTrue.setVisibility(View.VISIBLE);
holder.imgFalse.setVisibility(View.GONE);
}
if(position == 0) setEndQuiz(1);
else if(position == 1) setEndQuiz(2);
else if(position == 2) setEndQuiz(3);
else if(position == 3) setEndQuiz(4);
else if(position == 4) setEndQuiz(5);
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
return convertView;
}
#Override
public int getCount() {
return getQuestionsArrayList().size();
}
static class ViewHolder {
TextView questionTextView;
EditText editText;
ImageView imgTrue, imgFalse;
}
}

How to fix Runtime Exception Unable to start Activity

06-28 17:05:23.694 13262-13262/io.hypertrack.sendeta.debug
E/AndroidRuntime: FATAL EXCEPTION: main
Process: io.hypertrack.sendeta.debug, PID: 13262
java.lang.RuntimeException: Unable to start activity ComponentInfo{io.hypertrack.sendeta.debug/io.hypertrack.sendeta.activities.MainActivity}:
android.view.InflateException: Binary XML file line #4: Error
inflating class java.lang.reflect.Constructor
io.hypertrack.sendeta.activities.MainActivity.onCreate(MainActivity.java:109)
public class MainActivity extends AppCompatActivity implements LocationListener {
protected static final int MY_PERMISSIONS_ACCESS_FINE_LOCATION = 1;
// Time in milliseconds; only reload weather if last update is longer ago than this value
private static final int NO_UPDATE_REQUIRED_THRESHOLD = 300000;
private static Map<String, Integer> speedUnits = new HashMap<>(3);
private static Map<String, Integer> pressUnits = new HashMap<>(3);
private static boolean mappingsInitialised = false;
Typeface weatherFont;
Weather todayWeather = new Weather();
TextView todayTemperature;
TextView todayDescription;
TextView todayWind;
TextView todayPressure;
TextView todayHumidity;
TextView todaySunrise;
TextView todaySunset;
TextView lastUpdate;
TextView todayIcon;
ViewPager viewPager;
TabLayout tabLayout;
View appView;
LocationManager locationManager;
ProgressDialog progressDialog;
int theme;
boolean destroyed = false;
private List<Weather> longTermWeather = new ArrayList<>();
private List<Weather> longTermTodayWeather = new ArrayList<>();
private List<Weather> longTermTomorrowWeather = new ArrayList<>();
public String recentCity = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
// Initialize the associated SharedPreferences file with default values
PreferenceManager.setDefaultValues(this, R.xml.prefs, false);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
setTheme(theme = getTheme(prefs.getString("theme", "fresh")));
boolean darkTheme = theme == R.style.AppTheme_NoActionBar_Dark ||
theme == R.style.AppTheme_NoActionBar_Classic_Dark;
boolean blackTheme = theme == R.style.AppTheme_NoActionBar_Black ||
theme == R.style.AppTheme_NoActionBar_Classic_Black;
// Initiate activity
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scrolling);
appView = findViewById(R.id.viewApp);
progressDialog = new ProgressDialog(MainActivity.this);
// Load toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (darkTheme) {
toolbar.setPopupTheme(R.style.AppTheme_PopupOverlay_Dark);
} else if (blackTheme) {
toolbar.setPopupTheme(R.style.AppTheme_PopupOverlay_Black);
}
// Initialize textboxes
todayTemperature = (TextView) findViewById(R.id.todayTemperature);
todayDescription = (TextView) findViewById(R.id.todayDescription);
todayWind = (TextView) findViewById(R.id.todayWind);
todayPressure = (TextView) findViewById(R.id.todayPressure);
todayHumidity = (TextView) findViewById(R.id.todayHumidity);
todaySunrise = (TextView) findViewById(R.id.todaySunrise);
todaySunset = (TextView) findViewById(R.id.todaySunset);
lastUpdate = (TextView) findViewById(R.id.lastUpdate);
todayIcon = (TextView) findViewById(R.id.todayIcon);
weatherFont = Typeface.createFromAsset(this.getAssets(), "fonts/weather.ttf");
todayIcon.setTypeface(weatherFont);
// Initialize viewPager
viewPager = (ViewPager) findViewById(R.id.viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
destroyed = false;
initMappings();
// Preload data from cache
preloadWeather();
updateLastUpdateTime();
// Set autoupdater
AlarmReceiver.setRecurringAlarm(this);
}
public WeatherRecyclerAdapter getAdapter(int id) {
WeatherRecyclerAdapter weatherRecyclerAdapter;
if (id == 0) {
weatherRecyclerAdapter = new WeatherRecyclerAdapter(this, longTermTodayWeather);
} else if (id == 1) {
weatherRecyclerAdapter = new WeatherRecyclerAdapter(this, longTermTomorrowWeather);
} else {
weatherRecyclerAdapter = new WeatherRecyclerAdapter(this, longTermWeather);
}
return weatherRecyclerAdapter;
}
#Override
public void onStart() {
super.onStart();
updateTodayWeatherUI();
updateLongTermWeatherUI();
}
#Override
public void onResume() {
super.onResume();
if (getTheme(PreferenceManager.getDefaultSharedPreferences(this).getString("theme", "fresh")) != theme) {
// Restart activity to apply theme
overridePendingTransition(0, 0);
finish();
overridePendingTransition(0, 0);
startActivity(getIntent());
} else if (shouldUpdate() && isNetworkAvailable()) {
getTodayWeather();
getLongTermWeather();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
destroyed = true;
if (locationManager != null) {
try {
locationManager.removeUpdates(MainActivity.this);
} catch (SecurityException e) {
e.printStackTrace();
}
}
}
private void preloadWeather() {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
String lastToday = sp.getString("lastToday", "");
if (!lastToday.isEmpty()) {
new TodayWeatherTask(this, this, progressDialog).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "cachedResponse", lastToday);
}
String lastLongterm = sp.getString("lastLongterm", "");
if (!lastLongterm.isEmpty()) {
new LongTermWeatherTask(this, this, progressDialog).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "cachedResponse", lastLongterm);
}
}
private void getTodayWeather() {
new TodayWeatherTask(this, this, progressDialog).execute();
}
private void getLongTermWeather() {
new LongTermWeatherTask(this, this, progressDialog).execute();
}
private void searchCities() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle(this.getString(R.string.search_title));
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
input.setMaxLines(1);
input.setSingleLine(true);
alert.setView(input, 32, 0, 32, 0);
alert.setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String result = input.getText().toString();
if (!result.isEmpty()) {
saveLocation(result);
}
}
});
alert.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Cancelled
}
});
alert.show();
}
private void saveLocation(String result) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
recentCity = preferences.getString("city", Constants.DEFAULT_CITY);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("city", result);
editor.commit();
if (!recentCity.equals(result)) {
// New location, update weather
getTodayWeather();
getLongTermWeather();
}
}
private void aboutDialog() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Forecastie");
final WebView webView = new WebView(this);
String about = "<p>1.6.1</p>" +
"<p>A lightweight, opensource weather app.</p>" +
"<p>Developed by <a href='mailto:t.martykan#gmail.com'>Tomas Martykan</a></p>" +
"<p>Data provided by <a href='https://openweathermap.org/'>OpenWeatherMap</a>, under the <a href='http://creativecommons.org/licenses/by-sa/2.0/'>Creative Commons license</a>" +
"<p>Icons are <a href='https://erikflowers.github.io/weather-icons/'>Weather Icons</a>, by <a href='http://www.twitter.com/artill'>Lukas Bischoff</a> and <a href='http://www.twitter.com/Erik_UX'>Erik Flowers</a>, under the <a href='http://scripts.sil.org/OFL'>SIL OFL 1.1</a> licence.";
TypedArray ta = obtainStyledAttributes(new int[]{android.R.attr.textColorPrimary, R.attr.colorAccent});
String textColor = String.format("#%06X", (0xFFFFFF & ta.getColor(0, Color.BLACK)));
String accentColor = String.format("#%06X", (0xFFFFFF & ta.getColor(1, Color.BLUE)));
ta.recycle();
about = "<style media=\"screen\" type=\"text/css\">" +
"body {\n" +
" color:" + textColor + ";\n" +
"}\n" +
"a:link {color:" + accentColor + "}\n" +
"</style>" +
about;
webView.setBackgroundColor(Color.TRANSPARENT);
webView.loadData(about, "text/html", "UTF-8");
alert.setView(webView, 32, 0, 32, 0);
alert.setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alert.show();
}
private String setWeatherIcon(int actualId, int hourOfDay) {
int id = actualId / 100;
String icon = "";
if (actualId == 800) {
if (hourOfDay >= 7 && hourOfDay < 20) {
icon = this.getString(R.string.weather_sunny);
} else {
icon = this.getString(R.string.weather_clear_night);
}
} else {
switch (id) {
case 2:
icon = this.getString(R.string.weather_thunder);
break;
case 3:
icon = this.getString(R.string.weather_drizzle);
break;
case 7:
icon = this.getString(R.string.weather_foggy);
break;
case 8:
icon = this.getString(R.string.weather_cloudy);
break;
case 6:
icon = this.getString(R.string.weather_snowy);
break;
case 5:
icon = this.getString(R.string.weather_rainy);
break;
}
}
return icon;
}
public static String getRainString(JSONObject rainObj) {
String rain = "0";
if (rainObj != null) {
rain = rainObj.optString("3h", "fail");
if ("fail".equals(rain)) {
rain = rainObj.optString("1h", "0");
}
}
return rain;
}
private ParseResult parseTodayJson(String result) {
try {
JSONObject reader = new JSONObject(result);
final String code = reader.optString("cod");
if ("404".equals(code)) {
return ParseResult.CITY_NOT_FOUND;
}
String city = reader.getString("name");
String country = "";
JSONObject countryObj = reader.optJSONObject("sys");
if (countryObj != null) {
country = countryObj.getString("country");
todayWeather.setSunrise(countryObj.getString("sunrise"));
todayWeather.setSunset(countryObj.getString("sunset"));
}
todayWeather.setCity(city);
todayWeather.setCountry(country);
JSONObject coordinates = reader.getJSONObject("coord");
if (coordinates != null) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
sp.edit().putFloat("latitude", (float) coordinates.getDouble("lon")).putFloat("longitude", (float) coordinates.getDouble("lat")).commit();
}
JSONObject main = reader.getJSONObject("main");
todayWeather.setTemperature(main.getString("temp"));
todayWeather.setDescription(reader.getJSONArray("weather").getJSONObject(0).getString("description"));
JSONObject windObj = reader.getJSONObject("wind");
todayWeather.setWind(windObj.getString("speed"));
if (windObj.has("deg")) {
todayWeather.setWindDirectionDegree(windObj.getDouble("deg"));
} else {
Log.e("parseTodayJson", "No wind direction available");
todayWeather.setWindDirectionDegree(null);
}
todayWeather.setPressure(main.getString("pressure"));
todayWeather.setHumidity(main.getString("humidity"));
JSONObject rainObj = reader.optJSONObject("rain");
String rain;
if (rainObj != null) {
rain = getRainString(rainObj);
} else {
JSONObject snowObj = reader.optJSONObject("snow");
if (snowObj != null) {
rain = getRainString(snowObj);
} else {
rain = "0";
}
}
todayWeather.setRain(rain);
final String idString = reader.getJSONArray("weather").getJSONObject(0).getString("id");
todayWeather.setId(idString);
todayWeather.setIcon(setWeatherIcon(Integer.parseInt(idString), Calendar.getInstance().get(Calendar.HOUR_OF_DAY)));
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainActivity.this).edit();
editor.putString("lastToday", result);
editor.commit();
} catch (JSONException e) {
Log.e("JSONException Data", result);
e.printStackTrace();
return ParseResult.JSON_EXCEPTION;
}
return ParseResult.OK;
}
private void updateTodayWeatherUI() {
try {
if (todayWeather.getCountry().isEmpty()) {
preloadWeather();
return;
}
} catch (Exception e) {
preloadWeather();
return;
}
String city = todayWeather.getCity();
String country = todayWeather.getCountry();
DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(getApplicationContext());
getSupportActionBar().setTitle(city + (country.isEmpty() ? "" : ", " + country));
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
// Temperature
float temperature = UnitConvertor.convertTemperature(Float.parseFloat(todayWeather.getTemperature()), sp);
if (sp.getBoolean("temperatureInteger", false)) {
temperature = Math.round(temperature);
}
// Rain
double rain = Double.parseDouble(todayWeather.getRain());
String rainString = UnitConvertor.getRainString(rain, sp);
// Wind
double wind;
try {
wind = Double.parseDouble(todayWeather.getWind());
} catch (Exception e) {
e.printStackTrace();
wind = 0;
}
wind = UnitConvertor.convertWind(wind, sp);
// Pressure
double pressure = UnitConvertor.convertPressure((float) Double.parseDouble(todayWeather.getPressure()), sp);
todayTemperature.setText(new DecimalFormat("0.#").format(temperature) + " " + sp.getString("unit", "°C"));
todayDescription.setText(todayWeather.getDescription().substring(0, 1).toUpperCase() +
todayWeather.getDescription().substring(1) + rainString);
if (sp.getString("speedUnit", "m/s").equals("bft")) {
todayWind.setText(getString(R.string.wind) + ": " +
UnitConvertor.getBeaufortName((int) wind) +
(todayWeather.isWindDirectionAvailable() ? " " + getWindDirectionString(sp, this, todayWeather) : ""));
} else {
todayWind.setText(getString(R.string.wind) + ": " + new DecimalFormat("0.0").format(wind) + " " +
localize(sp, "speedUnit", "m/s") +
(todayWeather.isWindDirectionAvailable() ? " " + getWindDirectionString(sp, this, todayWeather) : ""));
}
todayPressure.setText(getString(R.string.pressure) + ": " + new DecimalFormat("0.0").format(pressure) + " " +
localize(sp, "pressureUnit", "hPa"));
todayHumidity.setText(getString(R.string.humidity) + ": " + todayWeather.getHumidity() + " %");
todaySunrise.setText(getString(R.string.sunrise) + ": " + timeFormat.format(todayWeather.getSunrise()));
todaySunset.setText(getString(R.string.sunset) + ": " + timeFormat.format(todayWeather.getSunset()));
todayIcon.setText(todayWeather.getIcon());
}
public ParseResult parseLongTermJson(String result) {
int i;
try {
JSONObject reader = new JSONObject(result);
final String code = reader.optString("cod");
if ("404".equals(code)) {
if (longTermWeather == null) {
longTermWeather = new ArrayList<>();
longTermTodayWeather = new ArrayList<>();
longTermTomorrowWeather = new ArrayList<>();
}
return ParseResult.CITY_NOT_FOUND;
}
longTermWeather = new ArrayList<>();
longTermTodayWeather = new ArrayList<>();
longTermTomorrowWeather = new ArrayList<>();
JSONArray list = reader.getJSONArray("list");
for (i = 0; i < list.length(); i++) {
Weather weather = new Weather();
JSONObject listItem = list.getJSONObject(i);
JSONObject main = listItem.getJSONObject("main");
weather.setDate(listItem.getString("dt"));
weather.setTemperature(main.getString("temp"));
weather.setDescription(listItem.optJSONArray("weather").getJSONObject(0).getString("description"));
JSONObject windObj = listItem.optJSONObject("wind");
if (windObj != null) {
weather.setWind(windObj.getString("speed"));
weather.setWindDirectionDegree(windObj.getDouble("deg"));
}
weather.setPressure(main.getString("pressure"));
weather.setHumidity(main.getString("humidity"));
JSONObject rainObj = listItem.optJSONObject("rain");
String rain = "";
if (rainObj != null) {
rain = getRainString(rainObj);
} else {
JSONObject snowObj = listItem.optJSONObject("snow");
if (snowObj != null) {
rain = getRainString(snowObj);
} else {
rain = "0";
}
}
weather.setRain(rain);
final String idString = listItem.optJSONArray("weather").getJSONObject(0).getString("id");
weather.setId(idString);
final String dateMsString = listItem.getString("dt") + "000";
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(Long.parseLong(dateMsString));
weather.setIcon(setWeatherIcon(Integer.parseInt(idString), cal.get(Calendar.HOUR_OF_DAY)));
Calendar today = Calendar.getInstance();
if (cal.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR)) {
longTermTodayWeather.add(weather);
} else if (cal.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR) + 1) {
longTermTomorrowWeather.add(weather);
} else {
longTermWeather.add(weather);
}
}
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainActivity.this).edit();
editor.putString("lastLongterm", result);
editor.commit();
} catch (JSONException e) {
Log.e("JSONException Data", result);
e.printStackTrace();
return ParseResult.JSON_EXCEPTION;
}
return ParseResult.OK;
}
private void updateLongTermWeatherUI() {
if (destroyed) {
return;
}
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
Bundle bundleToday = new Bundle();
bundleToday.putInt("day", 0);
RecyclerViewFragment recyclerViewFragmentToday = new RecyclerViewFragment();
recyclerViewFragmentToday.setArguments(bundleToday);
viewPagerAdapter.addFragment(recyclerViewFragmentToday, getString(R.string.today));
Bundle bundleTomorrow = new Bundle();
bundleTomorrow.putInt("day", 1);
RecyclerViewFragment recyclerViewFragmentTomorrow = new RecyclerViewFragment();
recyclerViewFragmentTomorrow.setArguments(bundleTomorrow);
viewPagerAdapter.addFragment(recyclerViewFragmentTomorrow, getString(R.string.tomorrow));
Bundle bundle = new Bundle();
bundle.putInt("day", 2);
RecyclerViewFragment recyclerViewFragment = new RecyclerViewFragment();
recyclerViewFragment.setArguments(bundle);
viewPagerAdapter.addFragment(recyclerViewFragment, getString(R.string.later));
int currentPage = viewPager.getCurrentItem();
viewPagerAdapter.notifyDataSetChanged();
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
if (currentPage == 0 && longTermTodayWeather.isEmpty()) {
currentPage = 1;
}
viewPager.setCurrentItem(currentPage, false);
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
private boolean shouldUpdate() {
long lastUpdate = PreferenceManager.getDefaultSharedPreferences(this).getLong("lastUpdate", -1);
boolean cityChanged = PreferenceManager.getDefaultSharedPreferences(this).getBoolean("cityChanged", false);
// Update if never checked or last update is longer ago than specified threshold
return cityChanged || lastUpdate < 0 || (Calendar.getInstance().getTimeInMillis() - lastUpdate) > NO_UPDATE_REQUIRED_THRESHOLD;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}

Unable to calculate proper value from each row in ListView

// i have two button for increasing and decreasing the quantity, after increasing or decreasing the value i want to calculate price from each row but it is not giving correct value.Also the quantity getting changed while scrolling .Mostly the above said problem occurs whenever the size of listview is more than screen size.
public class Baseddapter extends BaseAdapter
{
#Override
public int getCount()
{
return prodetailarray.size();
}
#Override
public Object getItem(int i)
{
// Log.d("item_value",""+prodetailarray.get(i).getPrice());
return null;
}
#Override
public long getItemId(int i)
{
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
listrowposition = position;
final ViewHolder holder;
if (convertView == null)
{
LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.singlerowbill_detail, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.txtproname_prodetail);
holder.sellprice = (TextView) convertView.findViewById(R.id.txtprice_prodetail);
holder.proid = (TextView) convertView.findViewById(R.id.txtproid_prodetail);
holder.qty = (TextView) convertView.findViewById(R.id.txtquntty_prodetail);
holder.imgplus = (ImageView) convertView.findViewById(R.id.imgplus_prodetail);
holder.imgminus = (ImageView) convertView.findViewById(R.id.imgminus_prodetail);
holder.singlerowprice = (TextView) convertView.findViewById(R.id.txtsinglerow_price);
holder.baseprice = (TextView) convertView.findViewById(R.id.txt_base_price_prodetail);
holder.taxid = (TextView) convertView.findViewById(R.id.txt_taxid_prodetail);
holder.taxname = (TextView) convertView.findViewById(R.id.txt_taxname_prodetail);
holder.taxval = (TextView) convertView.findViewById(R.id.txt_taxval_prodetail);
// holder.singlerowprice.addTextChangedListener(new MytextWatcher(convertView));
holder.delete = (ImageView) convertView.findViewById(R.id.txtdeleterow);
holder.txtkg = (TextView) convertView.findViewById(R.id.txtkg);
holder.whole_qntty = (TextView) convertView.findViewById(R.id.txt_whole_qntty_prodetail);
holder.delete.setTag(position);
holder.circularImageView = (CircularImageView) convertView.findViewById(R.id.productImage_billdetail);
holder.linearLayout = (LinearLayout) convertView.findViewById(R.id.linearkg);
holder.name.setTypeface(light);
holder.singlerowprice.setTypeface(light);
holder.baseprice.setTypeface(light);
holder.qty.setTypeface(light);
//holder.qty.setTag(position);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
base_price = prodetailarray.get(listrowposition).getBaseprice();
Log.d("baseprice==", "***" + base_price);
holder.baseprice.setText(prodetailarray.get(listrowposition).getBaseprice());
//this means if qnty contain only number means add as unit otherwise add as kg
if(prodetailarray.get(listrowposition).getQntity().matches("[0-9]+"))
{
holder.qty.setText(prodetailarray.get(position).getQntity());
//holder.linearLayout.setVisibility(View.VISIBLE);
holder.imgplus.setVisibility(View.VISIBLE);
holder.imgminus.setVisibility(View.VISIBLE);
// holder.txtkg.setVisibility(View.GONE);
Log.d("qntty_kg??",""+prodetailarray.get(listrowposition).getQntity());
}
else
{
// holder.linearLayout.setVisibility(View.GONE);
holder.imgplus.setVisibility(View.GONE);
holder.imgminus.setVisibility(View.GONE);
// holder.txtkg.setVisibility(View.VISIBLE);
holder.qty.setText(""+prodetailarray.get(listrowposition).getQntity());
Log.d("qntty_kg==",""+prodetailarray.get(listrowposition).getQntity());
// Toast.makeText(Bill_details.this,""+prodetailarray.get(position).getQntity(),Toast.LENGTH_LONG).show();
}
holder.name.setText(prodetailarray.get(listrowposition).getProductname());
holder.sellprice.setText(getResources().getString(R.string.Rs)+" "+prodetailarray.get(position).getPrice());
holder.taxid.setText(prodetailarray.get(listrowposition).getTaxid());
holder.taxname.setText(prodetailarray.get(listrowposition).getTaxname());
holder.taxval.setText(prodetailarray.get(listrowposition).getTaxvalue());
holder.whole_qntty.setText(prodetailarray.get(listrowposition).getWhole_qntty());
holder.proid.setText(prodetailarray.get(listrowposition).getProducuid());
final String str=prodetailarray.get(listrowposition).getQntity();
Double q = Double.parseDouble(str.replaceAll("KG", ""));
holder.singlerowprice.setText(getResources().getString(R.string.Rs)+" " + Double.parseDouble(prodetailarray.get(listrowposition).getPrice()) * q);
drawable = mDrawableBuilder.build(String.valueOf(holder.name.getText().toString().trim().toUpperCase().charAt(0)),
mColorGenerator.getColor((holder.name.getText().toString().trim().charAt(0))));
holder.circularImageView.setImageDrawable(drawable);
holder.delete.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
total_item = totalquantity-1;
totalquantity=total_item;
Integer index = (Integer) view.getTag();
Log.d("indexval==","delete"+index.intValue());
prodetailarray.remove(index.intValue());
adapter.notifyDataSetChanged();
listView.invalidateViews();
Log.d("listCount==",""+listView.getCount());
// totalprice=0;
Double add = 0.0;
Double pr = 0.0;
// listView.invalidateViews();
if (listView.getCount() == 0)
{
totalitem.setText("0 Items");
totalamount.setText( getResources().getString(R.string.Rs)+" 0");
editor.remove("count");
editor.remove("price");
editor.commit();
}
Log.d("liistvisiblepos==",""+(listView.getLastVisiblePosition()-listView.getFirstVisiblePosition())) ;
for (int i = 0; i < listView.getCount(); i++)
{
// this if is for after delete item it will take first item so we dont want like this
if(index.intValue() != i)
{
/* View v = listView.getChildAt(i);
TextView tvquan = (TextView) v.findViewById(R.id.txtquntty_prodetail);
TextView tvprice = (TextView) v.findViewById(R.id.txtsinglerow_price);
*/
String str = holder.qty.getText().toString().trim();
Double p = Double.parseDouble(str.replaceAll(getResources().getString(R.string.Rs), ""));
pr = pr + p;
totalitem.setText("" + total_item + " Items");
totalamount.setText(getResources().getString(R.string.Rs) + " " + pr);
// Log.d("listitemcount==", "tvquan==" + tvquan.getText().toString() + "add==" + add + "price" + pr + "p==" + p);
}
}
}
});
holder.imgplus.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
View v1=view;
PLUSMINUS = 100;
if(holder.qty.getText().toString().matches("[0-9]+"))
{
plus_qnty = Integer.parseInt(holder.qty.getText().toString());
Log.d("plus_qnty==",""+plus_qnty);
//this is for check the quantity that useer enter is not more than qntty in stock
Log.d("whole_qnt_plus==",""+holder.whole_qntty.getText().toString());
whole_qnt= Integer.parseInt(holder.whole_qntty.getText().toString());
Log.d("whole_qnt_plus==",""+whole_qnt);
plus_qnty = plus_qnty + 1;
if(plus_qnty>whole_qnt)
{
Toast.makeText(getApplicationContext(), getResources().getString(R.string.outofstock), Toast.LENGTH_LONG).show();
}
else
{
prodetailarray.get(listrowposition).setQntity(String.valueOf(plus_qnty));
holder.qty.setText("" + plus_qnty);
//remove all the text except price (integer value)
String str=holder.sellprice.getText().toString().trim();
Double sell_price= Double.parseDouble(str.replaceAll(getResources().getString(R.string.Rs), ""));
holder.singlerowprice.setText(getResources().getString(R.string.Rs)+" " + Double.parseDouble(holder.qty.getText().toString()) * sell_price);
prodetailarray.get(listrowposition).setQntity(String.valueOf(plus_qnty));
prodetailarray.get(listrowposition).setBaseprice("" + Double.parseDouble(base_price) * plus_qnty);
}
/*for calculate value after change if any change*/
Double add = 0.0;
Double pr = 0.0;
for (int i = 0;i < listView.getCount(); i++)
{
Log.d("listviewcount==",""+listView.getCount());
View v = listView.getAdapter().getView(i,null,null);
TextView tvquan = (TextView) v.findViewById(R.id.txtquntty_prodetail);
TextView tvprice = (TextView) v.findViewById(R.id.txtsinglerow_price);
// String str_qun=tvquan.getText().toString().trim();
String str_qun=tvquan.getText().toString().trim();
Log.d("listviewcount==",""+str_qun);
Double c = Double.parseDouble(str_qun.replaceAll("KG", ""));
add = c + add;
String str = tvprice.getText().toString().trim();
// String str = holder.singlerowprice.getText().toString().trim();
Log.d("str_qun==",""+str_qun+str);
Double p = Double.parseDouble(str.replaceAll(getResources().getString(R.string.Rs), ""));
pr = pr + p;
// Log.d("listitemcount==", "tvquan==" + tvquan.getText().toString() + "add==" + add + "price" + pr);
totalamount.setText(getResources().getString(R.string.Rs) +" "+ pr);
}
}
else {
}
}
});
holder.imgminus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PLUSMINUS = 200;
if(holder.qty.getText().toString().matches("[0-9]+"))
{
minus_qnty = Integer.parseInt(holder.qty.getText().toString());
if (minus_qnty == 1)
{
// holder.qty.setText(""+);
}
else
{
minus_qnty = minus_qnty - 1;
holder.qty.setText("" + minus_qnty);
String str=holder.sellprice.getText().toString();
Double sell_price= Double.parseDouble(str.replaceAll(getResources().getString(R.string.Rs), ""));
holder.singlerowprice.setText(getResources().getString(R.string.Rs)+" " + Double.parseDouble(holder.qty.getText().toString()) * sell_price);
prodetailarray.get(listrowposition).setQntity(String.valueOf(minus_qnty));
prodetailarray.get(listrowposition).setBaseprice("" + Double.parseDouble(base_price) * minus_qnty);
}
/*for calculate value after change if any change*/
Double add = 0.0;
Double pr = 0.0;
for (int i = 0; i <listView.getCount(); i++)
{
View v = listView.getAdapter().getView(i,null,null);
TextView tvquan = (TextView) v.findViewById(R.id.txtquntty_prodetail);
TextView tvprice = (TextView) v.findViewById(R.id.txtsinglerow_price);
String str_qun=tvquan.getText().toString().trim();
Double c = Double.parseDouble(str_qun.replaceAll("KG", ""));
add = c + add;
String str = tvprice.getText().toString().trim();
Double p = Double.parseDouble(str.replaceAll(getResources().getString(R.string.Rs), ""));
pr = pr + p;
// Log.d("listitemcount==", "tvquan==" + tvquan.getText().toString() + "add==" + add + "price" + pr);
totalamount.setText(getResources().getString(R.string.Rs) +" "+ pr);
}
}
else
{
}
}
});
if(!prodetailarray.get(listrowposition).getQntity().matches("[0-9]+"))
{
holder.qty.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
final Integer index = (Integer) view.getTag();
Log.d("indexval==","index==="+index);
final Dialog dialog_item = new Dialog(Bill_details.this);
dialog_item.setContentView(R.layout.add_item_dialog);
dialog_item.getWindow().setLayout(AppBarLayout.LayoutParams.FILL_PARENT, AppBarLayout.LayoutParams.WRAP_CONTENT);
final EditText edt_enter_qntty = (EditText) dialog_item.findViewById(R.id.txtqntty_item_dialog);
TextView ok = (TextView) dialog_item.findViewById(R.id.txtok_item_dialog);
ok.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
if(edt_enter_qntty.getText().toString().equals(""))
{
}
else
{
Double dialog_qntty= Double.parseDouble(edt_enter_qntty.getText().toString());
// PLUSMINUS = 100;
kg_qntty = dialog_qntty;
//this is for checking entered qunnt is not more than avail qntty
String whole_qnt=holder.whole_qntty.getText().toString();
String whole_qnt_replce= (whole_qnt.replaceAll("KG", ""));
whole_qnt_kg= Double.parseDouble(whole_qnt_replce);
Log.d("whole_qnt_kg==",""+whole_qnt_kg);
if(kg_qntty>whole_qnt_kg)
{
Toast.makeText(getApplicationContext(), getResources().getString(R.string.outofstock), Toast.LENGTH_LONG).show();
}
else
{
prodetailarray.get(listrowposition).setQntity(String.valueOf(kg_qntty));
holder.qty.setText("" + kg_qntty+"KG");
//remove all the text except price (integer value)
String str_qnty=holder.qty.getText().toString();
Double qty= Double.parseDouble(str_qnty.replaceAll("KG", ""));
String str=holder.sellprice.getText().toString();
Double sell_price= Double.parseDouble(str.replaceAll(getResources().getString(R.string.Rs), ""));
holder.singlerowprice.setText(getResources().getString(R.string.Rs)+" " + qty * sell_price);
prodetailarray.get(listrowposition).setQntity(String.valueOf(kg_qntty));
prodetailarray.get(listrowposition).setBaseprice("" + Double.parseDouble(base_price) * kg_qntty);
}
/*for calculate value after change if any change*/
Double add = 0.0;
Double pr = 0.0;
for (int i = 0;i <listView.getCount(); i++)
{
View v = listView.getAdapter().getView(i,null,null);
TextView tvquan = (TextView) v.findViewById(R.id.txtquntty_prodetail);
TextView tvprice = (TextView) v.findViewById(R.id.txtsinglerow_price);
String str_quan=tvquan.getText().toString().trim();
Log.d("strqn",str_quan);
String c = (str_quan.replaceAll("KG", ""));
Log.d("strqn", "" + c);
add = Double.parseDouble(c) + add;
String str_pri=tvprice.getText().toString().trim();
Double p= Double.parseDouble(str_pri.replaceAll(getResources().getString(R.string.Rs), ""));
pr = pr + p;
Log.d("total_qntty", "tvquan==" + tvquan.getText().toString() + "add==" + add + "price" + pr);
// totalitem.setText("" + add+" Items");
totalamount.setText(getResources().getString(R.string.Rs) +" "+ pr);
}
}
dialog_item.dismiss();
}
});
dialog_item.show();
}
});
}
return convertView;
}
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
}
Never update an item view in a list from the event handler (controller).
It looks like you are correctly updating the model (prodetailarray), but in an onClick or any event handler, all you want to do is update the model and then call notifyDataSetChanged(). This will inform your list view that the model has changed, and the list view will regenerate item views based on the new model data.
If that's not sufficient to solve your problem, you'll need to post your entire adapter code so we can identify the problem.
//see below getview method which I updated .
public View getView(final int position, View convertView, ViewGroup parent)
{
listrowposition = position;
final ViewHolder holder;
if (convertView == null)
{
LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.singlerowbill_detail, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.txtproname_prodetail);
holder.sellprice = (TextView) convertView.findViewById(R.id.txtprice_prodetail);
holder.proid = (TextView) convertView.findViewById(R.id.txtproid_prodetail);
holder.qty = (TextView) convertView.findViewById(R.id.txtquntty_prodetail);
holder.imgplus = (ImageView) convertView.findViewById(R.id.imgplus_prodetail);
holder.imgminus = (ImageView) convertView.findViewById(R.id.imgminus_prodetail);
holder.singlerowprice = (TextView) convertView.findViewById(R.id.txtsinglerow_price);
holder.baseprice = (TextView) convertView.findViewById(R.id.txt_base_price_prodetail);
holder.taxid = (TextView) convertView.findViewById(R.id.txt_taxid_prodetail);
holder.taxname = (TextView) convertView.findViewById(R.id.txt_taxname_prodetail);
holder.taxval = (TextView) convertView.findViewById(R.id.txt_taxval_prodetail);
// holder.singlerowprice.addTextChangedListener(new MytextWatcher(convertView));
holder.delete = (ImageView) convertView.findViewById(R.id.txtdeleterow);
holder.txtkg = (TextView) convertView.findViewById(R.id.txtkg);
holder.whole_qntty = (TextView) convertView.findViewById(R.id.txt_whole_qntty_prodetail);
holder.circularImageView = (CircularImageView) convertView.findViewById(R.id.productImage_billdetail);
holder.linearLayout = (LinearLayout) convertView.findViewById(R.id.linearkg);
holder.name.setTypeface(light);
holder.singlerowprice.setTypeface(light);
holder.baseprice.setTypeface(light);
holder.qty.setTypeface(light);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
base_price = prodetailarray.get(listrowposition).getBaseprice();
holder.qty.setTag(listrowposition);
holder.delete.setTag(listrowposition);
holder.imgplus.setTag(listrowposition);
holder.imgminus.setTag(listrowposition);
Log.d("baseprice==", "***" + base_price);
holder.baseprice.setText(prodetailarray.get(listrowposition).getBaseprice());
//this means if qnty contain only number means add as unit otherwise add as kg
if(prodetailarray.get(listrowposition).getQntity().matches("[0-9]+"))
{
holder.qty.setText(prodetailarray.get(listrowposition).getQntity());
//
holder.imgplus.setVisibility(View.VISIBLE);
holder.imgminus.setVisibility(View.VISIBLE);
//
Log.d("qntty_kg??",""+prodetailarray.get(listrowposition).getQntity());
}
else
{
holder.imgplus.setVisibility(View.GONE);
holder.imgminus.setVisibility(View.GONE);
//
holder.qty.setText(""+prodetailarray.get(listrowposition).getQntity());
Log.d("qntty_kg==",""+prodetailarray.get(listrowposition).getQntity());
}
holder.name.setText(prodetailarray.get(listrowposition).getProductname());
holder.sellprice.setText(getResources().getString(R.string.Rs)+" "+prodetailarray.get(listrowposition).getPrice());
holder.taxid.setText(prodetailarray.get(listrowposition).getTaxid());
holder.taxname.setText(prodetailarray.get(listrowposition).getTaxname());
holder.taxval.setText(prodetailarray.get(listrowposition).getTaxvalue());
holder.whole_qntty.setText(prodetailarray.get(listrowposition).getWhole_qntty());
holder.proid.setText(prodetailarray.get(listrowposition).getProducuid());
final String str=prodetailarray.get(listrowposition).getQntity();
Double q = Double.parseDouble(str.replaceAll("KG", ""));
holder.singlerowprice.setText(getResources().getString(R.string.Rs)+" " + Double.parseDouble(prodetailarray.get(listrowposition).getPrice()) * q);
drawable = mDrawableBuilder.build(String.valueOf(holder.name.getText().toString().trim().toUpperCase().charAt(0)),
mColorGenerator.getColor((holder.name.getText().toString().trim().charAt(0))));
holder.circularImageView.setImageDrawable(drawable);
holder.delete.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
total_item = totalquantity-1;
totalquantity=total_item;
Integer index = (Integer) view.getTag();
Log.d("indexval==","delete"+index.intValue());
prodetailarray.remove(index.intValue());
adapter.notifyDataSetChanged();
listView.invalidateViews();
Log.d("listCount==",""+listView.getCount());
Double add = 0.0;
Double pr = 0.0;
if (listView.getCount() == 0)
{
totalitem.setText("0 Items");
totalamount.setText( getResources().getString(R.string.Rs)+" 0");
editor.remove("count");
editor.remove("price");
editor.commit();
}
for (int i = 0; i < listView.getCount(); i++)
{
// this if is for after delete item it will take first item so we dont want like this
View v = listView.getAdapter().getView(i,null,listView);
if(v==null)
{
return;
}
TextView tvquan = (TextView) v.findViewById(R.id.txtquntty_prodetail);
TextView tvprice = (TextView) v.findViewById(R.id.txtsinglerow_price);
String str_qun=tvquan.getText().toString().trim();
Double c = Double.parseDouble(str_qun.replaceAll("KG", ""));
add = c + add;
String str = tvprice.getText().toString().trim();
Double p = Double.parseDouble(str.replaceAll(getResources().getString(R.string.Rs), ""));
pr = pr + p;
totalitem.setText("" + total_item + " Items");
totalamount.setText(getResources().getString(R.string.Rs) + " " + pr);
Log.d("listitemcount==", "tvquan==" + tvquan.getText().toString() + "add==" + add + "price" + pr + "p==" + p);
}
}
});
holder.imgplus.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
int in=(Integer) view.getTag();
PLUSMINUS = 100;
if(holder.qty.getText().toString().matches("[0-9]+"))
{
plus_qnty = Integer.parseInt(holder.qty.getText().toString());
Log.d("plus_qnty==",""+plus_qnty);
//this is for check the quantity that useer enter is not more than qntty in stock
Log.d("whole_qnt_plus==",""+holder.whole_qntty.getText().toString());
whole_qnt= Integer.parseInt(holder.whole_qntty.getText().toString());
Log.d("whole_qnt_plus==",""+whole_qnt);
plus_qnty = plus_qnty + 1;
if(plus_qnty>whole_qnt)
{
Toast.makeText(getApplicationContext(), getResources().getString(R.string.outofstock), Toast.LENGTH_LONG).show();
}
else
{
for(int i=0;i<prodetailarray.size();i++){
Log.d("proarr==","getQntity=="+""+prodetailarray.get(i).getQntity()+"baseprice=="+prodetailarray.get(i).getBaseprice());
}
holder.qty.setText("" + plus_qnty);
//remove all the text except price (integer value)
String str=holder.sellprice.getText().toString().trim();
Double sell_price= Double.parseDouble(str.replaceAll(getResources().getString(R.string.Rs), ""));
holder.singlerowprice.setText(getResources().getString(R.string.Rs)+" " + Double.parseDouble(holder.qty.getText().toString()) * sell_price);
Bills_Activity.productlistarray.set(position,);
prodetailarray.get(in).setQntity(String.valueOf(plus_qnty));
prodetailarray.get(in).setBaseprice("" + Double.parseDouble(base_price) * plus_qnty);
for(int i=0;i<prodetailarray.size();i++)
{
Log.d("proarr=="," after_getQntity=="+""+prodetailarray.get(i).getQntity()+"baseprice=="+prodetailarray.get(i).getBaseprice());
}
}
/*for calculate value after change if any change*/
Double add = 0.0;
Double pr = 0.0;
for (int i = 0;i <listView.getCount(); i++)
{
View v = listView.getAdapter().getView(i,null,listView);
if(v==null)
{
return;
}
TextView tvquan = (TextView) v.findViewById(R.id.txtquntty_prodetail);
TextView tvprice = (TextView) v.findViewById(R.id.txtsinglerow_price);
String str_qun=tvquan.getText().toString().trim();
Double c = Double.parseDouble(str_qun.replaceAll("KG", ""));
add = c + add;
String str = tvprice.getText().toString().trim();
Double p = Double.parseDouble(str.replaceAll(getResources().getString(R.string.Rs), ""));
pr = pr + p;
Log.d("listitemcount==", "tvquan==" + tvquan.getText().toString() + "add==" + add + "price" + pr);
totalamount.setText(getResources().getString(R.string.Rs) +" "+ pr);
}
}
else
{
}
}
});
holder.imgminus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PLUSMINUS = 200;
int in=(Integer) view.getTag();
if(holder.qty.getText().toString().matches("[0-9]+"))
{
minus_qnty = Integer.parseInt(holder.qty.getText().toString());
if (minus_qnty == 1)
{
}
else
{
minus_qnty = minus_qnty - 1;
holder.qty.setText("" + minus_qnty);
String str=holder.sellprice.getText().toString();
Double sell_price= Double.parseDouble(str.replaceAll(getResources().getString(R.string.Rs), ""));
holder.singlerowprice.setText(getResources().getString(R.string.Rs)+" " + Double.parseDouble(holder.qty.getText().toString()) * sell_price);
prodetailarray.get(in).setQntity(String.valueOf(minus_qnty));
prodetailarray.get(in).setBaseprice("" + Double.parseDouble(base_price) * minus_qnty);
}
/*for calculate value after change if any change*/
Double add = 0.0;
Double pr = 0.0;
for (int i = 0; i < listView.getCount(); i++)
{
View v = listView.getAdapter().getView(i,null,listView);
if(v==null)
{
return;
}
TextView tvquan = (TextView) v.findViewById(R.id.txtquntty_prodetail);
TextView tvprice = (TextView) v.findViewById(R.id.txtsinglerow_price);
String str_qun=tvquan.getText().toString().trim();
Double c = Double.parseDouble(str_qun.replaceAll("KG", ""));
add = c + add;
String str = tvprice.getText().toString().trim();
Double p = Double.parseDouble(str.replaceAll(getResources().getString(R.string.Rs), ""));
pr = pr + p;
Log.d("listitemcount==", "tvquan==" + tvquan.getText().toString() + "add==" + add + "price" + pr);
totalamount.setText(getResources().getString(R.string.Rs) +" "+ pr);
// totalamount.setText(""+ pr);
}
}
else
{
}
}
});
if(!prodetailarray.get(listrowposition).getQntity().matches("[0-9]+"))
{
holder.qty.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
index = (Integer) view.getTag();
Log.d("indexval==","index==="+index);
final Dialog dialog_item = new Dialog(Bill_details.this);
dialog_item.setContentView(R.layout.add_item_dialog);
dialog_item.getWindow().setLayout(AppBarLayout.LayoutParams.FILL_PARENT, AppBarLayout.LayoutParams.WRAP_CONTENT);
edt_enter_qntty = (EditText) dialog_item.findViewById(R.id.txtqntty_item_dialog);
TextView ok = (TextView) dialog_item.findViewById(R.id.txtok_item_dialog);
ok.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
if(edt_enter_qntty.getText().toString().equals(""))
{
}
else
{
Double dialog_qntty= Double.parseDouble(edt_enter_qntty.getText().toString());
// PLUSMINUS = 100;
kg_qntty = dialog_qntty;
//this is for checking entered qunnt is not more than avail qntty
String whole_qnt=holder.whole_qntty.getText().toString();
String whole_qnt_replce= (whole_qnt.replaceAll("KG", ""));
whole_qnt_kg= Double.parseDouble(whole_qnt_replce);
Log.d("whole_qnt_kg==",""+whole_qnt_kg);
if(kg_qntty>whole_qnt_kg)
{
Toast.makeText(getApplicationContext(), getResources().getString(R.string.outofstock), Toast.LENGTH_LONG).show();
}
else
{
holder.qty.setText("" + kg_qntty+"KG");
prodetailarray.get(index).setQntity(String.valueOf(kg_qntty));
//remove all the text except price (integer value)
String str_qnty=prodetailarray.get(index).getQntity().toString();
Double qty= Double.parseDouble(str_qnty.replaceAll("KG", ""));
String str=holder.sellprice.getText().toString();
Double sell_price= Double.parseDouble(str.replaceAll(getResources().getString(R.string.Rs), ""));
Log.d("qty * sell_price==",""+qty+" "+sell_price);
holder.singlerowprice.setText(getResources().getString(R.string.Rs)+" " + qty * sell_price);
prodetailarray.get(index).setBaseprice("" + Double.parseDouble(base_price) * kg_qntty);
}
/*for calculate value after change if any change*/
Double add = 0.0;
Double pr = 0.0;
for (int i = 0;i < listView.getCount(); i++)
{
View v = listView.getAdapter().getView(i,null,listView);
if(v==null)
{
return;
}
TextView tvquan = (TextView) v.findViewById(R.id.txtquntty_prodetail);
TextView tvprice = (TextView) v.findViewById(R.id.txtsinglerow_price);
String str_quan=tvquan.getText().toString().trim();
Log.d("strqn",str_quan);
String c = (str_quan.replaceAll("KG", ""));
Log.d("strqn", "" + c);
add = Double.parseDouble(c) + add;
String str_pri=tvprice.getText().toString().trim();
Double p= Double.parseDouble(str_pri.replaceAll(getResources().getString(R.string.Rs), ""));
pr = pr + p;
Log.d("total_qntty", "tvquan==" + tvquan.getText().toString() + "add==" + add + "price" + pr);
// totalitem.setText("" + add+" Items");
totalamount.setText(getResources().getString(R.string.Rs) +" "+ pr);
}
}
dialog_item.dismiss();
}
});
dialog_item.show();
}
});
}
return convertView;
}

custom listview stucks when new item is generting and scrolling

I have an issue.I have custom listView which has many child and also have another custom listview in it.All data which is display in both listView is coming from database.My Problem is that When I scroll My main ListView it stucks for a while and then scroll.I uploaded My all code here.
My Main Activity class:
public class TransactionListMonthWise<DisplayYear> extends TopParentActivity {
ListView statement;
ArrayList<DisplayMonth> status;
ArrayList<DisplayYear> yearstatus;
addBankTransactionList mAdapter;
TextView tvBankName, tvBalance, tvBankAccNoForHistory;
String monthname;
String monthName;
int yearName;
String bankname, amount, accno;
Date theDate;
String currencySymbl, cur_sym;
EPreferences epref;
String TotalBalance, BankBalance, finalTotalIncome;
Toolbar toolbarTransactionListMonthWise;
boolean loadingMore = false;
int itemsPerPage = 2;
DisplayMonth monthNameInAdapter;
int month;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transaction_monthwise);
bindview();
init();
addListener();
}
private void init() {
epref = EPreferences.getInstance(TransactionListMonthWise.this);
getPrefData();
Intent intent = getIntent();
bankname = intent.getStringExtra("NAME");
tvBankName.setText(bankname);
TotalBalance = String.valueOf(intent.getDoubleExtra("BALANCE", 0.0));
BankBalance = new BigDecimal(TotalBalance).toPlainString();
DecimalFormat decimalFormatIncome = new DecimalFormat("0.#");
finalTotalIncome = decimalFormatIncome.format(Double
.valueOf(TotalBalance));
tvBalance.setText(currencySymbl
+ " "
+ String.format("%,.00f",
(double) Double.parseDouble(finalTotalIncome)));
// tvBalance.setText(amount + " " + currencySymbl);
Log.i("symbol", currencySymbl);
accno = intent.getStringExtra("ACCNO");
status = new ArrayList<DisplayMonth>();
yearstatus = new ArrayList<DisplayYear>();
tvBankAccNoForHistory.setText("xxxxx"
+ intent.getStringExtra("ACC_NUMBER"));
Utils.BANK_ACC_NUM = intent.getStringExtra("ACC_NUMBER");
Utils.BANK_NAME_DISP = bankname;
setSupportActionBar(toolbarTransactionListMonthWise);
this.toolbarTransactionListMonthWise
.setNavigationIcon(R.drawable.ic_arrow_back_white100);
getSupportActionBar().setTitle(bankname + " History");
}
private void bindview() {
toolbarTransactionListMonthWise = (Toolbar) findViewById(R.id.toolbarTransactionListMonthWise);
statement = (ListView) findViewById(R.id.list_transaction_view);
tvBankName = (TextView) findViewById(R.id.tvBankNameForHistory);
tvBalance = (TextView) findViewById(R.id.tvNetBalanceForHistory);
tvBankAccNoForHistory = (TextView) findViewById(R.id.tvBankAccNoForHistory);
}
private void addListener() {
statement.setOnScrollListener(new AbsListView.OnScrollListener() {
int mLastFirstVisibleItem;
boolean mIsScrollingUp;
#Override
public void onScrollStateChanged(AbsListView view, int scrollstate) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
int lastInScreen = firstVisibleItem + visibleItemCount;
if ((lastInScreen == totalItemCount)) {
new MailSender().execute();
}
}
});
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(TransactionListMonthWise.this,
BankList.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
private String getMonth(int month1) {
switch (month1) {
case 1:
monthname = "Jan";
break;
case 2:
monthname = "Feb";
break;
case 3:
monthname = "Mar";
break;
case 4:
monthname = "Apr";
break;
case 5:
monthname = "May";
break;
case 6:
monthname = "Jun";
break;
case 7:
monthname = "Jul";
break;
case 8:
monthname = "Aug";
break;
case 9:
monthname = "Sep";
break;
case 10:
monthname = "Oct";
break;
case 11:
monthname = "Nov";
break;
case 12:
monthname = "Dec";
break;
default:
break;
}
return monthname;
}
private int getYear(int years) {
switch (years) {
case 1:
years = 2011;
break;
case 2:
years = 2012;
break;
case 3:
years = 2013;
break;
case 4:
years = 2014;
break;
case 5:
years = 2015;
break;
case 6:
years = 2016;
break;
default:
break;
}
return years;
}
private void getPrefData() {
cur_sym = epref.getPreferencesStr(epref.KEY_CURRENCY, "India");
Log.d("vaaaaa", " == " + cur_sym);
if (cur_sym.equalsIgnoreCase("India")) {
currencySymbl = getResources().getString(R.string.India);
} else if (cur_sym.equalsIgnoreCase("US")) {
currencySymbl = getResources().getString(R.string.United_States);
} else if (cur_sym.equalsIgnoreCase("Japan")) {
currencySymbl = getResources().getString(R.string.Japan);
} else if (cur_sym.equalsIgnoreCase("England")) {
currencySymbl = getResources().getString(R.string.England_pound);
} else if (cur_sym.equalsIgnoreCase("Costa Rica")) {
currencySymbl = getResources().getString(R.string.Costa);
} else if (cur_sym.equalsIgnoreCase("UK")) {
currencySymbl = getResources().getString(R.string.United);
} else if (cur_sym.equalsIgnoreCase("Phillipines")) {
currencySymbl = getResources().getString(R.string.Philippines);
} else if (cur_sym.equalsIgnoreCase("Mangolia")) {
currencySymbl = getResources().getString(R.string.Macedonia);
} else if (cur_sym.equalsIgnoreCase("Australia")) {
currencySymbl = getResources().getString(R.string.Australia);
} else if (cur_sym.equalsIgnoreCase("Europ")) {
currencySymbl = getResources().getString(R.string.Euro);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
public class MailSender extends AsyncTask<Void, Integer, Integer> {
Dialog progress;
#SuppressLint("ResourceAsColor")
#Override
protected void onPreExecute() {
super.onPreExecute();
progress = new Dialog(TransactionListMonthWise.this,
R.style.AppDialogExit);
progress.requestWindowFeature(Window.FEATURE_NO_TITLE);
progress.show();
progress.setContentView(R.layout.custom_loading_dialog);
TextView tv = (TextView) progress.findViewById(R.id.tv);
tv.setText("Mail is sending...");
progress.setCanceledOnTouchOutside(false);
progress.setCancelable(false);
}
#Override
protected Integer doInBackground(Void... params) {
final RelativeLayout footerView = (RelativeLayout) findViewById(R.id.loadItemsLayout_recyclerView);
Calendar cal = Calendar.getInstance();
month = cal.get(Calendar.MONTH) + 1;
// int year = cal.get(Calendar.YEAR) - 10;
int currentYear = cal.get(Calendar.YEAR);
Log.d("viewMonths", "month is" + month + " " + currentYear);
for (int j = month; j > 0; j--) {
monthNameInAdapter = new DisplayMonth();
monthName = getMonth(j);
monthNameInAdapter.setMonth(monthName);
status.add(monthNameInAdapter);
}
mAdapter = new addBankTransactionList(getApplicationContext(),
month, status, bankname, accno, currentYear, amount);
return 0;
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
// progress.dismiss();
if (progress != null) {
progress.dismiss();
progress = null;
}
try {
statement.setAdapter(mAdapter);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Main Xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/white"
android:fitsSystemWindows="true"
android:gravity="center"
android:orientation="vertical" >
<android.support.v7.widget.Toolbar
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbarTransactionListMonthWise"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="?colorPrimary"
android:minHeight="?actionBarSize"
android:paddingRight="10dp"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" >
</android.support.v7.widget.Toolbar>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
card_view:cardCornerRadius="5dp"
card_view:cardUseCompatPadding="true" >
<RelativeLayout
android:id="#+id/rlBankNameAndBalance"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#color/green_100"
android:clickable="true"
android:gravity="right"
android:orientation="vertical"
android:paddingLeft="#dimen/main_list_data_disp_padding_left"
android:paddingRight="#dimen/main_list_data_disp_padding_right"
android:paddingTop="#dimen/main_list_data_disp_padding_top" >
<TextView
android:id="#+id/tvBankNameForHistory"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/iconId"
android:text="#string/BankBalance"
android:textColor="#color/gray_900"
android:textSize="#dimen/main_list_data_disp_text_size" />
<TextView
android:id="#+id/tvBankAccNoForHistory"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tvBankNameForHistory"
android:text="#string/BankBalance"
android:textColor="#color/gray_500"
android:textSize="14sp" />
<TextView
android:id="#+id/tvNetBalanceForHistory"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:textColor="#color/gray_900"
android:textSize="#dimen/main_list_data_disp_text_size" />
</RelativeLayout>
</android.support.v7.widget.CardView>
<ListView
android:id="#+id/list_transaction_view"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_margin="2dp"
android:scrollbars="none" />
<include
android:id="#+id/loadItemsLayout_recyclerView"
android:layout_width="fill_parent"
android:layout_height="110dp"
android:layout_alignParentBottom="true"
layout="#layout/progress_layout"
android:visibility="gone" />
Main Adapter Class:
public class addBankTransactionList extends BaseAdapter {
// Activity activityCategory;
static ArrayList<DisplayMonth> monthName;
// ArrayList<DisplayYear> yearName;
ArrayList<Expense> expense;
ArrayList<Income> incomes, Arr;
#SuppressWarnings("rawtypes")
ArrayList<String> arrDateDebit, arrDateCredit;
ArrayList<Double> arrAmountDebit, arrAmountCredit;
Context contextAddBank;
int CurrentMonth;
String bankNameForMatch, months, allyear, SystemMonthInString, amount,
bankAccNoForMatch;
int monthname;
String currencySymbl, cur_sym;
String date = "", thirdYear;
String monthNameInString;
EPreferences epref;
ArrayList<Income> tempIncomeses = new ArrayList<Income>();
String dateIncome, dateExpense;
Double expenseAmount, incomeAmount;
DataBaseAdapter adapter;
// private String ;
int monthNameInStringExpense, monthNameInStringIncome;
int yr, year;
int monthsInIntIncome, dateInIntIncome, yearInIntIncome,
monthsInIntExpense;
String convertDate;
// private ArrayList<Income> tempincomes = new ArrayList<Income>();
List list;
Date date1;
String emptyExpenseAmount, emptyIncomeAmount;
FilterData data;
private String bankname, accno;
public static Boolean isScrolling = true;
public static class ViewHolder {
public TextView tvDate, tvIncomeMoney, tvExpenseMoney,
tvRecordnotFound, tvIncomeSymblIncomeDisp, tvTransactionType,
tvTransactionDate, tvTransactionAmount, tvMoneyCurrencyExpense,
tvMoneyCurrencyIncome;
ListView rvList;
}
public addBankTransactionList(Context mcontext, int month,
ArrayList<DisplayMonth> status, String bankname, String bankAccNo,
int year, String amt) {
super();
this.contextAddBank = mcontext;
monthName = status;
CurrentMonth = month;
bankNameForMatch = bankname;
bankAccNoForMatch = bankAccNo;
yr = year;
amount = amt;
}
public boolean setListViewHeightBasedOnItems(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter != null) {
int numberOfItems = listAdapter.getCount();
Log.i("TotalRecord", numberOfItems + "");
int totalItemsHeight = 0;
for (int itemPos = 0; itemPos < numberOfItems; itemPos++) {
View item = listAdapter.getView(itemPos, null, listView);
item.measure(0, 0);
totalItemsHeight += item.getMeasuredHeight();
}
int totalDividersHeight = listView.getDividerHeight()
* (numberOfItems - 1);
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalItemsHeight + totalDividersHeight;
listView.setLayoutParams(params);
listView.requestLayout();
listView.setClickable(false);
listView.setEnabled(false);
return true;
} else {
return false;
}
}
private void getPrefData() {
cur_sym = epref.getPreferencesStr(epref.KEY_CURRENCY, "India");
Log.d("vaaaaa", " == " + cur_sym);
if (cur_sym.equalsIgnoreCase("India")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.India);
} else if (cur_sym.equalsIgnoreCase("US")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.United_States);
} else if (cur_sym.equalsIgnoreCase("Japan")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.Japan);
} else if (cur_sym.equalsIgnoreCase("England")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.England_pound);
} else if (cur_sym.equalsIgnoreCase("Costa Rica")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.Costa);
} else if (cur_sym.equalsIgnoreCase("UK")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.United);
} else if (cur_sym.equalsIgnoreCase("Phillipines")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.Philippines);
} else if (cur_sym.equalsIgnoreCase("Mangolia")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.Macedonia);
} else if (cur_sym.equalsIgnoreCase("Australia")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.Australia);
} else if (cur_sym.equalsIgnoreCase("Europ")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.Euro);
}
}
private int getMonthName(String month1) {
switch (month1.toLowerCase().toString()) {
case "Jan":
monthname = 1;
break;
case "Feb":
monthname = 2;
break;
case "Mar":
monthname = 3;
break;
case "Apr":
monthname = 4;
break;
case "May":
monthname = 5;
break;
case "Jun":
monthname = 6;
break;
case "Jul":
monthname = 7;
break;
case "Aug":
monthname = 8;
break;
case "Sep":
monthname = 9;
break;
case "Oct":
monthname = 10;
break;
case "Nov":
monthname = 11;
break;
case "Dec":
monthname = 12;
break;
default:
break;
}
return monthname;
}
#Override
public int getCount() {
return monthName.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int position, View conView, ViewGroup parent) {
ViewHolder vh;
if (conView == null) {
conView = LayoutInflater.from(contextAddBank).inflate(
R.layout.transaction_list, null, false);
vh = new ViewHolder();
vh.tvDate = (TextView) conView.findViewById(R.id.tvDate);
vh.rvList = (ListView) conView
.findViewById(R.id.lvDisplayExpenseList);
vh.tvIncomeMoney = (TextView) conView
.findViewById(R.id.tvIncomeMoney);
vh.tvExpenseMoney = (TextView) conView
.findViewById(R.id.tvExpenseMoney);
vh.tvRecordnotFound = (TextView) conView
.findViewById(R.id.tvrecordnotFound);
vh.tvIncomeSymblIncomeDisp = (TextView) conView
.findViewById(R.id.tvIncomeSymblIncomeDisp);
vh.tvMoneyCurrencyExpense = (TextView) conView
.findViewById(R.id.tvMoneyCurrencyExpense);
vh.tvMoneyCurrencyIncome = (TextView) conView
.findViewById(R.id.tvMoneyCurrencyIncome);
adapter = new DataBaseAdapter(contextAddBank);
arrDateDebit = new ArrayList<String>();
arrAmountDebit = new ArrayList<Double>();
arrDateCredit = new ArrayList<String>();
arrAmountCredit = new ArrayList<Double>();
epref = EPreferences.getInstance(contextAddBank);
incomes = new ArrayList<Income>();
expense = new ArrayList<Expense>();
getPrefData();
vh.tvMoneyCurrencyExpense.setText(currencySymbl);
vh.tvMoneyCurrencyIncome.setText(currencySymbl);
adapter.open();
adapter.close();
conView.setTag(vh);
} else {
vh = (ViewHolder) conView.getTag();
}
expense.clear();
incomes.clear();
arrDateCredit.clear();
arrAmountCredit.clear();
arrDateDebit.clear();
arrAmountDebit.clear();
adapter.open();
// viewHolder.rvList.setAdapter(Adapter);
incomes = adapter.read_income();
expense = adapter.read_expense();
double totalExpense = 0.0;
double totalIncome = 0.0;
DisplayMonth month = monthName.get(position);
vh.tvDate.setText(month.getMonth() + " " + yr);
months = month.getMonth();
Log.d("tagNameAdapter",
"name is " + bankNameForMatch + ":::" + month.getMonth());
Log.d("expencesize", "size is " + expense.size());
// expense = adapter.read_expense_with_bankName(bankNameForMatch,
// bankAccNoForMatch);
if (expense.size() > 0) {
for (int l = 0; l < expense.size(); l++) {
Log.d("tagbankfil",
"" + bankNameForMatch + "=="
+ expense.get(l).getBankname() + " AND "
+ expense.get(l).getAccno() + "=="
+ bankAccNoForMatch);
if (bankNameForMatch.equals(expense.get(l).getBankname())
&& bankAccNoForMatch.substring(
bankAccNoForMatch.length() - 3)
.equalsIgnoreCase(
expense.get(l)
.getAccno()
.substring(
expense.get(l)
.getAccno()
.length() - 3))) {
dateExpense = expense.get(l).getDate();
expenseAmount = expense.get(l).getAmount();
Log.i("ExpenseAmount", expenseAmount + ":::::"
+ dateExpense);
Calendar calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
StringTokenizer tokensIncome = new StringTokenizer(
dateExpense, "-");
String firstDate = tokensIncome.nextToken();
String secondMonth = tokensIncome.nextToken();
thirdYear = tokensIncome.nextToken();
monthsInIntExpense = Integer.parseInt(secondMonth);
int totalYear = Integer.parseInt(thirdYear);
Log.i("MonthNameExpense", totalYear + "");
Log.i("MonthSplitExpense", firstDate + " " + secondMonth
+ " " + thirdYear);
// for (int jmon = 0; jmon < expense.size(); jmon++) {
Log.i("loopTimes", "Check");
SimpleDateFormat sdfSource = new SimpleDateFormat(
"dd-MM-yyyy");
Date dateVal = null;
Log.i("axisbankdateval", dateVal + "");
try {
dateVal = sdfSource.parse(dateExpense);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat sdfDestination = new SimpleDateFormat(
"dd-MMM-yyyy");
convertDate = sdfDestination.format(dateVal);
String[] parts = convertDate.split("-");
String transactionMonth = parts[1];
String transactionYear = parts[2];
Log.i("allYear", year + " ");
monthNameInStringExpense = getMonthName(transactionMonth);
Log.i("finddate", convertDate + ":::" + transactionMonth
+ ":::" + monthNameInStringExpense + "::"
+ transactionYear);
Log.d("tagmonth", "" + month.getMonth() + " ::: "
+ transactionMonth + " ---- " + totalYear + "::::"
+ year);
if (month.getMonth().contains(transactionMonth)
&& totalYear == year) {
emptyExpenseAmount = vh.tvExpenseMoney.getText()
.toString();
Log.i("dateAmount", " " + expense.get(l).getAmount()
+ " " + expense.get(l).getDate());
arrDateDebit.add(expense.get(l).getDate());
arrAmountDebit.add(expense.get(l).getAmount());
totalExpense += expense.get(l).getAmount();
DecimalFormat decimalFormatExpense = new DecimalFormat(
"0.#");
String finalTotalExpense = decimalFormatExpense
.format(Double.valueOf(totalExpense));
String valTvExpenseAmt = new BigDecimal(
finalTotalExpense).toPlainString();
vh.tvExpenseMoney.setText(String.format("%,.00f",
(double) Double.parseDouble(valTvExpenseAmt))
+ " " + currencySymbl);
if (totalExpense == 0.0) {
vh.tvExpenseMoney.setText("0.0");
vh.tvMoneyCurrencyExpense.setText(currencySymbl);
} else {
if (vh.tvRecordnotFound.getVisibility() == View.VISIBLE) {
vh.tvRecordnotFound.setVisibility(View.GONE);
vh.tvMoneyCurrencyExpense
.setVisibility(View.INVISIBLE);
vh.tvExpenseMoney.setText(" " + totalExpense
+ " " + currencySymbl);
vh.tvMoneyCurrencyExpense
.setText(currencySymbl);
}
}
}
}
}
}
if (incomes.size() > 0) {
for (int j = 0; j < incomes.size(); j++) {
Log.d("tagbankfil",
"" + bankNameForMatch + "=="
+ incomes.get(j).getIncome_bankname() + " AND "
+ incomes.get(j).getIncome_accno() + "=="
+ bankAccNoForMatch);
if (bankNameForMatch
.equals(incomes.get(j).getIncome_bankname())
&& bankAccNoForMatch
.substring(bankAccNoForMatch.length() - 3)
.equalsIgnoreCase(
incomes.get(j)
.getIncome_accno()
.substring(
incomes.get(j)
.getIncome_accno()
.length() - 3))) {
dateIncome = incomes.get(j).getIncome_date();
incomeAmount = incomes.get(j).getIncome_amount();
Log.i("IncomeAmount", incomeAmount + ":::::" + dateIncome);
Calendar calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
StringTokenizer tokensIncome = new StringTokenizer(
dateIncome, "-");
String firstDate = tokensIncome.nextToken();
String secondMonth = tokensIncome.nextToken();
thirdYear = tokensIncome.nextToken();
monthsInIntIncome = Integer.parseInt(thirdYear);
int totalYear = Integer.parseInt(thirdYear);
Log.i("MonthNameIncome", monthsInIntIncome + " " + ""
+ monthNameInStringIncome + " " + dateIncome + " "
+ incomes.size() + "" + totalYear);
Log.i("MonthSplitIncome", firstDate + " " + secondMonth
+ " " + thirdYear);
Log.i("loopTimes", "Check");
SimpleDateFormat sdfSource = new SimpleDateFormat(
"dd-MM-yyyy");
Date dateVal = null;
Log.i("axisbankdateval", dateVal + "");
try {
dateVal = sdfSource.parse(dateIncome);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat sdfDestination = new SimpleDateFormat(
"dd-MMM-yyyy");
convertDate = sdfDestination.format(dateVal);
String[] parts = convertDate.split("-");
String transactionMonth = parts[1];
String transactionYear = parts[2];
monthNameInStringIncome = getMonthName(transactionMonth);
Log.i("finddate", convertDate + "::" + monthname + "::"
+ monthNameInStringIncome);
if (month.getMonth().contains(transactionMonth)
&& totalYear == year) {
emptyIncomeAmount = vh.tvIncomeMoney.getText()
.toString();
arrDateCredit.add(incomes.get(j).getIncome_date());
arrAmountCredit.add(incomes.get(j).getIncome_amount());
totalIncome += incomes.get(j).getIncome_amount();
DecimalFormat decimalFormatIncome = new DecimalFormat(
"0.#");
String finalTotalIncome = decimalFormatIncome
.format(Double.valueOf(totalIncome));
String valTvIncomeAmt = new BigDecimal(finalTotalIncome)
.toPlainString();
vh.tvIncomeMoney.setText(String.format("%,.00f",
(double) Double.parseDouble(valTvIncomeAmt))
+ " ");
vh.tvMoneyCurrencyIncome.setText(currencySymbl);
if (totalIncome == 0.0) {
vh.tvIncomeMoney.setText("0.0");
vh.tvMoneyCurrencyIncome.setText(currencySymbl);
} else {
if (vh.tvRecordnotFound.getVisibility() == View.VISIBLE) {
vh.tvRecordnotFound.setVisibility(View.GONE);
vh.tvIncomeMoney.setText(" " + totalIncome
+ " " + currencySymbl);
}
}
}
}
}
Log.i("currentYear", year + "" + thirdYear);
}
CategoryList categoryListAdapter = new CategoryList(contextAddBank,
arrDateDebit, arrAmountDebit, arrDateCredit, arrAmountCredit);
vh.rvList.setAdapter(categoryListAdapter);
setListViewHeightBasedOnItems(vh.rvList);
vh.rvList.setScrollContainer(true);
categoryListAdapter.notifyDataSetChanged();
return conView;
}
}
Your application is sticking when you're scrolling down because you're doing all of that processing upon every move when you scroll. Every row is running through the statements of your getView method every single time it's brought back to the screen, phones don't have enough processing power for all of that. You need to separate all of that into a different class, and then load it into the adapter in a smaller data set so that all it has to do is display it. Basically, you're doing processing in the UI(Main) thread, which is bad.
Given how you also have nested listViews, changing to an expandedListView would also be a lot easier for you in the grand scheme of things, may do the job better. Here's a tutorial for it: https://www.youtube.com/watch?v=BkazaAeeW1Q

Item deleting from listview affecting asynctask

I am making a multi-video downloader. I have created a listview and for each item in the listview an asynctask is called which downloads the file in the background. Everything works perfect. But, if i want to delete an item from the listview for example from position 2, the item at position 3 (both are currently running) comes on position 2 and the asynctask attached previously to position 2 continues running and it shows the progress of asynctask that was previously attached to the position 2. How can I move the asynctask of position 3 to position 2.
Here is my Adapter Class from where I am calling the asynctask class:
public class DownloadInfoArrayAdapter extends ArrayAdapter<DownloadInfo> {
public static TextView progpercent;
// Simple class to make it so that we don't have to call findViewById frequently
// private static final String TAG = FileDownloadTask.class.getSimpleName();
public static Integer result;
LayoutInflater inflater5;
ImageView delete;
Activity activity1;
int mvalue;
ContextWrapper cw1;
int flag=0;
int status=0;
GlobalDownload downloadList;
ArrayList downloadState;
FileDownloadTask task;
private static class ViewHolder {
TextView textView;
ProgressBar progressBar;
ImageView delete;
DownloadInfo info;
TextView size;
TextView prog;
public TextView progpercent;
}
private static final String TAG = DownloadInfoArrayAdapter.class.getSimpleName();
public DownloadInfoArrayAdapter(Context context, int textViewResourceId,
List<DownloadInfo> objects, ContextWrapper cw, Activity DownloadScreen) {
super(context, textViewResourceId, objects);
cw1=cw;
activity1=DownloadScreen;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
final DownloadInfo info = getItem(position);
ViewHolder holder = null;
if(null == row) {
LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.file_download_row, parent, false);
holder = new ViewHolder();
holder.textView = (TextView) row.findViewById(R.id.downloadFileName);
holder.progressBar = (ProgressBar) row.findViewById(R.id.downloadProgressBar);
holder.size=(TextView) row.findViewById(R.id.downloadFileSize);
holder.progpercent=(TextView) row.findViewById(R.id.downloadFileProgress);
holder.delete=(ImageView) row.findViewById(R.id.deletebutton);
// holder.button = (Button)row.findViewById(R.id.downloadButton);
// holder.info = info;
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
holder.textView.setText(info.getFilename());
holder.progpercent.setText(info.getDownloadState().toString());
if(info.getStatus()== null)
{
Log.e("DATABASE1", "null ");
status=3;
info.setLastState(2);
}
else if(info.getStatus()== DownloadInfo.State.DONE)
{
if(info.getLastState()==1)
{
Log.e("DATABASE", "LS " + 1);
info.setDownloadState(DownloadInfo.DownloadState.COMPLETE);
status=1;
}
else if(info.getLastState()==0)
{
Log.e("DATABASE", "LS " + 2);
info.setDownloadState(DownloadInfo.DownloadState.FAILED);
status=1;
}
else
{
status=2;
}
}
Log.e("DATABASE", "DOWNLOAD STATE " + info.getDownloadState().toString());
if(info.getDownloadState()== DownloadInfo.DownloadState.NOT_STARTED)
{
if(status==3) {
holder.progressBar.setProgress(info.getProgress());
holder.progressBar.setMax(100);
holder.progpercent.setText("DOWNLOADING");
}
}
holder.size.setText(info.getFileSize());
info.setProgressBar(holder.progressBar);
if(info.getDownloadState()==DownloadInfo.DownloadState.NOT_STARTED){ info.setDownloadState(DownloadInfo.DownloadState.DOWNLOADING);
if (MainScreen.settingsvalue==0) {
Log.e("DATABASE", " " + 0);
mvalue = 0;
task = new FileDownloadTask(info, cw1, activity1, mvalue);
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
if(info.getDownloadState()== DownloadInfo.DownloadState.COMPLETE) {
Log.e("DATABASE", "UPDATE COMPLETE " + info.getDownloadState());
info.setStatus(DownloadInfo.State.DONE);
info.setLastState(1);
holder.progressBar.setProgress(R.drawable.download_bar);
holder.progpercent.setText(info.getDownloadState().toString());
cancelstatus=0;
}
if(info.getDownloadState()== DownloadInfo.DownloadState.FAILED) {
info.setStatus(DownloadInfo.State.DONE);
MainScreen.newDB.execSQL("update " + DatabaseHelper.TABLE_NAME + " set " + DatabaseHelper.COL_6 + " = '" + info.getStatus() + "', " + DatabaseHelper.COL_7 + " =0 where " + DatabaseHelper.COL_1 + " = " + info.getFileid());
Log.e("DATABASE", "UPDATED ");
info.setLastState(0);
holder.progpercent.setText(info.getDownloadState().toString());
cancelstatus=0;
}
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer index = (Integer) v.getTag();
Log.e("POSITION", "TAG " + index);
Log.e("POSITION", "POSITION " + position);
downloadList = ((GlobalDownload) activity1.getApplicationContext());
downloadState = (ArrayList) downloadList.getDownloadInfo();
CustomDialogClass.downloadfile=file.getAbsolutePath().toString();
CustomDialogClass2.customfilename2= info.getFilename() + "." + info.getFileType();
Log.e("VIDEOPATH", " " + CustomDialogClass.downloadfile);
CustomDialogClass2 cdd = new CustomDialogClass2(MainScreen.activity1);
cdd.show();
CustomDialogClass2.mPosition=position;
CustomDialogClass2.id=info.getFileid();
// downloadState.remove(position);
Log.e("STATUS", "Status before stopping " + info.getDownloadState());
if((info.getDownloadState()== DownloadInfo.DownloadState.DOWNLOADING)) {
info.setDownloadState(DownloadInfo.DownloadState.COMPLETE);
cancelstatus=1;
task.cancel(true);
}
}
});
return row;
}
}
Here is the Asynctask class
public class FileDownloadTask extends AsyncTask<String, Integer, Integer> {
private static final String TAG = FileDownloadTask.class.getSimpleName();
final DownloadInfo mInfo;
TextView display;
public int progress;
public String encodedurl;
PopupWindow popupWindow;
Activity activity;
// ListView listview1;
// Context context;
LayoutInflater layoutInflater;
static int i=0;
int Mvalue;
ContextWrapper cw;
File file;
String nameoffile;
PowerManager mgr;
PowerManager.WakeLock wakeLock;
public static int cancelstatus =0;
int a=0;
// DownloadInfoArrayAdapter mAdapter;
public FileDownloadTask(DownloadInfo info, ContextWrapper cw1, Activity activity1, int mvalue) {
mInfo = info;
cw=cw1;
activity=activity1;
this.Mvalue=mvalue;
// listView1 = (ListView) listview.findViewById(R.id.downloadListView);
// mAdapter = new DownloadInfoArrayAdapter(, R.id.downloadListView,mInfo);
}
// #Override
protected void onProgressUpdate(Integer... values) {
mInfo.setProgress(values[0]);
mInfo.setFilePercent(values[0]);
// Log.e("FILE PERCENT", String.valueOf(mInfo.getFilePercent()));
// mAdapter.notifyDataSetChanged();
// mAdapter.setNotifyOnChange(true);
// display = (TextView) row.findViewById(R.id.downloadFileProgress);
ProgressBar bar = mInfo.getProgressBar();
// Integer percent=mInfo.getFilePercent();
if (bar != null) {
bar.setProgress(mInfo.getProgress());
// percent(mInfo.getFilePercent());
// display.setText(mInfo.getProgress());
// bar.invalidate();
}
// DownloadScreen.adapter.notifyDataSetChanged();
// DownloadScreen.listView.setAdapter(DownloadScreen.adapter);
}
#Override
protected void onCancelled() {
super.onCancelled();
mInfo.setDownloadState(DownloadInfo.DownloadState.COMPLETE);
File rootdirectory = new File(Environment.getExternalStorageDirectory(), "YoutubeDownloaderVideos");
File file = new File(rootdirectory, CustomDialogClass2.customfilename2);
Log.e("FILE", " name" + file.toString());
file.delete();
DownloadScreen.adapter.notifyDataSetChanged();
}
#Override
protected Integer doInBackground(String... params) {
int count;
try {
String state = Environment.getExternalStorageState();
String root = Environment.getExternalStorageDirectory().toString();
URL url = new URL(mInfo.getFileUrl().toString());
Log.e("URL", "" + url);
HttpURLConnection conection = (HttpURLConnection) url.openConnection();
conection.connect();
Log.e("connection", " " + 0);
int lenghtOfFile = conection.getContentLength();
Log.e("length", "" + lenghtOfFile);
String nameoffile = mInfo.getFilename() + "." + mInfo.getFileType();
if (Environment.MEDIA_MOUNTED.equals(state)) {
File rootdirectory = new File(Environment.getExternalStorageDirectory(), "YoutubeDownloaderVideos");
if (!rootdirectory.exists()) {
rootdirectory.mkdirs();
}
File file = new File(rootdirectory, nameoffile);
file.createNewFile();
Log.e("name of file", "" + nameoffile);
InputStream input = new BufferedInputStream(url.openStream(), 8192);
OutputStream output = new FileOutputStream(file);
byte data[] = new byte[1024];
mInfo.setDownloadState(DownloadInfo.DownloadState.DOWNLOADING);
long total = 0;
while ((count = input.read(data)) != -1) {
if(!isCancelled()) {
total += count;
progress = (int) ((total * 100) / lenghtOfFile);
publishProgress(progress);
// Log.e("PROGRESS", "" + mInfo.getFileType() + progress);
mInfo.setFilePercent(progress);
output.write(data, 0, count);
i = 1;
}
}
mInfo.setDownloadState(DownloadInfo.DownloadState.COMPLETE);
mInfo.setStatus(DownloadInfo.State.COMPLETE);
output.flush();
output.close();
input.close();
Log.e("Download Complete", "" + 0);
Log.e("DEVICE SDCARD", " " + Mvalue);
}
return progress;
}
protected void onPostExecute(Integer progress) {
mInfo.setDownloadState(DownloadInfo.DownloadState.COMPLETE);
DownloadScreen.adapter.notifyDataSetChanged();
DownloadScreen.listView.setAdapter(DownloadScreen.adapter);
Uri contentUri = Uri.fromFile(file);
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,contentUri);
activity.sendBroadcast(mediaScanIntent);
CustomDialogClass.downloadfile=file.getAbsolutePath().toString();
CustomDialogClass.customfilename=mInfo.getFilename() + "." + mInfo.getFileType();
Log.e("VIDEOPATH", " " + CustomDialogClass.downloadfile);
CustomDialogClass cdd = new CustomDialogClass(MainScreen.activity1);
cdd.show();
}
#Override
protected void onPreExecute() {
}
}
you should override the remove method of your adapter in order to cancel properly the asyncTask associated to your item.

Categories

Resources