在Android中使用GraphView将日期设置为X轴的难度

时间:2017-01-19 15:13:18

标签: android date graph android-graphview

我从JSON获取x和y值并使用GraphView创建图表。如何将X轴实现为Dates.I我正在共享我的代码,请查看错误是什么?

这是我的代码:

import android.graphics.Color;
import android.icu.text.SimpleDateFormat;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.view.Menu;
import android.view.MenuItem;


import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.Viewport;
import com.jjoe64.graphview.helper.DateAsXAxisLabelFormatter;
import com.jjoe64.graphview.helper.StaticLabelsFormatter;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.DataPointInterface;
import com.jjoe64.graphview.series.LineGraphSeries;
import com.jjoe64.graphview.series.OnDataPointTapListener;
import com.jjoe64.graphview.series.Series;


import java.security.Timestamp;
import java.sql.Time;
import java.text.ParseException;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.HashMap;
import java.util.ArrayList;
import java.lang.Double;
import java.util.Map;
import java.util.Random;

import garima.asynctask.library.HttpHandler;

import static com.example.garima.bitcoingraph.sortedHashMap.sortByValues;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();

    //URL to get JSON Array
    private static String url = "https://api.blockchain.info/charts/market-price?format=json";
    HashMap<String, String> valueslist;

    //JSON Node Names
    private static final String TAG_STATUS = "status";
    private static final String TAG_NAME = "name";
    private static final String TAG_UNIT = "unit";
    private static final String TAG_PERIOD = "period";
    private static final String TAG_DESCRIPTION = "description";

    private LineGraphSeries<DataPoint> series;

    //On the click of this Get Data Button we receive information from json
    Button Btngetdata;

    JSONArray user = null;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        setContentView(R.layout.activity_main);

        GraphView graph = (GraphView) findViewById(R.id.graph);
        series = new LineGraphSeries<DataPoint>();
        graph.addSeries(series);
        series.setThickness(8);
        series.setDrawDataPoints(true);
        series.setOnDataPointTapListener(new OnDataPointTapListener() {
            @Override
            public void onTap(Series series, DataPointInterface dataPoint) {
                Toast.makeText(MainActivity.this,"On Data Point clicked:"+dataPoint, Toast.LENGTH_SHORT).show();
            }
        });


        //StaticLabelsFormatter staticLabelsFormatter = new StaticLabelsFormatter(graph);
        //staticLabelsFormatter.setHorizontalLabels(new String[] { "Feb'16", "Mar'16","April'16","May'16","June'16","July'16","Aug'16","Sep'16","Oct'16","Nov'16","Dec'16","Jan'17"});
        //graph.getGridLabelRenderer().setLabelFormatter(staticLabelsFormatter);

        graph.getGridLabelRenderer().setLabelFormatter(new DateAsXAxisLabelFormatter(MainActivity.this));
        //graph.getGridLabelRenderer().setNumHorizontalLabels(30); // only 4 because of the space
        graph.getGridLabelRenderer().setHumanRounding(false);

        Viewport viewport = graph.getViewport();
        viewport.setYAxisBoundsManual(true);
        viewport.setMinY(0);
        viewport.setMaxY(1200);
        viewport.setScalable(true);
        viewport.setScrollable(true);
        viewport.setScalableY(true);
        viewport.setScrollableY(true);
        //viewport.setXAxisBoundsManual(true);





        valueslist = new HashMap<>();

        Btngetdata = (Button) findViewById(R.id.getdata);
        Btngetdata.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                new JSONParse().execute();

            }
        });

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void addEntry(String Xax, String Yax) {
        //int Xaxis_val = Integer.parseInt(Xax);
        //Log.i(TAG, "addEntry: value of Xaxis val is" + Xaxis_val);
        float Yaxis_val = Float.parseFloat(Yax);
        Log.i(TAG, "addEntry: value of Y axis is " + Yaxis_val);
        Date date= new Date();
        SimpleDateFormat fmtOut = new SimpleDateFormat("dd/MM/yyyy");
        try {
            date=fmtOut.parse(Xax);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Log.i(TAG, "addEntry: date as x is"+date);
        series.appendData(new DataPoint(date, Yaxis_val), true, 200);

    }






    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("Main Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        AppIndex.AppIndexApi.start(client, getIndexApiAction());
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.end(client, getIndexApiAction());
        client.disconnect();
    }


    private class JSONParse extends AsyncTask<Void, Void, Void> {
        private ProgressDialog pDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();


            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Getting Data ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();

        }


        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url);

            Log.e(TAG, "Response from url: " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    String Status_Value = jsonObj.getString(TAG_STATUS);
                    String Name_Value = jsonObj.getString(TAG_NAME);
                    String Unit_Value = jsonObj.getString(TAG_UNIT);
                    String Period_Value = jsonObj.getString(TAG_PERIOD);
                    String Description_Value = jsonObj.getString(TAG_DESCRIPTION);


                    // Getting JSON Array node
                    JSONArray values = jsonObj.getJSONArray("values");

                    // looping through All Values
                    for (int i = 0; i < values.length(); i++) {
                        JSONObject c = values.getJSONObject(i);


                        String x_val = c.getString("x");
                        String y_val = c.getString("y");


                        // tmp hash map for single value
                        HashMap<String, String> val = new HashMap<>();

                        // adding each child node to HashMap key => value
                        val.put("x", x_val);
                        val.put("y", y_val);

                        // adding values to values list
                        valueslist.put(x_val, y_val);
                    }
                } catch (final JSONException e) {
                    Log.e(TAG, "Json parsing error: " + e.getMessage());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Json parsing error: " + e.getMessage(),
                                    Toast.LENGTH_LONG)
                                    .show();
                        }
                    });

                }
            } else {
                Log.e(TAG, "Couldn't get json from server.");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Couldn't get json from server. Check LogCat for possible errors!",
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }

            return null;
        }

        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        protected void onPostExecute(Void Result) {
            pDialog.dismiss();


 /*               ListAdapter adapter = new SimpleAdapter(
                        MainActivity.this, valueslist,
                        R.layout.list_item, new String[]{"x", "y",
                        }, new int[]{R.id.x_var,
                        R.id.y_var});

                lv.setAdapter(adapter); */
            Log.i(TAG, "onPostExecute: value of list is" + valueslist);
            ArrayList<String> xVals = new ArrayList<>();
            /*ArrayList<Entry> yVals = new ArrayList<Entry>();



            /*for(Map<String,String> map:valueslist){
                String tagName = map.get(TAG_VALUEx);
                Log.i(TAG, "onPostExecute: value is"+ tagName);
                String tagNameY=map.get(TAG_VALUEy);
                Log.i(TAG, "onPostExecute: value of y is"+tagNameY);
                addEntry(tagName,tagNameY);
            }*/
            HashMap<String,String> sortedList=sortByValues(valueslist);

            Log.i(TAG,"sorted hash map is "+sortedList);


            for (Map.Entry<String, String> entry : sortedList.entrySet()) {
                System.out.println(entry.getKey() + " " + entry.getValue());
                String tagName = entry.getKey();
                long timestampString =  Long.parseLong(tagName);
                String value = new java.text.SimpleDateFormat("dd/MM/yyyy").
                        format(new java.util.Date(timestampString * 1000));
               /*// String newval=value.substring(0, value.indexOf(' '));
                Date date= new Date();
                SimpleDateFormat fmtOut = new SimpleDateFormat("dd/MM/yyyy");
                try {
                     date=fmtOut.parse(value);
                } catch (ParseException e) {
                    e.printStackTrace();
                }*/


                String tagNameY=entry.getValue();
                //Log.i(TAG, "onPostExecute: value of date is"+date);
                addEntry(value,tagNameY);
            }

        }




    }

}

