Android Dynamic Line Chart Example

Hiiii Everyone in this tutorial I am sharing how to show a line chart in android. In this article, I share Dynamic data to show in the graph using network library Volley. Get an Array list of data throw API and show these to in Line chart graph in android.

API Response

 
   "message":"Data get successfully!",
   "status":"1",
   "allData": 
       
         "score":"12",
         "date":"14-May-2019"
      },
       
         "score":"24",
         "date":"15-May-2019"
      },
       
         "score":"36",
         "date":"15-May-2019"
      },
       
         "score":"48",
         "date":"15-May-2019"
      },
       
         "score":"60",
         "date":"15-May-2019"
      }
   ]
}

 

Step 1: First one to  Start Android Studio

Step 2 :  Seconds step to Create a New Project Project ClickOn  ==> File  ==> NEW ==> New Project

Step 3: After create on your project open your java file and XML file and you can just copy the code and paste on your file and run your project.

Step 4 Add Library In build.gradle

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:28.+'
    compile 'com.android.support:design:28.+'
    compile 'com.android.support:support-v4:28.+'
    compile 'de.hdodenhof:circleimageview:2.1.0'
    compile 'com.android.support:cardview-v7:28.+'
    compile 'com.android.support:recyclerview-v7:28.+'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.android.volley:volley:1.0.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.github.PhilJay:MPAndroidChart:v2.2.4'
    compile 'com.android.support:support-vector-drawable:28.+'
    testCompile 'junit:junit:4.12'
}

In these, I am used MPAndroidChart Library.

compile ‘com.github.PhilJay:MPAndroidChart:v2.2.4’

Step 5 Open Your XML File and add the line chart graph 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.codeplayon.lineChart">

            <com.github.mikephil.charting.charts.LineChart
                android:layout_gravity="center"
                android:id="@+id/line"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
            </com.github.mikephil.charting.charts.LineChart>

</LinearLayout>

 

Step: 6  Implement In Java Class Add these code in your java class.

public class LineChart extends AppCompatActivity implements OnChartValueSelectedListener {
    public static final String KEY_Email = "patientId";
    public static final String KEY_Token = "flag";
    String Token,patient_id,Visitid;
    ArrayList<Entry> x;
    ArrayList<String> y;
    private LineChart mChart;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_line_chart);
    
        x = new ArrayList<Entry>();
        y = new ArrayList<String>();
        mChart = (LineChart)findViewById(R.id.line);
        mChart.setDrawGridBackground(false);
        mChart.setDescription("");
        mChart.setTouchEnabled(true);
        mChart.setDragEnabled(true);
        mChart.setScaleEnabled(true);
        mChart.setPinchZoom(true);
        mChart.getXAxis().setTextSize(15f);
        mChart.getAxisLeft().setTextSize(15f);
//        mChart.setMarkerView(mv);
        XAxis xl = mChart.getXAxis();
        xl.setAvoidFirstLastClipping(true);
        YAxis leftAxis = mChart.getAxisLeft();
        leftAxis.setInverted(true);
        YAxis rightAxis = mChart.getAxisRight();
        rightAxis.setEnabled(false);
        Legend l = mChart.getLegend();
        l.setForm(Legend.LegendForm.LINE);
        Graph_List();
    }

    private void Graph_List() {
        final ProgressDialog loading = new ProgressDialog(Adl_BarChart.this);
        loading.setMessage("Please Wait...");
        loading.setCancelable(false);
        loading.show();
// json response code
        StringRequest stringRequest = new StringRequest(Request.Method.POST, ConfiURL.Graph_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            Log.d("JSON", response);
                            loading.dismiss();
                            JSONObject jsonObject = new JSONObject(response);
                            String error_status = jsonObject.getString("status");
                            if (error_status.equals("0")) {
                                String error_msg = jsonObject.getString("message");
//                                Toast.makeText(LogIn.this, error_msg, Toast.LENGTH_SHORT).show();
                                ContextThemeWrapper ctw = new ContextThemeWrapper( Adl_BarChart.this, R.style.Theme_AlertDialog);
                                final android.app.AlertDialog.Builder alertDialogBuilder = new android.app.AlertDialog.Builder(ctw);
                                alertDialogBuilder.setTitle("Message");
                                alertDialogBuilder.setMessage(error_msg);
                                alertDialogBuilder.setCancelable(false);
                                alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {

                                    }
                                });
                                alertDialogBuilder.show();
                            } else {
                                JSONArray jsonArray = jsonObject.getJSONArray("allData");
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    JSONObject json_data = jsonArray.getJSONObject(i);
                                    String score = json_data.getString("score");
                                    String date = json_data.getString("date");
                                    x.add(new Entry(Integer.parseInt(score), i));
                                    y.add(date);

                                }
                                LineDataSet set1 = new LineDataSet(x, Token);
                                set1.setColors(ColorTemplate.COLORFUL_COLORS);
                                set1.setLineWidth(1.5f);
                                set1.setCircleRadius(4f);
                                LineData data = new LineData(y, set1);
                                mChart.setData(data);
                                mChart.invalidate();
                            }

                        } catch (Exception e) {
                            loading.dismiss();
                            Log.d("Tag", e.getMessage());

                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        loading.dismiss();
                        if (error instanceof TimeoutError || error instanceof NoConnectionError) {
                            ContextThemeWrapper ctw = new ContextThemeWrapper( Adl_BarChart.this, R.style.Theme_AlertDialog);
                            final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ctw);
                            alertDialogBuilder.setTitle("No connection");
                            alertDialogBuilder.setMessage(" Network Timeout  error please try again ");
                            alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {

                                }
                            });
                            alertDialogBuilder.show();
                        } else if (error instanceof AuthFailureError) {
                            ContextThemeWrapper ctw = new ContextThemeWrapper( Adl_BarChart.this, R.style.Theme_AlertDialog);
                            final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ctw);
                            alertDialogBuilder.setTitle("Connection Error");
                            alertDialogBuilder.setMessage(" Connection authentication failure  error please try again");
                            alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {

                                }
                            });
                            alertDialogBuilder.show();
                            //TODO
                        } else if (error instanceof ServerError) {
                            ContextThemeWrapper ctw = new ContextThemeWrapper( Adl_BarChart.this, R.style.Theme_AlertDialog);
                            final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ctw);
                            alertDialogBuilder.setTitle("Connection Error");
                            alertDialogBuilder.setMessage("Connection error please try again");
                            alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {

                                }
                            });
                            alertDialogBuilder.show();
                            //TODO
                        } else if (error instanceof NetworkError) {
                            ContextThemeWrapper ctw = new ContextThemeWrapper( Adl_BarChart.this, R.style.Theme_AlertDialog);
                            final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ctw);
                            alertDialogBuilder.setTitle("Connection Error");
                            alertDialogBuilder.setMessage("Network connection error please try again");
                            alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {

                                }
                            });
                            alertDialogBuilder.show();
                            //TODO
                        } else if (error instanceof ParseError) {
                            ContextThemeWrapper ctw = new ContextThemeWrapper( Adl_BarChart.this, R.style.Theme_AlertDialog);
                            final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ctw);
                            alertDialogBuilder.setTitle("Error");
                            alertDialogBuilder.setMessage("Parse error");
                            alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {

                                }
                            });
                            alertDialogBuilder.show();
                        }
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put(KEY_Email,patient_id);
                map.put(KEY_Token,Token);
                return map;
            }
        };

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

    @Override
    public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {

    }

    @Override
    public void onNothingSelected() {

    }

https://www.youtube.com/watch?v=puFfeMJ1bms

You may also like...