2017-01-20 25 views
0

我有一个自定义数组列表需要保存在sqlite中,我将此数组列表转换为字符串使用字符串方法并将其保存在数据库中。现在我需要再次这个数组list.So如何转换自定义数组列表形式这个特定的字符串。将字符串转换为自定义ArrayList

这是我用来数组转换为字符串

ArrayList<Publication> pb = new Array List<Publication>(); 
pb.add(new Publication("", "")); 
String st = pb.tostring(); 

代码现在我在SQLite数据库添加st为字符串。我的问题是我如何从这个字符串恢复到发布的自定义ArrayList。

+1

发布UR串 – Athul

+0

请的一个例子分享您的代码 –

+0

你是怎么保存的数组列表?在每个字符串之后添加逗号(,)? –

回答

1

您可以使用阅读串Gson将字符串转换为自定义ArrayList的库。 在您的应用程序添加此gradle这个依赖的build.gradle

compile 'com.google.code.gson:gson:2.2.+' 

然后使用此代码

Gson gson = new Gson(); 
TypeToken<ArrayList<Publication>> token = new TypeToken<ArrayList<Publication>>() { 
    }; 
ArrayList<Publication> pb = gson.fromJson(str, token.getType()); 
+0

我从sqlite数据库像这样[[email protected],[email protected]]获取字符串值,你的代码不在这里工作。这里常见的是我的包名和发布是一个班级名称。 – Rims

+0

Publication类构造函数的参数是什么? –

+0

有多个字段,如int publication_id; byte [] publication_image; String publication_date;字符串publication_color – Rims

0

如果分隔 “”

String[] strValues = str.split(",");//this is the string u saved in sqlite 

/*Use asList method of Arrays class to convert Java String array to ArrayList*/ 
ArrayList<Publication> aList = new ArrayList<Publication>(); 
for(i=0; i<strValues.count(); i++) 
aList.add(new Publication().setField(strValues[i])); 

现在自定义类公开

class Publication{ 
String field; 

public void setField(String f) { 

field=f; 
} 

public String getField() { 

return field; 
} 

} 

for (String value: strValues) { 
    aList.add(new Publication(value)); 
} 

class Publication { 
    private final String input; 

    public Publication(String input) { 
     this.input = input; 
    } 

    // not needed but implemented for completeness  
    public static Publication parse(String input) { 
     return new Publication(input); 
    } 
} 



检查: 你不会成为能够插入ArrayList中直接进入sqlite的。相反,你可以使用JSONObject(org.json.JSONObject)来插入ArrayList。请在下面检查,并给它一个镜头....

//Add values to arraylist item 
ArrayList<Publication> item = new ArrayList<Publication>(); 
item.add //add the item to array list 

要插入,

JSONObject json = new JSONObject(); 
json.put("uniqueArrays", new JSONArray(items)); 
String arrayList = json.toString(); 
Insert the string into db. 

阅读,从数据库字符串,

JSONObject json = new JSONObject(stringreadfromsqlite); 
    ArrayList<Publication> items = json.optJSONArray("uniqueArrays"); 
+0

我使用ArrayList ,它意味着自定义对象。 – Rims

+0

Wt是出版领域然后 – Athul

+0

@Rheema在出版物 – Athul

相关问题