【问题标题】:How to convert from a List to Array ? Android如何从列表转换为数组?安卓
【发布时间】:2015-02-02 08:50:57
【问题描述】:

好的,伙计们,事情是这样的,我有一个使用 ODATA service 的应用程序,在 SMP server 中,我得到这样的数据:

public class callService extends AsyncTask<Void, Void, ArrayList<String>> 
    {
        public ArrayList<String> doInBackground(Void... params) 
        {
            ODataConsumer c = ODataJerseyConsumer.create("http://MyUrlService:8080");
            List<OEntity> listEntities = c.getEntities("MYENTITYTOCONSUME").execute().toList();
            System.out.println("Size" + listEntities.size());
            if (listEntities.size() > 0) 
            {               
                for (OEntity entity : listEntities) 
                {
                zmob_kunnr.add((String) entity.getProperty("Name1").getValue()
                    + " - "
                + entity.getProperty("Kunnr").getValue().toString());
                }
            }
            return zmob_kunnr;
        }   
        protected void onPostExecute(ArrayList<String> result) 
        {
        super.onPostExecute(result);
        adapter = new ArrayAdapter<String>(ConsumoKnuur.this, android.R.layout.simple_list_item_1, result);
        list.setAdapter(adapter);
        }
    }

好的,我从网络上得到了这个解决方案,可以实现为列表,我需要存储这个实体,其中一个是客户列表,并从这个实体中获取两个属性并保存在我的数据库中:

Entity Customer:Custormer_ID, Customer_Name

这是我调用我的 sqlite 的代码:

 public void sqlite() 
    {
        sql_obj.open();
        sql_obj.deleteAll();    
            for(int i=0; i < zmob_kunnr.size(); i++)
            {
                sql_obj.insert(zmob_kunnr.get(i).toString(), zmob_kunnr.get(i).toString() );   
            }
        sql_obj.close();
    }

还有我的 SQLite:

private static final String TABLE_CLIENTE = "CREATE TABLE " 
            + TB_CLIENTE
            + "(ID_CLIENTE INTEGER PRIMARY KEY AUTOINCREMENT, " //Id for controller my logics
            + " Kunnr TEXT , " //customer ID
            + " Name1 TEXT );"; //customer_name
public long insert(String name1, String Kunnr) 
    {   
        ContentValues initialValues = new ContentValues();
        initialValues.put("Name1", Name1); //Customer_Name
        initialValues.put("Kunnr", Kunnr); //Customer_ID
        return database.insert(TB_CLIENTE, null, initialValues);
    }

当然,我的其他方法并不重要,所以当我在 sql 调用方法中运行“for”时会发生什么,我得到列表的 size() 和列表的行并存储整个每次都在数据库的一列中,所以我得到了两个具有相同值的不同表,

我怎样才能改变解决这个问题,而不是在列表中消费我需要在数组中消费?或者我需要创建一个获取列表值的方法,然后在 ,(coma) 之后,创建两个不同的对象来存储这些数据?

我在网上看了很久,没有找到,可能是因为我还不知道,所以,我不知道我在找什么,我正在使用odata4j API 这是文档的链接,http://odata4j.org/v/0.7/javadoc/

我是编程新手,所以我真的遇到了麻烦,任何有帮助的建议都将是真正的,不胜感激,

非常感谢,祝你有美好的一天!!!

【问题讨论】:

  • zmob_kunnr 是如何定义的?如果您将 zmob_kunnr 的类型更改为 ArrayList&lt;OEntity&gt;,您可以在您的 insert 语句中使用 sql_obj.insert(zmob_kunnr.get(i).getProperty("Name1").getValue(), zmob_kunnr.get(i).getProperty("Kunnr").getValue().toString());
  • 您好 Nayeem 非常感谢您的有用回答,我理解您的逻辑,现在说得通了,我将 mob_kunnr 更改为 ArrayList,我还更改了 zmob_kunnr 的所有其他调用,但是方法 zmob_kunnr.add 给我“添加”一个问题(类型 ArrayList 中的方法 add(OEntity) 不适用于参数(String))更改为 addAll 并且如果我仍然存在问题并且告诉我要添加
  • 哈哈好吧我不是Nayeem,但你需要将for循环的主体更改为zmob_kunnr.add(entity)
  • 哦对不起lan2thedv,我现在才意识到我的赌注对不起!!!
  • 嘿,非常感谢,我可以解决我的问题,非常感谢我很感激,顺便说一下,在这个解决方案中我能够获得 4 个不同的实体?w 或者我需要创建一个每个循环??

