Related
Hi I am new to android i have searching this for a week,
i have a fragment that contains
textview
editext
spinner
calender
image choosing
Adding and removing same fragment in an container with unique tag. in spinner there is multiple numbers that is displayed in activity dynamically, if i add or remove same fragment, the values shown in textview should change dynamically. I know to access each instance by its tag and can get the values in activity but unable to find which fragment instance have changed.
For example, if i have added same fragment four times, made change in spinner in all the four fragment, unable to identify which instance have increased or decreased and correct the total
And also unable to find whether image is added or not.
My fragment is
public class Service_details extends Fragment {
private static final String IMAGE_DIRECTORY = "/demonuts";
private int GALLERY = 1, CAMERA = 2;
ProgressDialog pDialog;
TextView textView_service_no, textView_datePicker, textView_amount, textView_optionalDate;
Spinner spinner_services;
EditText editText_dedicated, editText_intention;
ImageView display_photo;
HashMap<String, String> cList = new HashMap<>();
String[] services;
String initial_spinner_value;
String birthday_price;
String deathday_price;
String rosary_price;
String mass_price;
String prayer_price;
String marriageday_price;
OnMessageReadListener messageReadListener;
String service_value = null;
String service_spinner_string=null;
String person_image_string =null;
String editText_dedicated_string=null;
String editText_intention_string=null;
String textView_telecast_date_string=null;
String textView_amount_string =null;
String total_amount_string=null;
String tax_amount_string=null;
String final_total_amount_string=null;
int c;
int count;
String TAG = "Fragment";
Bitmap bitmap;
LinearLayout linearLayout10;
public interface OnMessageReadListener {
void onMessageRead(String message);
}
public Service_details() {
// Required empty public constructor
}
public static Service_details newInstance(int i) {
Service_details service_details = new Service_details();
Bundle bundle = new Bundle();
int c = i;
bundle.putInt("service_count",i);
service_details.setArguments(bundle);
return service_details;
}
Calendar cal;
public String message;
String path;
int temp;
int a;
#SuppressLint("SetTextI18n")
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_service_details, container, false);
textView_service_no = view.findViewById(R.id.service_counting);
editText_dedicated = view.findViewById(R.id.editText_dedicated_to);
editText_intention = view.findViewById(R.id.editText_intention);
textView_datePicker = view.findViewById(R.id.date_picker);
spinner_services = view.findViewById(R.id.spinner_services);
textView_amount = view.findViewById(R.id.textview_amount);
display_photo = view.findViewById(R.id.display_photo);
textView_optionalDate = view.findViewById(R.id.textview_exactDate);
cal = Calendar.getInstance();
linearLayout10 = view.findViewById(R.id.linear10);
ButterKnife.bind(this, view);
getJson();
assert getArguments() != null;
count = getArguments().getInt("service_count");
Log.e(TAG, "count value : "+ count);
textView_service_no.setText(valueOf(count));
++count;
a=0;
display_photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showPictureDialog();
}
});
textView_optionalDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerDialog dialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
textView_optionalDate.setText(""+arg3+"/"+(arg2+1)+"/"+arg1);
Toast.makeText(getActivity(), ""+arg3+"/"+(arg2+1)+"/"+arg1, Toast.LENGTH_SHORT).show();
}
}, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));
dialog.show();
}
});
textView_datePicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerDialog dialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
textView_datePicker.setText(""+arg3+"/"+(arg2+1)+"/"+arg1);
Toast.makeText(getActivity(), ""+arg1+"/"+(arg2+1)+"/"+arg3, Toast.LENGTH_SHORT).show();
}
}, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));
cal.add(Calendar.DAY_OF_WEEK_IN_MONTH, 5);
dialog.getDatePicker().setMinDate(cal.getTimeInMillis());
dialog.show();
}
});
services = new String[]{"Select Service","Birth Day", "Death Day", "Rosary", "Hollymass", "Prayer", "Marriage Day"};
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item, services);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner_services.setAdapter(arrayAdapter);
spinner_services.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String spin_value = parent.getItemAtPosition(position).toString();
((Services)getActivity()).setCurrentSpinnerItem(spin_value);
switch (position) {
case 0:
textView_amount.setText(cList.get("empty"));
display_photo.setVisibility(View.GONE);
linearLayout10.setVisibility(View.GONE);
Log.e(TAG,"textView_amount (fragment name)"+ textView_amount.getTag());
String message_temp = textView_amount.getText().toString();
if(!message_temp.equals("")){
a = Integer.parseInt(message_temp);
}
a = a-temp;
message = Integer.toString(a);
Log.e(TAG, "message_temp: "+message_temp);
messageReadListener.onMessageRead(message);
break;
case 1:
textView_amount.setText(cList.get("birthday_price"));
display_photo.setVisibility(View.VISIBLE);
linearLayout10.setVisibility(View.VISIBLE);
message_temp = textView_amount.getText().toString();
if(!message_temp.equals("")){
a = Integer.parseInt(message_temp);
}
a = a-temp;
message = Integer.toString(a);
a= Integer.parseInt(message_temp);
a= a-temp;
message = Integer.toString(a);*/
messageReadListener.onMessageRead(message);
break;
case 2:
textView_amount.setText(cList.get("deathday_price"));
display_photo.setVisibility(View.VISIBLE);
linearLayout10.setVisibility(View.GONE);
message_temp = textView_amount.getText().toString();
if(!message_temp.equals("")){
a = Integer.parseInt(message_temp);
}
a = a-temp;
message = Integer.toString(a);
messageReadListener.onMessageRead(message);
break;
case 3:
textView_amount.setText(cList.get("rosary_price"));
display_photo.setVisibility(View.GONE);
linearLayout10.setVisibility(View.GONE);
message_temp = textView_amount.getText().toString();
if(!message_temp.equals("")){
a = Integer.parseInt(message_temp);
}
a = a-temp;
message = Integer.toString(a);
messageReadListener.onMessageRead(message);
break;
case 4:
textView_amount.setText(cList.get("mass_price"));
display_photo.setVisibility(View.GONE);
linearLayout10.setVisibility(View.GONE);
message_temp = textView_amount.getText().toString();
if(!message_temp.equals("")){
a = Integer.parseInt(message_temp);
}
a = a-temp;
message = Integer.toString(a);
messageReadListener.onMessageRead(message);
break;
case 5:
textView_amount.setText(cList.get("prayer_price"));
display_photo.setVisibility(View.GONE);
linearLayout10.setVisibility(View.GONE);
message_temp = textView_amount.getText().toString();
if(!message_temp.equals("")){
a = Integer.parseInt(message_temp);
}
a = a-temp;
message = Integer.toString(a);
messageReadListener.onMessageRead(message);
break;
case 6:
textView_amount.setText(cList.get("marriageday_price"));
display_photo.setVisibility(View.GONE);
linearLayout10.setVisibility(View.VISIBLE);
message_temp = textView_amount.getText().toString();
if(!message_temp.equals("")){
a = Integer.parseInt(message_temp);
}
a = a-temp;
message = Integer.toString(a);
messageReadListener.onMessageRead(message);
break;
}
// String message = textView_amount.getText().toString();
// messageReadListener.onMessageRead(message);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
return view;
}
private void showPictureDialog(){
AlertDialog.Builder pictureDialog = new AlertDialog.Builder(getActivity());
pictureDialog.setTitle("Select Action");
String[] pictureDialogItems = {
"Select photo from gallery",
"Capture photo from camera" };
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
choosePhotoFromGallary();
break;
case 1:
takePhotoFromCamera();
break;
}
}
});
pictureDialog.show();
}
public void choosePhotoFromGallary() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, GALLERY);
}
private void takePhotoFromCamera() {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == getActivity().RESULT_CANCELED) {
return;
}
if (requestCode == GALLERY) {
if (data != null) {
Uri contentURI = data.getData();
Log.e(TAG, "contentURI : " + contentURI);
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), contentURI);
String path = saveImage(bitmap);
Toast.makeText(getActivity(), "Image Saved!", Toast.LENGTH_SHORT).show();
display_photo.setImageBitmap(bitmap);
Log.e(TAG, "PATH1" + path);
Log.e(TAG, "BITMAP " + bitmap);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Failed!", Toast.LENGTH_SHORT).show();
}
}
} else if (requestCode == CAMERA) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
display_photo.setImageBitmap(thumbnail);
path = saveImage(thumbnail);
Log.e(TAG, "PATH2" + path);
saveImage(thumbnail);
Toast.makeText(getActivity(), "Image Saved!", Toast.LENGTH_SHORT).show();
}
}
public String saveImage(Bitmap myBitmap) {
Log.e(TAG, "PATH3" + path);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File wallpaperDirectory = new File(
Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
Log.e(TAG, "wallpaperDirectory" + wallpaperDirectory);
if (!wallpaperDirectory.exists()) {
wallpaperDirectory.mkdirs();
}
try {
File f = new File(wallpaperDirectory, Calendar.getInstance()
.getTimeInMillis() + ".jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(getActivity(),
new String[]{f.getPath()},
new String[]{"image/jpeg"}, null);
fo.close();
Log.d("TAG", "File Saved::--->" + f.getAbsolutePath());
Log.e(TAG, "File Saved::--->" + f.getAbsolutePath());
Log.e(TAG, "PATH4" + path);
return f.getAbsolutePath();
} catch (IOException e1) {
e1.printStackTrace();
}
return "";
}
/*------------------------------------------------------------------------------------------------------------*/
public void getDetailsFromFragment() {
service_value = textView_service_no.getText().toString();
editText_dedicated_string = editText_dedicated.getText().toString();
editText_intention_string = editText_intention.getText().toString();
textView_telecast_date_string = textView_datePicker.getText().toString();
textView_amount_string = textView_amount.getText().toString();
service_spinner_string = spinner_services.getSelectedItem().toString();
if(bitmap!=null){
person_image_string = bitmap.toString();
}
Log.e(TAG, " SERVICE NO. : " + service_value + " \n" + "SERVICES :" + service_spinner_string + " \n" + "DEDICATED TO : " + editText_dedicated_string + " \n" + " INTENTION : " +
editText_intention_string + " \n" + " TELECASTE DATE : " + textView_telecast_date_string + " \n" + " AMOUNT : " + textView_amount_string + "\n" + "IMAGE : " + person_image_string);
Log.e(TAG, "FINAL PAYMENT DETAILS: " + total_amount_string + " " + tax_amount_string + " " + final_total_amount_string);
messageReadListener.onMessageRead(message);
}
public void changeCount(int a){
c = a;
textView_service_no.setText(valueOf(c));
}
#Override
public void onAttach (Context context){
super.onAttach(context);
Activity activity = (Activity) context;
try {
messageReadListener = (OnMessageReadListener) activity;
} catch (ClassCastException c) {
throw new ClassCastException(activity.toString() + " must override onMessageReadListener...");
}
}
}
My activity is
public class Services extends DashBoard implements Service_details.OnMessageReadListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_services);
}
#OnClick(R.id.add_service)
public void addService(){
service_one_amount = Integer.parseInt(message4);
// service_one_amount = message4;
Log.e(TAG, "service_one_amount : "+ service_one_amount);
// service_one_amount = service_one_amount+ ;
if(size<5){
fragTag = "numericField" + numericFragmentCount;
getSupportFragmentManager().beginTransaction().add(R.id.container_frame,Service_details.newInstance(a), fragTag).commit();
++a;
++numericFragmentCount;
Log.e(TAG, "fragment size: "+ size);
}else {
Toast.makeText(this,"Maximum limit reached",Toast.LENGTH_LONG).show();
}
}
#OnClick(R.id.remove_service)
public void removeService(){
size= getSupportFragmentManager().getFragments().size();
if(size>1) {
--numericFragmentCount;
fragTag = "numericField" + numericFragmentCount;
fragment = getSupportFragmentManager().findFragmentById(R.id.container_frame);
if (fragment != null) {
getSupportFragmentManager().beginTransaction().remove(fragment).commit();
--a;
}
Log.e(TAG, "fragment : " + fragment);
}else {
Toast.makeText(this,"Minimum limit reached",Toast.LENGTH_LONG).show();
}
}
#SuppressLint("SetTextI18n")
#Override
public void onMessageRead(String message) {
try{
String identity_frag = "numericField1";
Fragment service_details1 = getSupportFragmentManager().findFragmentByTag("numericField1");
Fragment service_details2 = getSupportFragmentManager().findFragmentByTag("numericField2");
Fragment service_details3 = getSupportFragmentManager().findFragmentByTag("numericField3");
Fragment service_details4 = getSupportFragmentManager().findFragmentByTag("numericField4");
Fragment service_details5 = getSupportFragmentManager().findFragmentByTag("numericField5");
Log.e(TAG,"before adding message4: "+message4);
message1 = Integer.parseInt(message);
service_details1 instanceof Service_details;
Log.e(TAG,"before initial temp: "+ temp);
if(!textView_amount_view.getText().toString().equals("0")){
initial_amount= String.valueOf(message4);
}else {
initial_amount =textView_amount_view.getText().toString();
}
message3 = Integer.parseInt(initial_amount);
message1= message3+message1-temp;
temp = message1;
Log.e(TAG,"after initial temp: "+ temp);
message1 = message1+service_one_amount;
long res = (long) Math.ceil((message1/ 100.0f) * 18);
double res1 = ((message1/ 100f) * 18);
Toast.makeText(getApplicationContext(), "" + res1, Toast.LENGTH_SHORT).show();
int final_amount = (int) (message1 + res);
message4 = Integer.toString(message1);
Log.e(TAG,"after adding message4: "+message4);
textView_amount_view.setText(currency_symbol+" "+ String.valueOf(message4));
textView_tax_amount_view.setText(currency_symbol+" "+ String.valueOf(res)+ decimal_value);
textView_total_amount_view.setText(currency_symbol+" "+ String.valueOf(final_amount)+ decimal_value);
Log.e(TAG,"total amount: "+message4);
Log.e(TAG,"tax amount: "+res);
Log.e(TAG,"amount after tax: "+final_amount);
}catch (NumberFormatException e){
e.printStackTrace();
}
}
}
if u find question is hard please upvote to reach more people..
Thanks in advance..
I'm new with android and java, so I apologize if what I say is not entirely correct.
In my application I'd like to convert an ArrayList to integer
to increase each value with a +1. Please note the commented out part to understand where is my problem. I can't find the right way..
This is what I do for now:
public String mRequest(String mUrl, String mAuth, String mParam, String customerId, ArrayList filter) {
InputStream mStreamResponse;
String mString = null;
try {
URL obj = new URL(mUrl);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Authorization", mAuth);
con.setRequestProperty("X-Limit", String.valueOf(xLimit));
con.setRequestProperty("X-Skip", String.valueOf(xSkip));
con.setRequestProperty("X-Sort", "{\"created\":-1}");
String parameters = null;
System.out.println("Value of mParam -> " + mParam);
if (mParam != null && customerId != null) {
Log.e("ERROR", "Ricerca per parametro e customerId");
} else if (mParam != null) {
parameters = "\"number\":{\"$regex\":" + mParam + "}";
} else if (customerId != null) {
parameters = "\"customer.id\":{\"$eq\":" + "\"" + customerId + "\"" + "}";
} else {
parameters = "\"number\":{\"$regex\":\"\"}";
}
System.out.println("parameters");
System.out.println(parameters);
if (filter != null) {
//convert ArrayList to Array
Object[] mArray = filter.toArray();
String filterGroup = mArray[0].toString() + ".id";
System.out.println("Group selected -> " + filterGroup);
for (int i = 1; i < mArray.length; i++) {
System.out.println("Value -> " + mArray[i]);
}
String pFilter = null;
for (int i = 1; i < mArray.length; i++) {
/*
*
* This is where I need to change value in
* pos i with i + 1
*
*/
switch (mArray[i].toString()) {
case "0":
mArray[i] = "1";
break;
case "1":
mArray[i] = "2";
break;
case "2":
mArray[i] = "3";
break;
case "3":
mArray[i] = "4";
break;
case "4":
mArray[i] = "5";
break;
case "5":
mArray[i] = "6";
break;
case "6":
mArray[i] = "7";
break;
case "7":
mArray[i] = "8";
break;
case "8":
mArray[i] = "9";
break;
case "9":
mArray[i] = "10";
break;
case "10":
mArray[i] = "11";
break;
case "11":
mArray[i] = "12";
break;
case "12":
mArray[i] = "13";
break;
}
if (mArray.length == 2){
pFilter = mArray[i].toString();
} else {
if (mArray[i] != mArray[mArray.length - 1]) {
if (pFilter != null) {
pFilter = pFilter + mArray[i].toString() + ",";
} else {
pFilter = mArray[i].toString() + ",";
}
} else {
pFilter = pFilter + mArray[i].toString();
}
}
}
String mFilter = "[" + pFilter + "]";
System.out.println("Insert value in a string -> " + mFilter);
String tempParam = null;
if (filterGroup.equals("assignee")) {
tempParam = "{\"$eq\":" + mFilter + "}";
} else {
tempParam = "{\"$in\":" + mFilter + "}";
}
//Override the value with the same filterGroup
if (filterMap.containsKey(filterGroup)) {
String toOverride = filterGroup;
filterMap.remove(filterGroup);
filterMap.put(toOverride, tempParam);
} else {
filterMap.put(filterGroup, tempParam);
}
//iterate
for (Map.Entry<String, String> entry : filterMap.entrySet()) {
switch (entry.getKey()) {
case "status.id":
status = "\"" + entry.getKey() + "\":" + entry.getValue();
break;
case "queue.id":
queues = "\"" + entry.getKey() + "\":" + entry.getValue();
break;
case "type.id":
types = "\"" + entry.getKey() + "\":" + entry.getValue();
break;
case "severity.id":
severities = "\"" + entry.getKey() + "\":" + entry.getValue();
break;
case "assignee.id":
mytickets = "\"" + entry.getKey() + "\":" + entry.getValue();
break;
}
}
filterMapValues = parameters ;
if (status != null) {
filterMapValues += ", " + status;
}
if (queues != null) {
filterMapValues += ", " + queues;
}
if (types != null) {
filterMapValues += ", " + types;
}
if (severities != null) {
filterMapValues += ", " + severities;
}
if (mytickets != null) {
filterMapValues += ", " + mytickets;
}
String myFilter = "{" + filterMapValues + "}";
System.out.println("myFilter -> " + myFilter);
//setup request header
con.setRequestProperty("X-Filter", myFilter);
} else {
String xFilter = "{\"status.id\":" + statusAll + ", \"queue.id\":" + queueAll + ", \"type.id\":" + typeAll + ", \"severity.id\":" + severityAll + "," + parameters + "}";
con.setRequestProperty("X-Filter", xFilter);
System.out.println("Reset all -> " + xFilter);
}
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + mUrl);
System.out.println("Response Code : " + responseCode);
mStreamResponse = con.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(mStreamResponse));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
mStreamResponse.close();
} catch (IOException e) {
e.printStackTrace();
}
}
mString = sb.toString();
} catch (Exception e) {
}
return mString;
}
How can I do?
Thanks in advance.
Edit
I started the for loop in pos #1 because in pos #0 I save filterGroup value, and that's a String, I need to menage as int only values in pos > 0
First off:
I'd like to convert an ArrayList to integer [...]
ArrayList<E> is a collection object with type E that can be any object or primitive. What you are really asking for is how to convert an ArrayList<String> (see that it is an ArrayList of type String) into an integer array. I can see you have already converted the ArrayList<String> into an Object[] (Object array that can hold both integers and Strings) using the following line in the example code given above:
Object[] mArray = filter.toArray();
Getting back to the original answer, this would do it:
int[] mArray = new int[filter.size()];
for (int i = 0; i < filter.size(); i++) {
int value = Integer.parseInt(filter.get(i));
mArray[i] = value++;
}
Your code is correct just change the for loop initial value to start from 0 rather than 1 like this:
int tempValue = 0;
for (int i = 0; i < mArray.length; i++) {
{
// increasing your mArray value
tempValue = (Integer) mArray[i] + 1;
mArray[i] = tempValue;
//Rest of your code
}
Can you try this please.
Remove your switch case inside for and replace it with below. Hope you want something like this.
for(int i=0; i<mArray.length(); i++){
mArray[i] = i+1;
}
let me know..
Do follwoing
Step 1: Create a method
private List<Integer> stringToIncrementedString(ArrayList<String> stringArrayList){
List<Integer> arrayInt;
arrayInt = new ArrayList<Integer>();
for(int i=1 ;i<stringArrayList.size();i++)
arrayInt.add(Integer.parseInt(stringArrayList.get(i))+1);
return arrayInt;
}
Step 2 :Call this method from where you want.It will return the Arraylist with incremented value.
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
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();
}
public void onCallStateChanged(int state,String incomingNumber)
{
System.out.print("\nState :- "+state);
switch(state){
case TelephonyManager.CALL_STATE_IDLE:
if(flag==true && ringflag == true)
{
flag=false;
ringflag=false;
System.out.print("\nflag = " + flag);
System.out.print("\nringflag = " + ringflag);
stop = System.currentTimeMillis();
System.out.println("\nTotal time : " +stop);
System.out.println("\nTotal time : " +(stop - start)/1000);
System.out.println("\nIDLE : " + incomingNumber);
long time = (stop - start) / 1000;
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
f = new File(path + "/sms.txt");
if (f.exists()) {
try {
raf =new RandomAccessFile(f, "rw");
long pointer = raf.length();
raf.seek(pointer);
String data = ":-"+no+","+time;
raf.writeBytes(data);
raf.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
raf = new RandomAccessFile(f,"rw");
String data = ":-"+no+","+time;
raf.writeBytes(data);
raf.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
if(ringflag == true)
{
System.out.println("OFFHOOK :- " + incomingNumber);
start = System.currentTimeMillis();
System.out.print("\nStart is :-" + start);
flag=true;
}
break;
case TelephonyManager.CALL_STATE_RINGING:
no = incomingNumber;
System.out.println("Ringing : " + incomingNumber);
ringflag= true;
break;
}
}
I can answer the first part of your question
To get the call duration it is important to access the Call Logs.
Using the information given in CallLog.Calls, It can be done like below:
Uri allCalls = Uri.parse("content://call_log/calls");
Cursor c = managedQuery(allCalls, null, null, null, null);
for(String colName : c.getColumnNames())
Log.v(TAG, "Column Name: " + colName);
if (c.moveToFirst())
{
do{
String id = c.getString(c.getColumnIndex(CallLog.Calls._ID));
String num = c.getString(c.getColumnIndex(CallLog.Calls.NUMBER));
int type = Integer.parseInt(c.getString(c.getColumnIndex(CallLog.Calls.TYPE)));
String duration = c.getString(c.getColumnIndex(CallLog.Calls.DURATION));
System.out.println("call time duration is"+duration);
switch (type)
{
case 1: Log.v(TAG, id + ", " +num + ": INCOMING") ; break;
case 2: Log.v(TAG, id + ", " +num + ": OUTGOING") ;break;
case 3: Log.v(TAG, id + ", " +num + ": MISSED") ; break;
}
} while (c.moveToNext());
}
Refer this nice blog post for more information.