Android如何将msg保存到本地存储?

时间:2015-06-11 21:39:44

标签: android sqlite local-storage

我对Android开发人员来说很陌生。我目前正在制作一个简单的消息应用。所以我想存储从节点服务器收到的所有短信。我现在不应该怎么做。

我从节点服务器收到的消息是JSONObject,如:

{"name":"XX", "id":"XX","message":"xxxxxxxx"}

我正在使用Custom ArrayAdepter来显示文本:

public class ChatArrayAdapter extends ArrayAdapter<Text> {

private TextView text,avatar;
private List<Text> msgcontx = new ArrayList<Text>();
private LinearLayout wrapper;

@Override
public void add(Textobject){
    msgcontx.add(object);
    super.add(object);
}

public ChatArrayAdapter(Context context,int textViewResourceId) {
    super(context, textViewResourceId);
}

public int getCount(){
    return this.msgcontx.size();
}

public Text getItem(int index){
    return this.msgcontx.get(index);
}

public View getView(int position,View convertView,ViewGroup parent){
    View row = convertView;
    if(row == null){
        LayoutInflater inflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        row = inflater.inflate(R.layout.chat_listview, parent,false);
    }
    wrapper = (LinearLayout)row.findViewById(R.id.wrapper);
    Text comment = getItem(position);

    avatar = (TextView)row.findViewById(R.id.avatar);
    avatar.setText(comment.userID);
    avatar.setVisibility(comment.left? View.VISIBLE: View.GONE);

    text = (TextView)row.findViewById(R.id.comment);
    text.setText(comment.comment);
    // chat background to be changed
    text.setBackgroundResource(comment.left ? R.drawable.bg_chat_recipient : R.drawable.bg_chat_sender );
    wrapper.setGravity(comment.left? Gravity.START : Gravity.END);

    return row;
}

  public Bitmap decodeToBitmap(byte[] decodedByte){
    return BitmapFactory.decodeByteArray(decodedByte, 0,decodedByte.length );

  }
}

现在我不知道如何在本地存储中存储从节点服务器收到的msg,当我打开应用程序时,我还要显示msg历史记录。

我应该使用SQL吗?但我应该如何存储消息?把它们放在不同的行? 我知道这可能是一个愚蠢的问题,但我真的不知道如何将msg存储到本地存储并再次阅读它们。

任何人都可以简单介绍一下吗?非常感谢!

1 个答案:

答案 0 :(得分:0)

你应该使用某种类型的数据库。我推荐一个带有orm的sql db - 它允许你根据类创建一个数据库,并且不需要大量的sql。

我喜欢active android,但也看看糖的情况。

您应该有一个消息表,表中的每一行都是一条消息。在一个orm中,您可以使用类来定义消息。示例代码(使用ActiveAndroid orm):

@Table(name="Messages")
class Message extends Model {
    String name;
    String id;
    String message;

    //the empty consructor is required by active android
    public Message(){
       super();
    }

}

要实际将消息输入数据库,您需要解析json并从中创建Messages对象,然后保存它们。要将json解析为Message对象,您可以使用Gson或logan square

相关问题