这是错误:

I/MainActivity: addEntry: date as x isTue Jan 03 00:00:00 GMT+01:00 2017

I/System.out: 1483488000 1126.7633375
I/MainActivity: addEntry: value of Y axis is 1126.7633
I/MainActivity: addEntry: date as x isWed Jan 04 00:00:00 GMT+01:00 2017
I/System.out: 1454457600 368.38
I/MainActivity: addEntry: value of Y axis is 368.38
I/MainActivity: addEntry: date as x isWed Feb 03 00:00:00 GMT+01:00 2016
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.garima.bitcoingraph, PID: 3095
                  java.lang.IllegalArgumentException: new x-value must be greater then the last value. x-values has to be ordered in ASC.
                      at com.jjoe64.graphview.series.BaseSeries.checkValueOrder(BaseSeries.java:486)
                      at com.jjoe64.graphview.series.BaseSeries.appendData(BaseSeries.java:408)
                      at com.jjoe64.graphview.series.LineGraphSeries.appendData(LineGraphSeries.java:646)
                      at com.jjoe64.graphview.series.BaseSeries.appendData(BaseSeries.java:464)
                      at com.example.garima.bitcoingraph.MainActivity.addEntry(MainActivity.java:177)
                      at com.example.garima.bitcoingraph.MainActivity.-wrap0(MainActivity.java)
                      at com.example.garima.bitcoingraph.MainActivity$JSONParse.onPostExecute(MainActivity.java:361)
                      at com.example.garima.bitcoingraph.MainActivity$JSONParse.onPostExecute(MainActivity.java:312)
                      at android.os.AsyncTask.finish(AsyncTask.java:660)
                      at android.os.AsyncTask.-wrap1(AsyncTask.java)
                      at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:677)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6077)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Application terminated.

1 个答案:

答案 0 :(得分:0)

  

java.lang.IllegalArgumentException:新的x值必须大于   最后一个值。必须在ASC中订购x值。

我认为您必须在上升模式下订购日期,然后添加到DataPoint系列。

对不起,如果我的英语不好。