想询问有关MPAndroidChart-折线图的问题。我尝试过搜索,但无法找到样本。
1)如何在X的最左侧和最右侧设置标签。(例如:StartDate和EndDate)?
2)如何继续从最后一点绘制线直到AxisMaximum?
关注是我的代码
package com.abc.personalexpensestracker;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import io.github.luizgrp.sectionedrecyclerviewadapter.SectionedRecyclerViewAdapter;
public class ViewBudgetDetail extends AppCompatActivity {
private Toolbar mToolbar;
private LineChart mLineChart;
private SectionedRecyclerViewAdapter mSectionAdapter;
private RecyclerView mBudgetsList;
private DatabaseReference mUsersTransactionsDatabase;
private DatabaseReference mUsersCategoriesDatabase;
private DatabaseReference mUsersBudgetsDatabase;
private FirebaseAuth mAuth;
private FirebaseUser mCurrUser;
private ArrayList<TransactionsData> transactionsDataArrayList =null;
private ArrayList<CategoriesData> categoriesDataArrayList = null;
private String extraName , extraFromDate , extraToDate ;
private Double extraAmt=0.0,extraAmtSpent=0.0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_budget_detail);
mLineChart = (LineChart) findViewById(R.id.budgetLineChart);
mAuth = FirebaseAuth.getInstance();
mCurrUser = mAuth.getCurrentUser();
mUsersTransactionsDatabase = FirebaseDatabase.getInstance().getReference().child("users_transactions").child(mCurrUser.getUid()).child("by_year");
mUsersCategoriesDatabase = FirebaseDatabase.getInstance().getReference().child("users_categories").child(mCurrUser.getUid()).child("expenses");
mToolbar = (Toolbar) findViewById(R.id.toolbar_ViewBudget);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("Budget Detail");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//Binding selected data from recyclerView
Bundle getBundle = null;
getBundle = this.getIntent().getExtras();
extraAmt = getBundle.getDouble("selected_amount");
extraName = getBundle.getString("selected_catName");
final String extraCatID = getBundle.getString("selected_catID");
extraFromDate = getBundle.getString("selected_fromDate");
extraToDate = getBundle.getString("selected_toDate");
extraAmtSpent=getBundle.getDouble("selected_spentAmt");
final String extraNote = getBundle.getString("selected_note");
final String extraUniqueKey = getBundle.getString("selected_UniqueKey");
// CategoriesData selectedCat = new CategoriesData();
// selectedCat.setName(catName);
mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_edit: {
Toast.makeText(ViewBudgetDetail.this, "You click save edit!", Toast.LENGTH_LONG).show();
Intent editBudgetIntent = new Intent(ViewBudgetDetail.this,EditExistingBudget.class);
Bundle transactionBundle = new Bundle();
transactionBundle.putDouble("selected_amount",extraAmt);
transactionBundle.putString("selected_catName",extraName);
transactionBundle.putString("selected_catID",extraCatID);
transactionBundle.putString("selected_fromDate",extraFromDate);
transactionBundle.putString("selected_toDate",extraToDate);
transactionBundle.putString("selected_note",extraNote);
transactionBundle.putString("selected_UniqueKey",extraUniqueKey);
editBudgetIntent.putExtras(transactionBundle);
startActivity(editBudgetIntent);
}
return true;
case R.id.action_delete:{
Toast.makeText(ViewBudgetDetail.this, "You click delete button!", Toast.LENGTH_LONG).show();
}
return true;
default:
return false;
}
}
});
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(ViewBudgetDetail.this, "You click cancel button!", Toast.LENGTH_LONG).show();
finish();
}
});
}
@Override
public void onResume() {
super.onResume();
transactionsDataArrayList = new ArrayList<TransactionsData>();
getTransactionsByBudget(extraFromDate,extraToDate,extraName);
mUsersTransactionsDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
addLineDataSet();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menu_save,menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.getItem(0).setEnabled(false); // here pass the index of save menu item
menu.getItem(0).setVisible(false);
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
return true;
}
private ArrayList<String> setXAxisValues(String from, String to){
ArrayList<String> xVals = new ArrayList<String>();
xVals.add(from);
xVals.add(to);
return xVals;
}
private ArrayList<Entry> setYAxisValues(){
ArrayList<Entry> yVals = new ArrayList<Entry>();
Double amount =0.0;
int index=1;
yVals.add(new Entry(0,0f));
if(transactionsDataArrayList.size()>0){
for(TransactionsData transactionsData : transactionsDataArrayList){
amount = amount + transactionsData.getAmount();
yVals.add(new Entry(index,amount.floatValue()));
index ++;
}
}
return yVals;
}
private void setLineData() {
ArrayList<Entry> yVals = setYAxisValues();
LineDataSet dataSet;
// create a dataset and give it a type
dataSet = new LineDataSet(yVals, "Your spending");
//dataSet.setDrawCircles(false);
dataSet.setFillAlpha(110);
//dataSet.setFillColor(R.color.colorSecondary);
// set the line to be drawn like this "- - - - - -"
dataSet.setColor(Color.BLACK);
dataSet.setCircleColor(Color.RED);
dataSet.setLineWidth(0.5f);
dataSet.setCircleRadius(2f);
dataSet.setDrawCircleHole(false);
dataSet.setValueTextSize(5f);
dataSet.setDrawFilled(true);
ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
dataSets.add(dataSet); // add the datasets
// create a data object with the datasets
LineData data = new LineData(dataSets);
// set data
mLineChart.setData(data);
}
public List<List<String>> getYearAndMonthList(String fromYear, String fromMonth, String toYear, String toMonth) {
List<List<String>> list = new ArrayList<List<String>>();
Calendar startDate = Calendar.getInstance();
Calendar endDate = Calendar.getInstance();
Date from_date =null,to_date=null;
ParsePosition pos = new ParsePosition(0);
SimpleDateFormat format_FullDate = new SimpleDateFormat("dd-MM-yyyy");
SimpleDateFormat format_year = new SimpleDateFormat("yyyy");
SimpleDateFormat format_month = new SimpleDateFormat("MM");
try{
from_date = format_FullDate.parse("01-" +fromMonth+ "-" +fromYear);
to_date = format_FullDate.parse("01-" +toMonth+ "-" +toYear);
}catch (ParseException e) {
e.printStackTrace();
}
startDate.setTime(from_date);
endDate.setTime(to_date);
while (startDate.compareTo(endDate)<=0){
list.add(Arrays.asList(format_year.format(from_date),format_month.format(from_date)));
startDate.add(Calendar.MONTH,1);
from_date = startDate.getTime();
}
return list;
}
public void getTransactionsByBudget (final String from, final String to, String category){
final String sCategory = category;
// reset the selected date into variable
final SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
final Date fromDate = format.parse( from ,new ParsePosition(0));
final Date toDate = format.parse( to,new ParsePosition(0));
SimpleDateFormat format_month = new SimpleDateFormat("MM");
SimpleDateFormat format_year = new SimpleDateFormat("yyyy");
final String fromMonth = format_month.format(fromDate);
final String toMonth = format_month.format(toDate);
final String fromYear = format_year.format(fromDate);
final String toYear = format_year.format(toDate);
//- one day and + one day
final Calendar cFrom = Calendar.getInstance();
cFrom.setTime(fromDate);
cFrom.add(Calendar.DATE,-1);
final Date fDate = cFrom.getTime();
final Calendar cTo = Calendar.getInstance();
cTo.setTime(toDate);
cTo.add(Calendar.DATE,1);
final Date tDate = cTo.getTime();
//Get the list of Year and Months to retrieve from
List<List<String>> arrayListMonths = new ArrayList<List<String>>();
arrayListMonths = getYearAndMonthList(fromYear,fromMonth,toYear,toMonth);
//uniqueCategoriesSet = new LinkedHashSet<String>();
for(List<String> list : arrayListMonths){
if(list.size()>0){
String year = list.get(0);
String month = list.get(1);
mUsersTransactionsDatabase.child(year).child(month).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot categorySnapshot: dataSnapshot.getChildren()){
if(categorySnapshot.child("category").getValue().toString().equals(sCategory))
{
String dateTime = categorySnapshot.child("datetime").getValue(String.class);
Date transactDate = format.parse( dateTime, new ParsePosition(0));
if (transactDate.after(fDate) && transactDate.before(tDate))
{
String transactionCat = categorySnapshot.child("category").getValue(String.class);
String transactionDate = categorySnapshot.child("datetime").getValue(String.class);
Double transactionAmt = categorySnapshot.child("amount").getValue(Double.class);
String transactionCatType = categorySnapshot.child("category_type").getValue(String.class);
String transactionNote = categorySnapshot.child("notes").getValue(String.class);
String transactionUniqueKey = categorySnapshot.getKey();
final TransactionsData transactionsData = new TransactionsData();
//******* Firstly take data in model object ******//*
transactionsData.setCategory(transactionCat);
transactionsData.setDatetime(transactionDate);
transactionsData.setAmount(transactionAmt);
transactionsData.setCategory_type(transactionCatType);
transactionsData.setNotes(transactionNote);
transactionsData.setUniqueID(transactionUniqueKey);
//******** Take Model Object in ArrayList **********//*
transactionsDataArrayList.add(transactionsData);
}
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
}
private void addLineDataSet(){
mLineChart.setDrawGridBackground(false);
// add data
setLineData();
/*// get the legend (only possible after setting data)
Legend l = mLineChart.getLegend();
// modify the legend ...
l.setPosition(Legend.LegendPosition.BELOW_CHART_CENTER);
l.setForm(Legend.LegendForm.DEFAULT);*/
mLineChart.getLegend().setEnabled(false);
// no description text
Description desc = new Description();
desc.setText("Budget");
mLineChart.setDescription(desc);
mLineChart.setNoDataText("There is no spending yet.");
// enable touch gestures
mLineChart.setTouchEnabled(true);
// enable scaling and dragging
mLineChart.setDragEnabled(true);
mLineChart.setScaleEnabled(true);
mLineChart.setScaleXEnabled(true);
mLineChart.setScaleYEnabled(true);
LimitLine upper_limit = new LimitLine(extraAmt.floatValue(), "Limit Set");
upper_limit.setLineWidth(2f);
upper_limit.enableDashedLine(10f, 10f, 0f);
upper_limit.setLabelPosition(LimitLine.LimitLabelPosition.RIGHT_TOP);
upper_limit.setTextSize(10f);
YAxis leftAxis = mLineChart.getAxisLeft();
leftAxis.removeAllLimitLines(); // reset all limit lines to avoid overlapping lines
leftAxis.addLimitLine(upper_limit);
leftAxis.setAxisMaxValue(100 + extraAmtSpent.floatValue());
leftAxis.setAxisMinValue(0f);
//leftAxis.setYOffset(20f);
leftAxis.enableGridDashedLine(10f, 10f, 0f);
leftAxis.setDrawZeroLine(true);
// limit lines are drawn behind data (and not on top)
leftAxis.setDrawLimitLinesBehindData(true);
mLineChart.getAxisRight().setEnabled(false);
ArrayList<String> xVals = setXAxisValues(extraFromDate,extraToDate);
XAxis axis = mLineChart.getXAxis();
axis.setValueFormatter(new IndexAxisValueFormatter(xVals));
axis.setLabelCount(2,true);
axis.setGranularity(1f);
axis.setGranularityEnabled(true);
axis.setCenterAxisLabels(false);
axis.setPosition(XAxis.XAxisPosition.BOTTOM);
axis.setAxisMinimum(0.0f);
axis.setAxisMaximum(10f);
axis.setDrawGridLines(false);
//mLineChart.getViewPortHandler().setMaximumScaleY(2f);
//mLineChart.getViewPortHandler().setMaximumScaleX(2f);
mLineChart.animateX(1000, Easing.EasingOption.EaseInOutQuart);
// dont forget to refresh the drawing
mLineChart.invalidate();
}
}
答案 0 :(得分:1)
我设法完成了它。 (我发布我的答案和最终代码,希望这会帮助一些想和我一样的人)
1)在Max-2位置添加EndDate标签
private ArrayList<String> setXAxisValues(String from, String to){
ArrayList<String> xVals = new ArrayList<String>();
for(int i=0; i<mTotalNumberOfDay ;i++){
if (i==1) {
xVals.add(from);
}else if(i==mTotalNumberOfDay-2) {
xVals.add(i, to);
}else
{
xVals.add(i, "");
}
}
return xVals;
}
2)在准备行输入数据时,在Max + 1位置添加额外的条目(我添加+1的原因是因为我不想显示该条目的圆点)
yVals.add(new Entry(0,0f));
int j=1;
for (List<String> data: dataList){
if (Double.valueOf(data.get(1))!=0) {
amount = amount + Double.valueOf(data.get(1));
yVals.add(new Entry(j, amount.floatValue()));
}
j++;
}
yVals.add(new Entry(mTotalNumberOfDay+1,amount.floatValue()));
See the final result screenshot here
以下是最终代码:
package com.abc.personalexpensestracker;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import io.github.luizgrp.sectionedrecyclerviewadapter.SectionedRecyclerViewAdapter;
public class ViewBudgetDetail extends AppCompatActivity {
private Toolbar mToolbar;
private LineChart mLineChart;
private SectionedRecyclerViewAdapter mSectionAdapter;
private RecyclerView mBudgetsList;
private DatabaseReference mUsersTransactionsDatabase;
private DatabaseReference mUsersCategoriesDatabase;
private DatabaseReference mUsersBudgetsDatabase;
private FirebaseAuth mAuth;
private FirebaseUser mCurrUser;
private ArrayList<TransactionsData> transactionsDataArrayList =null;
private ArrayList<CategoriesData> categoriesDataArrayList = null;
private String extraName , extraFromDate , extraToDate ;
private Double extraAmt=0.0,extraAmtSpent=0.0;
private int mTotalNumberOfDay=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_budget_detail);
mLineChart = (LineChart) findViewById(R.id.budgetLineChart);
mAuth = FirebaseAuth.getInstance();
mCurrUser = mAuth.getCurrentUser();
mUsersTransactionsDatabase = FirebaseDatabase.getInstance().getReference().child("users_transactions").child(mCurrUser.getUid()).child("by_year");
mUsersCategoriesDatabase = FirebaseDatabase.getInstance().getReference().child("users_categories").child(mCurrUser.getUid()).child("expenses");
mToolbar = (Toolbar) findViewById(R.id.toolbar_ViewBudget);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("Budget Detail");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//Binding selected data from recyclerView
Bundle getBundle = null;
getBundle = this.getIntent().getExtras();
extraAmt = getBundle.getDouble("selected_amount");
extraName = getBundle.getString("selected_catName");
final String extraCatID = getBundle.getString("selected_catID");
extraFromDate = getBundle.getString("selected_fromDate");
extraToDate = getBundle.getString("selected_toDate");
extraAmtSpent=getBundle.getDouble("selected_spentAmt");
final String extraNote = getBundle.getString("selected_note");
final String extraUniqueKey = getBundle.getString("selected_UniqueKey");
// CategoriesData selectedCat = new CategoriesData();
// selectedCat.setName(catName);
mTotalNumberOfDay = getTotalNumberOfDay(extraFromDate,extraToDate);
mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_edit: {
Toast.makeText(ViewBudgetDetail.this, "You click save edit!", Toast.LENGTH_LONG).show();
Intent editBudgetIntent = new Intent(ViewBudgetDetail.this,EditExistingBudget.class);
Bundle transactionBundle = new Bundle();
transactionBundle.putDouble("selected_amount",extraAmt);
transactionBundle.putString("selected_catName",extraName);
transactionBundle.putString("selected_catID",extraCatID);
transactionBundle.putString("selected_fromDate",extraFromDate);
transactionBundle.putString("selected_toDate",extraToDate);
transactionBundle.putString("selected_note",extraNote);
transactionBundle.putString("selected_UniqueKey",extraUniqueKey);
editBudgetIntent.putExtras(transactionBundle);
startActivity(editBudgetIntent);
}
return true;
case R.id.action_delete:{
Toast.makeText(ViewBudgetDetail.this, "You click delete button!", Toast.LENGTH_LONG).show();
}
return true;
default:
return false;
}
}
});
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(ViewBudgetDetail.this, "You click cancel button!", Toast.LENGTH_LONG).show();
finish();
}
});
}
@Override
public void onResume() {
super.onResume();
transactionsDataArrayList = new ArrayList<TransactionsData>();
getTransactionsByBudget(extraFromDate,extraToDate,extraName);
mUsersTransactionsDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
addLineDataSet();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menu_save,menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.getItem(0).setEnabled(false); // here pass the index of save menu item
menu.getItem(0).setVisible(false);
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
return true;
}
private ArrayList<String> setXAxisValues(String from, String to){
ArrayList<String> xVals = new ArrayList<String>();
for(int i=0; i<mTotalNumberOfDay ;i++){
if (i==1) {
xVals.add(from);
}else if(i==mTotalNumberOfDay-2) {
xVals.add(i, to);
}else
{
xVals.add(i, "");
}
}
return xVals;
}
private ArrayList<Entry> setYAxisValues(){
List<String> days = new ArrayList();
days = getDaysArrayList(extraFromDate,extraToDate);
ArrayList<Entry> yVals = new ArrayList<Entry>(days.size());
Double amount =0.0;
List<List<String>> dataList = new ArrayList<List<String>>();
if(transactionsDataArrayList.size()>0){
for(int i = 0; i<days.size();i++){
Double amt =0.0;
for(TransactionsData transactionsData : transactionsDataArrayList){
if(transactionsData.getDatetime().equals(days.get(i))) {
amt = amt + transactionsData.getAmount();
}
}
dataList.add(Arrays.asList(days.get(i),amt.toString()));
}
}
yVals.add(new Entry(0,0f));
int j=1;
for (List<String> data: dataList){
if (Double.valueOf(data.get(1))!=0) {
amount = amount + Double.valueOf(data.get(1));
yVals.add(new Entry(j, amount.floatValue()));
}
j++;
}
yVals.add(new Entry(mTotalNumberOfDay+1,amount.floatValue()));
return yVals;
}
private void setLineData() {
ArrayList<Entry> yVals = setYAxisValues();
LineDataSet dataSet;
// create a dataset and give it a type
dataSet = new LineDataSet(yVals, "Your spending");
//dataSet.setDrawCircles(false);
dataSet.setFillAlpha(110);
//dataSet.setFillColor(R.color.colorSecondary);
// set the line to be drawn like this "- - - - - -"
dataSet.setColor(Color.BLACK);
dataSet.setCircleColor(Color.RED);
dataSet.setLineWidth(0.5f);
dataSet.setCircleRadius(2f);
dataSet.setDrawCircleHole(false);
dataSet.setValueTextSize(5f);
dataSet.setDrawFilled(true);
ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
dataSets.add(dataSet); // add the datasets
// create a data object with the datasets
LineData data = new LineData(dataSets);
// set data
mLineChart.setData(data);
}
private int getTotalNumberOfDay(String from, String to){
int total =0;
Calendar startDate = Calendar.getInstance();
Calendar endDate = Calendar.getInstance();
Date from_date =null,to_date=null;
ParsePosition pos = new ParsePosition(0);
SimpleDateFormat format_FullDate = new SimpleDateFormat("dd-MM-yyyy");
from_date = format_FullDate.parse(from,new ParsePosition(0));
to_date = format_FullDate.parse(to,new ParsePosition(0));
startDate.setTime(from_date);
endDate.setTime(to_date);
long msDiff = endDate.getTimeInMillis() - startDate.getTimeInMillis();
long daysDiff = TimeUnit.MILLISECONDS.toDays(msDiff);
daysDiff=daysDiff+1;
return ((int) daysDiff);
}
private List<String> getDaysArrayList(String from, String to){
List<String> sortedDays = null;
List<String> list = new ArrayList();
Calendar startDate = Calendar.getInstance();
Calendar endDate = Calendar.getInstance();
Date from_date =null,to_date=null;
ParsePosition pos = new ParsePosition(0);
SimpleDateFormat format_FullDate = new SimpleDateFormat("dd-MM-yyyy");
from_date = format_FullDate.parse(from,new ParsePosition(0));
to_date = format_FullDate.parse(to,new ParsePosition(0));
startDate.setTime(from_date);
endDate.setTime(to_date);
while (startDate.compareTo(endDate)<=0){
list.add(format_FullDate.format(from_date));
startDate.add(Calendar.DATE,1);
from_date = startDate.getTime();
}
// to sort Date to display in ASD order
sortedDays = list.subList(0, list.size());
Collections.sort(sortedDays);
return sortedDays;
}
public List<List<String>> getYearAndMonthList(String fromYear, String fromMonth, String toYear, String toMonth) {
List<List<String>> list = new ArrayList<List<String>>();
Calendar startDate = Calendar.getInstance();
Calendar endDate = Calendar.getInstance();
Date from_date =null,to_date=null;
ParsePosition pos = new ParsePosition(0);
SimpleDateFormat format_FullDate = new SimpleDateFormat("dd-MM-yyyy");
SimpleDateFormat format_year = new SimpleDateFormat("yyyy");
SimpleDateFormat format_month = new SimpleDateFormat("MM");
try{
from_date = format_FullDate.parse("01-" +fromMonth+ "-" +fromYear);
to_date = format_FullDate.parse("01-" +toMonth+ "-" +toYear);
}catch (ParseException e) {
e.printStackTrace();
}
startDate.setTime(from_date);
endDate.setTime(to_date);
while (startDate.compareTo(endDate)<=0){
list.add(Arrays.asList(format_year.format(from_date),format_month.format(from_date)));
startDate.add(Calendar.MONTH,1);
from_date = startDate.getTime();
}
return list;
}
public void getTransactionsByBudget (final String from, final String to, String category){
final String sCategory = category;
// reset the selected date into variable
final SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
final Date fromDate = format.parse( from ,new ParsePosition(0));
final Date toDate = format.parse( to,new ParsePosition(0));
SimpleDateFormat format_month = new SimpleDateFormat("MM");
SimpleDateFormat format_year = new SimpleDateFormat("yyyy");
final String fromMonth = format_month.format(fromDate);
final String toMonth = format_month.format(toDate);
final String fromYear = format_year.format(fromDate);
final String toYear = format_year.format(toDate);
//- one day and + one day
final Calendar cFrom = Calendar.getInstance();
cFrom.setTime(fromDate);
cFrom.add(Calendar.DATE,-1);
final Date fDate = cFrom.getTime();
final Calendar cTo = Calendar.getInstance();
cTo.setTime(toDate);
cTo.add(Calendar.DATE,1);
final Date tDate = cTo.getTime();
//Get the list of Year and Months to retrieve from
List<List<String>> arrayListMonths = new ArrayList<List<String>>();
arrayListMonths = getYearAndMonthList(fromYear,fromMonth,toYear,toMonth);
//uniqueCategoriesSet = new LinkedHashSet<String>();
for(List<String> list : arrayListMonths){
if(list.size()>0){
String year = list.get(0);
String month = list.get(1);
mUsersTransactionsDatabase.child(year).child(month).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot categorySnapshot: dataSnapshot.getChildren()){
if(categorySnapshot.child("category").getValue().toString().equals(sCategory))
{
String dateTime = categorySnapshot.child("datetime").getValue(String.class);
Date transactDate = format.parse( dateTime, new ParsePosition(0));
if (transactDate.after(fDate) && transactDate.before(tDate))
{
String transactionCat = categorySnapshot.child("category").getValue(String.class);
String transactionDate = categorySnapshot.child("datetime").getValue(String.class);
Double transactionAmt = categorySnapshot.child("amount").getValue(Double.class);
String transactionCatType = categorySnapshot.child("category_type").getValue(String.class);
String transactionNote = categorySnapshot.child("notes").getValue(String.class);
String transactionUniqueKey = categorySnapshot.getKey();
final TransactionsData transactionsData = new TransactionsData();
//******* Firstly take data in model object ******//*
transactionsData.setCategory(transactionCat);
transactionsData.setDatetime(transactionDate);
transactionsData.setAmount(transactionAmt);
transactionsData.setCategory_type(transactionCatType);
transactionsData.setNotes(transactionNote);
transactionsData.setUniqueID(transactionUniqueKey);
//******** Take Model Object in ArrayList **********//*
transactionsDataArrayList.add(transactionsData);
}
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
}
private void addLineDataSet(){
mLineChart.setDrawGridBackground(false);
// add data
setLineData();
/*// get the legend (only possible after setting data)
Legend l = mLineChart.getLegend();
// modify the legend ...
l.setPosition(Legend.LegendPosition.BELOW_CHART_CENTER);
l.setForm(Legend.LegendForm.DEFAULT);*/
mLineChart.getLegend().setEnabled(false);
// no description text
Description desc = new Description();
desc.setText("Budget");
mLineChart.setDescription(desc);
mLineChart.setNoDataText("There is no spending yet.");
// enable touch gestures
mLineChart.setTouchEnabled(true);
// enable scaling and dragging
mLineChart.setDragEnabled(true);
mLineChart.setScaleEnabled(true);
mLineChart.setScaleXEnabled(true);
mLineChart.setScaleYEnabled(true);
LimitLine upper_limit = new LimitLine(extraAmt.floatValue(), "Limit Set");
upper_limit.setLineWidth(2f);
upper_limit.enableDashedLine(10f, 10f, 0f);
upper_limit.setLabelPosition(LimitLine.LimitLabelPosition.RIGHT_TOP);
upper_limit.setTextSize(10f);
YAxis leftAxis = mLineChart.getAxisLeft();
leftAxis.removeAllLimitLines(); // reset all limit lines to avoid overlapping lines
leftAxis.addLimitLine(upper_limit);
leftAxis.setAxisMaxValue(100 + extraAmtSpent.floatValue());
leftAxis.setAxisMinValue(0f);
//leftAxis.setYOffset(20f);
leftAxis.enableGridDashedLine(10f, 10f, 0f);
leftAxis.setDrawZeroLine(true);
// limit lines are drawn behind data (and not on top)
leftAxis.setDrawLimitLinesBehindData(true);
mLineChart.getAxisRight().setEnabled(false);
ArrayList<String> xVals = setXAxisValues(extraFromDate,extraToDate);
XAxis axis = mLineChart.getXAxis();
axis.setAxisMinimum(0.0f);
axis.setAxisMaximum(((float) mTotalNumberOfDay));
axis.setValueFormatter(new IndexAxisValueFormatter(xVals));
axis.setLabelCount(xVals.size());
axis.setGranularity(1f);
axis.setGranularityEnabled(true);
axis.setCenterAxisLabels(true);
axis.setAxisLineWidth(2f);
axis.setPosition(XAxis.XAxisPosition.BOTTOM);
axis.setDrawGridLines(false);
//mLineChart.getViewPortHandler().setMaximumScaleY(2f);
//mLineChart.getViewPortHandler().setMaximumScaleX(2f);
mLineChart.animateX(1000, Easing.EasingOption.EaseInOutQuart);
// dont forget to refresh the drawing
mLineChart.invalidate();
}
}