如果互联网连接不可用,请加载本地数据

时间:2016-04-04 15:10:11

标签: android network-programming android-volley

我有一个Android应用程序,它显示来自我的外部数据库的数据,所以来自几个表。当互联网连接可用时,一切正常(所有数据都来自URL链接,并且它们已经被齐射解析)。但是,当互联网不可用时,如何保存和加载最新数据。

最好的方法是什么?我是android的新手......

请帮忙。

2 个答案:

答案 0 :(得分:1)

通常Volley以及它使用的HttpStack允许您无缝缓存响应。但这取决于您的回复和要求。这些缓存策略遵循http缓存定义。如果你想为Volley提供不同的行为,你可以覆盖这一部分。基本上,当您创建请求时,您可以覆盖

protected Response<String> parseNetworkResponse(NetworkResponse response) {

而不是

return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
你做了

long now = System.currentTimeMillis();
Cache.Entry entry = HttpHeaderParser.parseCacheHeaders(response);
        entry.ttl = now + 30l * 24 * 60 * 60 * 1000;  //kepps cache for 30 days 
//entry.softTtl = now + 30l * 24 * 60 * 60 * 1000;  //will not refresh for 30 days     
        return Response.success(parsed, entry);

每次服务器指定时基本上都会刷新缓存,但除非更改,否则将始终返回缓存30天。

请注意,在这里您可能会收到2个回复或一个响应和1个错误(如果没有网络)。第一个将是缓存。

<强>更新

如果你添加(在上面的例子中注释):

entry.softTtl = now + 30l * 24 * 60 * 60 * 1000;  //will not refresh for 30 days 

这会影响缓存的刷新。在这种情况下,它不会尝试刷新缓存30天。在这种情况下,您将返回1个回复。

请注意,我从不推荐这样的解决方案,因为缓存需要更新,特别是如果你想在POST请求中伪造缓存,就像你的情况一样。

接收2个回调并不是真正的问题,因为您可以为用户处理这个无缝的问题,并在需要时更新UI。此外,如果你想拥有更多控制权,你可以通过实施

来了解哪一个来自缓存,哪一个来自网络?
  

ResponseDelivery

或延伸

  

ExecutorDelivery

然后检查参数

  

mResponse.intermediate

然后决定该怎么做。 ResponseDelivery是调用回调的那个。

<强>更新

类似的问题和示例here

答案 1 :(得分:0)

if you have to store only small chunk of data then use SharedPreferences If you have large data then use SQLite

Use below code to create and update SQLite DB

public class SqlMangaeMenu 
{
SQLiteDatabase db1 = null;
private static String DBNAME = "YourLocal.db";
Context gcntxt;


public SqlMangaeMenu(Context cntxt) 
{
    // TODO Auto-generated constructor stub     

    gcntxt=cntxt;
    db1 = cntxt.openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);

    db1.execSQL("CREATE TABLE IF NOT EXISTS mytbl(appid varchar PRIMARY KEY,appname varchar,iconcode varchar,msgidentfier varchar,scode varchar,image blob,imagehdr blobhdr); ");

}//EOF Constructor



public void insertContent(String appid,String appname,String iconcode,String msgidentifier,String scode,Bitmap bmp,Bitmap bmphdr)
{
    ContentValues contentValues = new ContentValues();

    contentValues.put("appid", appid);
    contentValues.put("appname", appname);
    contentValues.put("iconcode", iconcode);
    contentValues.put("msgidentfier", msgidentifier);
    contentValues.put("scode", scode);  

    byte[] blob = null,blobhdr=null;
    if(bmp!=null)
    {
    ByteArrayOutputStream outStr = new ByteArrayOutputStream();
    bmp.compress(CompressFormat.PNG, 100, outStr);
    blob = outStr.toByteArray();        
    }
    contentValues.put("image", blob);

    if(bmphdr!=null)
    {
    ByteArrayOutputStream outStr1 = new ByteArrayOutputStream();
    bmphdr.compress(CompressFormat.PNG, 100, outStr1);
    blobhdr = outStr1.toByteArray();

    }
    contentValues.put("imagehdr", blobhdr);

    Log.d("db", "SQL Writing"+appid+appname+iconcode+msgidentifier+scode);

    try {
        // db1.insert("mytbl",null,contentValues);
        db1.insertWithOnConflict("mytbl", null, contentValues,SQLiteDatabase.CONFLICT_IGNORE);
    } catch (Exception e) 
    {
        // TODO: handle exception

    }


    db1.close();

}//EOF insertContent

// Deleting single contact
public void Delete_appid(String id) 
{
   db1.delete("mytbl", "appid" + "=" + id, null);

    db1.close();
}//EOF Delete_appid


public void readAppId()
{

    MyApplication.dbappid=new ArrayList<String>();      

    String appid;
    try
    {          

        Cursor c = db1.rawQuery("SELECT * FROM mytbl", null);
        //Cursor c = db1.rawQuery("SELECT MAX(ID) FROM mytbl", null);


        if(c!= null)
        {
         if (c.moveToFirst()) 
              {
                do {
                    appid=c.getString(c.getColumnIndex("appid"));


                    MyApplication.dbappid.add(appid);


                   }while(c.moveToNext());
               }


          }
        Log.d("db", "SQL Reading");
        db1.close();
        } 
     catch(Exception e)
     {
          System.out.println(e);

     }

}//EOF readAppId


public void readDataandImage()
{
    Bitmap image=null,imagehdr = null;
    //Bitmap images
    MyApplication.dbimg=new ArrayList<Bitmap>();
    MyApplication.dbhdrimage=new ArrayList<Bitmap>();

    //String
    MyApplication.dbappname=new ArrayList<String>();
    MyApplication.dbappid=new ArrayList<String>();
    MyApplication.dbiconcode=new ArrayList<String>();


    String appname,appid,iconcode;
    try
    {
        Cursor c = db1.rawQuery("SELECT * FROM mytbl", null);

        if(c!= null)
        {
         if (c.moveToFirst()) 
              {
                do {

                    image=null;imagehdr=null;
                    byte[] blob = c.getBlob(c.getColumnIndex("image"));
                    byte[] blobhdr = c.getBlob(c.getColumnIndex("imagehdr"));
                    appid=c.getString(c.getColumnIndex("appid"));
                    appname=c.getString(c.getColumnIndex("appname"));
                    iconcode=c.getString(c.getColumnIndex("iconcode"));

                    if(blob!=null)
                    {
                    image = BitmapFactory.decodeByteArray(blob, 0, blob.length);
                    }
                    if(blobhdr!=null)
                    {
                    imagehdr = BitmapFactory.decodeByteArray(blobhdr, 0, blobhdr.length);
                    }

                    //Images
                    MyApplication.dbimg.add(image);
                    MyApplication.dbappid.add(appid);

                    //String
                    MyApplication.dbappname.add(appname);
                    MyApplication.dbiconcode.add(iconcode);
                    MyApplication.dbhdrimage.add(imagehdr);



                   }while(c.moveToNext());
               }


          }
        Log.d("db", "SQL Reading");
        db1.close();
        } 
     catch(Exception e)
     {
          System.out.println(e);

     }


}//EOF readDataandImage


public int dbRowCount()
{
    int rowcnt=0;
    String countQuery = "SELECT * FROM mytbl";
    //SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db1.rawQuery(countQuery, null);
    rowcnt = cursor.getCount();
    cursor.close();
    db1.close();
    Log.d("db", "Numrecs"+rowcnt);
    return rowcnt;
}//EOFdbRowCount 

}

where MyApplication is a static class to hold the read values.