Skip to content Skip to sidebar Skip to footer

Mpandroidchart - Line Chart: How To Continue Draw Line Till The End(max)?

Would like to ask question regarding to MPAndroidChart- Line Chart. I have tried searching but couldn't find a sample. 1) How to set label at the left-most and right-most of X. (eg

Solution 1:

I managed to get it done. ( I post my answer and final code, hope this will help some people who want to do the same as me )

1) by adding the EndDate label at the Max-2 position

privateArrayList<String> setXAxisValues(Stringfrom, String to){
            ArrayList<String> xVals = newArrayList<String>();
            for(int i=0; i<mTotalNumberOfDay ;i++){
                if (i==1) {
                    xVals.add(from);
                }elseif(i==mTotalNumberOfDay-2) {
                    xVals.add(i, to);
                }else
                {
                    xVals.add(i, "");
                }
            }
            return xVals;
        }

2) When preparing Line Entry data, add extra Entry at the position Max+1 (the reason I add +1 is because of I don't want to show the circle-dot of that Entry)

   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

Following is the final code:

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;

            publicclassViewBudgetDetailextendsAppCompatActivity {

                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;
                privateint mTotalNumberOfDay=0;

                @OverrideprotectedvoidonCreate(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 recyclerViewBundlegetBundle=null;
                    getBundle = this.getIntent().getExtras();
                     extraAmt = getBundle.getDouble("selected_amount");
                      extraName = getBundle.getString("selected_catName");
                    finalStringextraCatID= getBundle.getString("selected_catID");
                      extraFromDate = getBundle.getString("selected_fromDate");
                      extraToDate = getBundle.getString("selected_toDate");
                    extraAmtSpent=getBundle.getDouble("selected_spentAmt");
                    finalStringextraNote= getBundle.getString("selected_note");
                    finalStringextraUniqueKey= getBundle.getString("selected_UniqueKey");
                   // CategoriesData selectedCat = new CategoriesData();// selectedCat.setName(catName);

                    mTotalNumberOfDay = getTotalNumberOfDay(extraFromDate,extraToDate);

                    mToolbar.setOnMenuItemClickListener(newToolbar.OnMenuItemClickListener() {
                        @OverridepublicbooleanonMenuItemClick(MenuItem item) {
                            switch (item.getItemId()) {
                                case R.id.action_edit: {
                                    Toast.makeText(ViewBudgetDetail.this, "You click save edit!", Toast.LENGTH_LONG).show();

                                    IntenteditBudgetIntent=newIntent(ViewBudgetDetail.this,EditExistingBudget.class);
                                    BundletransactionBundle=newBundle();
                                    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);

                                }
                                returntrue;
                                case R.id.action_delete:{
                                    Toast.makeText(ViewBudgetDetail.this, "You click delete button!", Toast.LENGTH_LONG).show();

                                }
                                returntrue;
                                default:
                                    returnfalse;
                            }
                        }
                    });

                    mToolbar.setNavigationOnClickListener(newView.OnClickListener() {
                        @OverridepublicvoidonClick(View v) {
                            Toast.makeText(ViewBudgetDetail.this, "You click cancel button!", Toast.LENGTH_LONG).show();
                            finish();
                        }
                    });



                }

                @OverridepublicvoidonResume() {
                    super.onResume();


                    transactionsDataArrayList = newArrayList<TransactionsData>();
                    getTransactionsByBudget(extraFromDate,extraToDate,extraName);

                mUsersTransactionsDatabase.addListenerForSingleValueEvent(newValueEventListener() {
                                            @OverridepublicvoidonDataChange(DataSnapshot dataSnapshot) {

                                               addLineDataSet();


                                            }

                                            @OverridepublicvoidonCancelled(DatabaseError databaseError) {

                                            }
                                        });


                }


                @OverridepublicbooleanonCreateOptionsMenu(Menu menu) {
                    super.onCreateOptionsMenu(menu);
                    getMenuInflater().inflate(R.menu.menu_save,menu);
                    returntrue;

                }

                @OverridepublicbooleanonPrepareOptionsMenu(Menu menu) {
                    menu.getItem(0).setEnabled(false); // here pass the index of save menu item
                    menu.getItem(0).setVisible(false);
                    returnsuper.onPrepareOptionsMenu(menu);

                }


                @OverridepublicbooleanonOptionsItemSelected(MenuItem item) {
                    super.onOptionsItemSelected(item);
                    returntrue;
                }


                private ArrayList<String> setXAxisValues(String from, String to){
                    ArrayList<String> xVals = newArrayList<String>();
                    for(int i=0; i<mTotalNumberOfDay ;i++){
                        if (i==1) {
                            xVals.add(from);
                        }elseif(i==mTotalNumberOfDay-2) {
                            xVals.add(i, to);
                        }else
                        {
                            xVals.add(i, "");
                        }
                    }


                    return xVals;
                }

                private ArrayList<Entry> setYAxisValues(){


                    List<String> days = newArrayList();
                    days = getDaysArrayList(extraFromDate,extraToDate);

                    ArrayList<Entry> yVals = newArrayList<Entry>(days.size());
                    Doubleamount=0.0;

                    List<List<String>> dataList = newArrayList<List<String>>();
                     if(transactionsDataArrayList.size()>0){

                         for(inti=0; i<days.size();i++){

                             Doubleamt=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(newEntry(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(newEntry(j, amount.floatValue()));
                        }
                        j++;
                    }

                    yVals.add(newEntry(mTotalNumberOfDay+1,amount.floatValue()));

                    return yVals;
                }

                privatevoidsetLineData() {



                    ArrayList<Entry> yVals = setYAxisValues();
                    LineDataSet dataSet;

                    // create a dataset and give it a type
                    dataSet = newLineDataSet(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 = newArrayList<ILineDataSet>();
                    dataSets.add(dataSet); // add the datasets// create a data object with the datasetsLineDatadata=newLineData(dataSets);


                    // set data
                    mLineChart.setData(data);

                   }

                privateintgetTotalNumberOfDay(String from, String to){
                    inttotal=0;

                    CalendarstartDate= Calendar.getInstance();
                    CalendarendDate= Calendar.getInstance();
                    Datefrom_date=null,to_date=null;
                    ParsePositionpos=newParsePosition(0);
                    SimpleDateFormatformat_FullDate=newSimpleDateFormat("dd-MM-yyyy");

                    from_date = format_FullDate.parse(from,newParsePosition(0));
                    to_date = format_FullDate.parse(to,newParsePosition(0));

                    startDate.setTime(from_date);
                    endDate.setTime(to_date);

                    longmsDiff= endDate.getTimeInMillis() - startDate.getTimeInMillis();
                    longdaysDiff= 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 =  newArrayList();

                    CalendarstartDate= Calendar.getInstance();
                    CalendarendDate= Calendar.getInstance();
                    Datefrom_date=null,to_date=null;
                    ParsePositionpos=newParsePosition(0);
                    SimpleDateFormatformat_FullDate=newSimpleDateFormat("dd-MM-yyyy");

                    from_date = format_FullDate.parse(from,newParsePosition(0));
                    to_date = format_FullDate.parse(to,newParsePosition(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 =  newArrayList<List<String>>();

                    CalendarstartDate= Calendar.getInstance();
                    CalendarendDate= Calendar.getInstance();
                    Datefrom_date=null,to_date=null;
                    ParsePositionpos=newParsePosition(0);
                    SimpleDateFormatformat_FullDate=newSimpleDateFormat("dd-MM-yyyy");
                    SimpleDateFormatformat_year=newSimpleDateFormat("yyyy");
                    SimpleDateFormatformat_month=newSimpleDateFormat("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;
                }

                publicvoidgetTransactionsByBudget(final String from, final String to, String category){

                    finalStringsCategory= category;

                    // reset the selected date into variablefinalSimpleDateFormatformat=newSimpleDateFormat("dd-MM-yyyy");
                    finalDatefromDate= format.parse( from ,newParsePosition(0));
                    finalDatetoDate= format.parse( to,newParsePosition(0));

                    SimpleDateFormatformat_month=newSimpleDateFormat("MM");
                    SimpleDateFormatformat_year=newSimpleDateFormat("yyyy");

                    finalStringfromMonth= format_month.format(fromDate);
                    finalStringtoMonth= format_month.format(toDate);

                    finalStringfromYear= format_year.format(fromDate);
                    finalStringtoYear= format_year.format(toDate);


                    //- one day and + one dayfinalCalendarcFrom= Calendar.getInstance();
                    cFrom.setTime(fromDate);
                    cFrom.add(Calendar.DATE,-1);
                    finalDatefDate= cFrom.getTime();
                    finalCalendarcTo= Calendar.getInstance();
                    cTo.setTime(toDate);
                    cTo.add(Calendar.DATE,1);
                    finalDatetDate= cTo.getTime();


                    //Get the list of Year and Months to retrieve from
                    List<List<String>> arrayListMonths = newArrayList<List<String>>();
                    arrayListMonths = getYearAndMonthList(fromYear,fromMonth,toYear,toMonth);

                    //uniqueCategoriesSet = new LinkedHashSet<String>();for(List<String> list : arrayListMonths){

                        if(list.size()>0){
                            Stringyear= list.get(0);
                            Stringmonth= list.get(1);

                            mUsersTransactionsDatabase.child(year).child(month).addValueEventListener(newValueEventListener() {
                                @OverridepublicvoidonDataChange(DataSnapshot dataSnapshot) {



                                    for(DataSnapshot categorySnapshot: dataSnapshot.getChildren()){

                                        if(categorySnapshot.child("category").getValue().toString().equals(sCategory))

                                        {

                                            StringdateTime= categorySnapshot.child("datetime").getValue(String.class);
                                            DatetransactDate= format.parse( dateTime, newParsePosition(0));


                                            if (transactDate.after(fDate) && transactDate.before(tDate))
                                            {

                                                StringtransactionCat= categorySnapshot.child("category").getValue(String.class);
                                                StringtransactionDate= categorySnapshot.child("datetime").getValue(String.class);
                                                DoubletransactionAmt= categorySnapshot.child("amount").getValue(Double.class);
                                                StringtransactionCatType= categorySnapshot.child("category_type").getValue(String.class);
                                                StringtransactionNote= categorySnapshot.child("notes").getValue(String.class);
                                                StringtransactionUniqueKey= categorySnapshot.getKey();

                                                finalTransactionsDatatransactionsData=newTransactionsData();
                                                //******* 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);

                                            }
                                        }
                                    }

                                }

                                @OverridepublicvoidonCancelled(DatabaseError databaseError) {

                                }
                            });


                        }
                    }

                }

                privatevoidaddLineDataSet(){


                    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 textDescriptiondesc=newDescription();
                    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);

                    LimitLineupper_limit=newLimitLine(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);

                    YAxisleftAxis= 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);
                    XAxisaxis= mLineChart.getXAxis();
                    axis.setAxisMinimum(0.0f);
                    axis.setAxisMaximum(((float) mTotalNumberOfDay));
                    axis.setValueFormatter(newIndexAxisValueFormatter(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();


                }
            }

Post a Comment for "Mpandroidchart - Line Chart: How To Continue Draw Line Till The End(max)?"