标签: java android arrays sqlite odata


【解决方案1】:

您可以通过执行以下操作将每个实体添加到 `ArrayList' 数组中:

for (OEntity entity : listEntities) {
    zmob_kunnr.add(entity);
}

这将允许您在插入数据库时​​通过getProperty() 访问实体中包含的数据。

以下语句也不需要,因为for each循环遍历列表中的每个元素,因此如果列表为空,for (OEntity entity : listEntities)将不会执行。

if (listEntities.size() > 0) {               
    ...
}

如果您有多个ODataConsumers,您有两种选择,具体取决于您的要求(如果我理解您的问题的话):

  1. 可以依次获取每个ODataConsumer,获取listEntities,加入zmob_kunnr列表,列表项加入数据库后,清空zmob_kunnr列表,调用@987654331 @ 带有新的 URL。这是您当前的解决方案所允许的。

在将值读入数据库时​​,似乎需要知道哪个属性与 URL 相关联。您可以使用 POJO 作为实体及其属性列表的持有者。您现在可以添加和删除属性。请注意,属性将按照插入时的相同顺序被删除。

public class OEntityHolder {
    private final OEntity entity;
    private Queue<String> properties;

    public OEntityHolder(OEntity entity) {
        this.entity = entity;
        this.properties = new LinkedBlockingQueue<>();
    } 

    public OEntity getEntity() {
        return this.entity;
    }

    public void addProperty(String property) {
        this.properties.add(property);
    }

    public void removeProperty() {
        this.properties.poll();
    }
}

这将需要更改包含entities 的列表:

ArrayList<OEntityHolder> zmob_entity_holders = new ArrayList<>();

如果您想同时添加来自不同 URL 的所有 entities,则需要在调用 doInBackground 时访问所有 URL。像这样的:

public ArrayList<OEntityHolder> doInBackground(Void... params) {
    String [][] urls = {{"http:MyUrl/ZMOB_FECODSet", "Name1", "Fecod"},
                        {"http:MyUrl/ZMOB_OTEILSet", "Name2", "Oteil"},
                        {"http:MyUrl/ZMOB_KUNNRSet", "Name3", "Kunnr"},
                        {"http:MyUrl/ZMOB_BAULTSet", "Name4", "Bault"}};
    for (String [] urlProp:urls) {
        //Here you get the list of entities from the url
        List<OEntity> listEntities = ODataJerseyConsumer.create(urlProp[0]).getEntities("MYENTITYTOCONSUME").execute().toList();
        for (OEntity entity:listEntities) {
            OEntityHolder holder = new OEntityHolder(entity);
            for (int i = 1; i < urlProp.length; i++)
                holder.addProperty(urlProp[i]);
            zmob_entity_holders.add(holder);
        }
    }
    //At this point, all of the entities associated with the list of URLS will be added to the list
    return zmob_entity_holders;
}   

您现在拥有与zmob_kunnr 中的 URL 列表关联的所有实体。在您可以并且可以像这样将 then 插入数据库之前:

for (OEntityHolder holder : zmob_entity_holders) {
    sql_obj.insert(holder.getEntity().getProperty(holder.removeProperty()).toString(), holder.getEntity().getProperty(holder.removeProperty()).toString());
}

如果每个实体都有一个关联名称,您可以将名称存储在映射中,其中key 是 URL,value 是名称。

HashMap<String, String> urlEntityNames = new HashMap<>();
urlEntityNames.put("http://MyUrlService:8080", "MYENTITYTOCONSUME");
...//Add more URLs and entity names

然后,您可以在遍历实体列表时在地图中查找正确的名称:

List<OEntity> listEntities = ODataJerseyConsumer.create(url).getEntities(urlEntityNames.get(url)).execute().toList();

我希望这会有所帮助,如果我误解了你,请在 cmets 中纠正我。

编辑:添加了 URL、持有者和数据库插入列表。

【讨论】:

  • 哦,也非常感谢@lan2thedv,感谢你们两个,这也是我想要的……!!!
  • 是的,答案将所有实体添加到zmob_kunnr。我现在看到ZMOB_KUNNRSetzmob_kunnr 列表之间的关联,但我不确定我是否理解正确。您想将 http:MyUrl/ZMOB_KUNNRSet 中的实体添加到 zmob_kunnr、http:MyUrl/ZMOB_OTEILSet 到 zmob_oteil 等。它们的属性会改变吗?例如:http:MyUrl/ZMOB_OTEILSet - entity.getProperty("Oteil")?
  • 好的,我明白了,我更新了答案。不幸的是,由于我对您的全部问题或解释缺乏了解,因此我无法为您提供任何进一步的帮助。如果还有其他我无法帮助您解决的问题,请发布一个新问题,它会得到更多关注。祝你好运!
  • 没问题!很高兴我能帮忙:)
  • 嘿@lan2thedv,你能重新上传一下你的最后一个代码吗,这对我来说更有意义,我几乎找到了我想要对你说的话的解决方案,并发布为回答,但是当我调用第二个时,我在 postExecute 方法上的第二个 AsyncTask 的最后一个异常,这就是为什么我想要你的最后一个代码,看看我该如何管理它,非常感谢......跨度>
【解决方案2】:

我想我找到了解决方案,但我的日志猫对我的第二个 doInBackgroundBault(材料)的任何更新都给出了例外,

public class callServiceCliente extends AsyncTask<Void, Void, ArrayList<OEntity>> {
    protected void onPreExecute() {
        progressC = ProgressDialog.show(Atualizar_Dados.this, "Aguarde...", "Atualizando Clientes", true, true);
    }

    public ArrayList<OEntity> doInBackground(Void... params) {
        ODataConsumer ccli = ODataJerseyConsumer.create(URL);
        List<OEntity> listEntitiesKunnr = ccli.getEntities("ZMOB_KUNNRSet").execute().toList();

        System.out.println("Size" + listEntitiesKunnr.size());

        for (OEntity entityKunnr : listEntitiesKunnr) {
            zmob_kunnr.add(entityKunnr);
        }
        return zmob_kunnr;
    }

    protected void onPostExecute(ArrayList<OEntity> kunnr) {
        super.onPostExecute(kunnr);
        try {
            sql_obj.open();
            sql_obj.deleteAll();

            for (int k = 0; k < zmob_kunnr.size(); k++) {
                sql_obj.insertCliente(zmob_kunnr.get(k).getProperty("Kunnr").getValue().toString().toUpperCase(), zmob_kunnr.get(k).getProperty("Name1").getValue().toString().toUpperCase());
            }
            sql_obj.close();
        } catch (Exception e) {
        }
        try {
            clienteAdapter = new ArrayAdapter<OEntity>(Atualizar_Dados.this, android.R.layout.simple_list_item_1, kunnr);
            listCliente.setAdapter(clienteAdapter);

        } catch (Exception eq) {
        }
        progressC.dismiss();
        new callServiceMaterial().execute();
    }
}

public class callServiceMaterial extends AsyncTask<Void, Void, ArrayList<OEntity>> {
    protected void onPreExecute() {
        progressM = ProgressDialog.show(Atualizar_Dados.this, "Aguarde...", "Atualizando Materiais", true, true);
    }

    public ArrayList<OEntity> doInBackground(Void... params) {
        ODataConsumer cmat = ODataJerseyConsumer.create(URL);
        List<OEntity> listEntitiesBault = cmat.getEntities("ZMOB_BAULTSet").filter("IErsda eq '20141101'").execute().toList();
        System.out.println("Size" + listEntitiesBault.size());
        for (OEntity entityBault : listEntitiesBault) {
            zmob_bault.add(entityBault);
        }
        return zmob_bault;
    }

    protected void onPostExecute(ArrayList<OEntity> bault) {
        super.onPostExecute(bault);
        try {
            sql_obj.open();
            sql_obj.deleteAll();
            for (int b = 0; b < zmob_bault.size(); b++) {
                sql_obj.insertMaterial(zmob_bault.get(b).getProperty("Matnr").getValue().toString().toUpperCase(), zmob_bault.get(b).getProperty("Maktxt").getValue().toString().toUpperCase());
            }
            sql_obj.close();
        } catch (Exception e) {
        }
        try {
            materialAdapter = new ArrayAdapter<OEntity>(Atualizar_Dados.this, android.R.layout.simple_list_item_1, bault);
            listMaterial.setAdapter(clienteAdapter);

        } catch (Exception eq) {
        }
        progressM.dismiss();
        new callServiceProblema().execute();
    }
}

public class callServiceProblema extends AsyncTask<Void, Void, ArrayList<OEntity>> {
    protected void onPreExecute() {
        progressProb = ProgressDialog.show(Atualizar_Dados.this, "Aguarde...", "Atualizando Problemas", true, true);
    }

    public ArrayList<OEntity> doInBackground(Void... params) {
        ODataConsumer cprob = ODataJerseyConsumer.create(URL);
        List<OEntity> listEntitiesFecod = cprob.getEntities("ZMOB_FECODSet").execute().toList();

        System.out.println("Size" + listEntitiesFecod.size());
        for (OEntity entityFecod : listEntitiesFecod) {
            zmob_fecod.add(entityFecod);
        }
        return zmob_fecod;
    }

    protected void onPostExecute(ArrayList<OEntity> fecod) {
        super.onPostExecute(fecod);
        try {
            sql_obj.open();
            sql_obj.deleteAll();
            for (int f = 0; f < zmob_fecod.size(); f++) {
                sql_obj.insertProblema(zmob_fecod.get(f).getProperty("Fecod").getValue().toString().toUpperCase(), zmob_fecod.get(f).getProperty("Kurztext").getValue().toString().toUpperCase());
            }
            sql_obj.close();
        } catch (Exception e) {
        }
        try {
            problemaAdapter = new ArrayAdapter<OEntity>(Atualizar_Dados.this, android.R.layout.simple_list_item_1, fecod);
            listProblema.setAdapter(problemaAdapter);

        } catch (Exception eq) {
        }
        progressProb.dismiss();
        new callServiceProcedencia().execute();
    }
}

public class callServiceProcedencia extends AsyncTask<Void, Void, ArrayList<OEntity>> {
    protected void onPreExecute() {
        progressProc = ProgressDialog.show(Atualizar_Dados.this, "Aguarde...", "Atualizando base de dados", true, true);
    }

    public ArrayList<OEntity> doInBackground(Void... params) {
        ODataConsumer c = ODataJerseyConsumer.create(URL);
        List<OEntity> listEntitiesProcedencia = c.getEntities("ZMOB_OTEILSet").execute().toList();
        System.out.println("Size" + listEntitiesProcedencia.size());
        for (OEntity entityProcedencia : listEntitiesProcedencia) {
            zmob_oteil.add(entityProcedencia);
        }
        return zmob_oteil;
    }

    protected void onPostExecute(ArrayList<OEntity> oteil) {
        super.onPostExecute(oteil);
        try {
            sql_obj.open();
            sql_obj.deleteAll();

            for (int o = 0; o < zmob_oteil.size(); o++) {
                sql_obj.insertCliente(zmob_oteil.get(o).getProperty("Fecod").getValue().toString().toUpperCase(), zmob_oteil.get(o).getProperty("Kurztext").getValue().toString().toUpperCase());
            }
            sql_obj.close();
        } catch (Exception e) {
        }
        try {
            procedenciaAdapter = new ArrayAdapter<OEntity>(Atualizar_Dados.this, android.R.layout.simple_list_item_1, oteil);
            // listCliente.setAdapter(clienteAdapter);

        } catch (Exception eq) {
        }
        progressProc.show(Atualizar_Dados.this, "Finalizado", "Base de dados atualizada", true, true).dismiss();
        Toast.makeText(Atualizar_Dados.this, "Base de dados atualizada com sucesso", Toast.LENGTH_LONG).show();
    }
}

好的,这是我找到的解决方案,我无法插入您的解决方案,因为当我输入 inser.add(entity) 时,它们没有向我显示属性,但如果您有更好的方法做我所做的,我会非常感激,

顺便说一句,我需要在 filter() 中按范围日期查询这个消耗。就像我在这里做的那样......

列表 listEntitiesBault = cmat.getEntities("ZMOB_BAULTSet").filter("IErsda eq '20141101'").execute().toList();但不起作用,所以我不知道为什么,我在互联网上看到了几个关闭的解决方案,并看到了 .top(1) 和 .first(); 等字段;我不明白...

非常感谢!!!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-29
    • 1970-01-01
    • 2017-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-24
    • 2017-02-22
    相关资源
    最近更新 更多