【问题标题】:How to pass an ArrayList<String> to another activity and convert it into double如何将 ArrayList<String> 传递给另一个活动并将其转换为双精度
【发布时间】:2014-05-03 15:43:40
【问题描述】:

大家好,我正在构建一个应用程序,该应用程序通过我从 mysql 获得的一些值生成动态图,这些值在 json 数组中请求。

我的代码是:

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);
            }
        });

在 LiveGraph 活动中,我得到这样的意图值:

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));
    }

}

我的 LiveGraphClass 活动:

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());
    }
}

我的积分活动

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;
    }


}

我得到了这个错误

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)

谁能帮我解决这个问题?为什么会发生这种情况,因为我通过意图发送双打并且我得到双打所以我尝试生成双图??

我的php代码:

<?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);
?>

提前致谢!任何帮助都将受到欢迎和赞赏。

【问题讨论】:

  • 请大家帮忙看看如何从graphfragment获取值到livegraph类中??

标签: android mysql android-intent android-fragments


【解决方案1】:

您从MySQL 提取的数据不是正确的JSON 格式,无法转换为双精度数组。 JSONArrayJSONObjects 的集合。现在,您得到的似乎是单个 Array,其格式类似于 [9.32, 5.22, 10.201 ... ]

你应该有一个包含JSONObjectsJSONArray

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

然后您可以从JSONArray 中提取JSONObjects 并直接访问数字值

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

您可以轻松地将其转换为循环以运行整个 JSONArray

更新 - PHP 问题

您的字符串没有以正确的JSON 格式返回,因为如果您的查询进入单个数组,您会将整个结果转储。试试这样的:

$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);

我会先对其进行测试,但想法是您需要创建将成为 JSONArray 的内容,然后向其中添加将成为 JSONObject 的更小的内部数组。当您 json_encode 时,您将拥有一个包含对象 {double:some_number} 的数组 []。要提取,您所要做的就是遍历JSONArray 并获取与键值双精度相关的每个双精度。它会像这样工作:

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
}

【讨论】:

  • 意图正确??然后我得到一个 Intent i = this.getIntent(); myPrices = i.getStringExtra("stockprices");我将如何将字符串转换为 jsonarray??
  • 使用 log.d 获取整个字符串我会告诉你如何转换它
  • 就是这样。无效双精度:“[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]”
  • 您需要修改从服务器获取的内容。这是来自PHP吗?可以显示后端代码吗?
【解决方案2】:

您将 Intent 作为字符串 [] 发送,但您尝试将其作为字符串接收,这是不可能的。所以改为这样做:

像这样修改你的 LiveGraph 类:

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);
    }
}

希望对你有帮助!!!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-27
    • 1970-01-01
    相关资源
    最近更新 更多