How to pass an ArrayList to another activi

2019-09-02 16:14发布

Hey guys i am building an app which produces a dynamic graph through some values i get from mysql which are requested in json array.

My code is:

Intent i = this.getActivity().getIntent();
        HashMap<String, String> hashMap = (HashMap<String, String>) i.getSerializableExtra("stockInfo");
        name = i.getStringExtra("name");
        ball = i.getStringExtra("price");
        final ArrayList<String> myItems = new ArrayList<String>(hashMap.values());
        myItems.remove(name);
        myItems.remove(ball);
Button buttonLiveGraph = (Button)rootView.findViewById(R.id.buttonlive);
        buttonLiveGraph.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(getActivity().getApplicationContext(), LiveGraph.class);
                intent.putExtra("stockprices", myItems.toString());
                getActivity().startActivity(intent);
            }
        });

and in LiveGraph activity i get the intent values like so:

import org.achartengine.GraphicalView;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

public class LiveGraph extends Activity {

    private static GraphicalView view;
    private LiveGraphClass live = new LiveGraphClass();
    private static Thread thread;


    private String myPrices;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_live_graph);
        Intent i = this.getIntent();
        myPrices = i.getStringExtra("stockprices");
        thread = new Thread(){
            @Override
            public void run() {
                for (double i = 0; i < 15; i++) {
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    Point p = getDataFromReceiver(i);
                    live.addNewPoints(p);
                    view.repaint();
                }

            }
        };
        thread.start();
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        view = live.getView(this);
        setContentView(view);
    }

    public Point getDataFromReceiver(double x){
        return new Point(x, Double.parseDouble(myPrices));
    }

}

My LiveGraphClass activity:

public class LiveGraphClass {


    private GraphicalView view;
    private TimeSeries dataset = new TimeSeries("Rain Fall");
    private XYMultipleSeriesDataset mDataset = new XYMultipleSeriesDataset();
    private XYSeriesRenderer renderer = new XYSeriesRenderer();
    private XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();

    public LiveGraphClass(){
        mDataset.addSeries(dataset);
        mRenderer.addSeriesRenderer(renderer);
        renderer.setColor(Color.WHITE);
        renderer.setPointStyle(PointStyle.SQUARE);
        renderer.setFillPoints(true);
        mRenderer.setExternalZoomEnabled(true);
        mRenderer.setZoomButtonsVisible(true);
        mRenderer.setBackgroundColor(Color.BLACK);
        mRenderer.setApplyBackgroundColor(true);
        mRenderer.setZoomEnabled(true);
        mRenderer.setYTitle("Range");
        mRenderer.setXTitle("Values");
    }

    public GraphicalView getView(Context context){

        view = ChartFactory.getLineChartView(context, mDataset, mRenderer);
        return view;
    }

    public void addNewPoints(Point p){
        dataset.add(p.getX(), p.getY());
    }
}

My point activity

public class Point {

    private double x;
    private double y;
    public Point(double x, double y) {
        super();
        this.x = x;
        this.y = y;
    }
    public double getX() {
        return x;
    }
    public double getY() {
        return y;
    }


}

and i get this error

03-25 12:20:09.515: E/AndroidRuntime(1671): java.lang.NumberFormatException: Invalid double: "[9.32, 5.22, 10.201, 2.54, 3.214, 1.02, 0.21, 0.147, 7.01, 0.365, 8.23, 0.254, 8.89, 0.155, 4.32]"
03-25 12:20:09.515: E/AndroidRuntime(1671):     at java.lang.StringToReal.invalidReal(StringToReal.java:63)
03-25 12:20:09.515: E/AndroidRuntime(1671):     at java.lang.StringToReal.parseDouble(StringToReal.java:269)
03-25 12:20:09.515: E/AndroidRuntime(1671):     at java.lang.Double.parseDouble(Double.java:295)

Can anybody help me solve this problem?? why is that happening since i send doubles through intent and i get doubles so i try to produce a double graph??

My php code:

<?php
try {
    $handler = new PDO(this is not available);
    $handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $e) {
    echo $e->getMessage();
    die();
}

$query = $handler->query('SELECT * FROM metoxes');
$records = array();
$records = $query->fetchAll(PDO::FETCH_ASSOC);
$json['metoxes'] = $records;
echo json_encode($json);
?>

Thanks in advance! any help will be much welcomed and appreaciated.

2条回答
老娘就宠你
2楼-- · 2019-09-02 16:54

You send the Intent as a string[] but you trying to receive it like as a String which is not possible. So do this instead:

Modify your LiveGraph class like this:

public class LiveGraph extends ActionBarActivity {

    private static GraphicalView view;
    private LiveGraphClass live = new LiveGraphClass();
    private static Thread thread;
    static String[] myPrices;
    double point;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_live_graph);
        Toolbar tb = (Toolbar) findViewById(R.id.toolBar);
        setSupportActionBar(tb);
        Intent i = this.getIntent();
        myPrices = i.getStringArrayExtra("stockprices");
        thread = new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < myPrices.length; i++) {
                    try {
                        Thread.sleep(800);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    Point p = new Point(i, Double.parseDouble(myPrices[i]));
                    live.addNewPoints(p);
                    view.repaint();
                }
            }
        };
        thread.start();
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        view = live.getView(this);
        setContentView(view);
    }
}

Hope it helps!!!

查看更多
Bombasti
3楼-- · 2019-09-02 16:57

The data you're pulling from MySQL is not in proper JSON format and cannot be converted to an array of doubles. A JSONArray is a collection of JSONObjects. Right now you're getting what appears to be a single Array formatted like [9.32, 5.22, 10.201 ... ]

What you should have is a JSONArray that contains JSONObjects

points:[{1:9.32},{2:5.22}]

You could then extract the JSONObjects from the JSONArray and simply access the number values directly

JSONArray points = new JSONArray(pointsString);
JSONObject firstPoint = points.getJSONObject(1);
double value = firstPoint.getDouble("1");

you can easily convert this to a loop to run over an entire JSONArray of values

Update - PHP issues

Your string is not coming back in proper JSON format because you are dumping the entire result if your query into a single array. Try something like this:

$outerObject = array();
$result = $query->fetchAll(PDO::FETCH_ASSOC);
$numResult = count($result);
for($i = 0; $i < $numResult; $i++){
     $indexDouble = result[$i];
     $innerObject = array();
     $innerObject['double'] = $indexDouble;
     $outerObject[] = $innerObject;
}
$json = array();
$json['metoxes'] = $outerObject;
echo json_encode($json);

I'd test that out first but the idea is that you need to create what will be the JSONArray and then add to it smaller inner arrays that will become the JSONObject. When you json_encode that you will have an array [] with objects {double:some_number}. To extract, all you have to do is loop through the JSONArray and get every double associated with key value double. It would work something like this:

JSONArray fullArray = JSONArray(stringInput);
int length = fullArray.length;
for(int i = 0; i < length; i++){

    double target = fullArray.getJSONObject(i).getDouble("double");
    //do something with the double
}
查看更多
登录 后发表回答