【问题标题】:How to save an array into a PHP database如何将数组保存到 PHP 数据库中
【发布时间】:2018-02-17 02:44:20
【问题描述】:

我尝试将数组放入数据库。在edittext中,我写了例如大蒜、西红柿、洋葱,但是当我将数据保存到数据库并转到我的php数据库时,它只说成分而不是那个文本。如果我手动添加文本(我手动添加数字而不是成分,但它是同一件事)到数据库它看起来不错并创建了良好的 json 文件。我该如何解决这个问题?

MainActivity.java

String id;
    ArrayList<String> ingredients = new ArrayList<String>();

    @BindView(R.id.etId) EditText etId;
    @BindView(R.id.etIngredients) EditText etIngredients;



    id = etId.getText().toString();
    ingredients = etIngredients.getText().toString();

食谱.java

public class Recipes {
    String id;
    List<String> ingredients;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public List<String> getIngredients() {
        return ingredients;
    }

    public void setIngredients(List<String> ingredients) {
        this.ingredients = ingredients;
    }
}

以及如何在列中检索该成分?

我使用它从 json 文件中返回它,但它连续返回成分 [1,3,4,5,6]

Reipes rec = recipes.get(position);
    holder.textViewId.setText(rec.getId());
    holder.textViewIngredients.setText(rec.getIngredients().toString());

my online database

前 4 个菜谱是手动添加的,其中的成分是在 android 应用中添加的。

how it looks when get data in android

【问题讨论】:

  • 首先为什么要将逗号分隔的值保存到单个字段中?这就是一对多关系和外键的用途。首先正确地规范您的数据库。然后,如果您说 PHP 仍然没有正确保存它,我们将需要准确地知道您从 Java 发送到 PHP 的数据字符串的格式。如果您对字符串正确感到满意,那么我们需要查看执行保存的 PHP 代码。
  • 其次,如果您从 PHP 服务器以 JSON 形式返回一组成分 ID,并且您想以不同的方式显示它们,则必须循环遍历它们并单独处理它们,而不仅仅是将数据作为字符串转储到您的屏幕中(这就是您现在正在做的事情)。
  • 你可以简单地将你的成分作为一个字符串变量发送,为什么要把它作为 ArrayList

标签: java php android json


【解决方案1】:

你将不得不更换

ArrayList<String> ingredients = new ArrayList<String>();

通过

String ingredients;

在你的食谱课上尝试改变成分的类型

String ingredients;
public String getIngredients() {
    return ingredients;
}

public void setIngredients(String ingredients) {
    this.ingredients = ingredients;
}

【讨论】:

    猜你喜欢
    • 2012-09-29
    • 1970-01-01
    • 2016-06-14
    • 1970-01-01
    • 2014-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    相关资源
    最近更新 更多