在android中的特定时间段后缓存json数据

时间:2015-07-06 11:29:44

标签: android json sqlite

我在显示Json数据方面遇到了麻烦。

我想获取数据并将其保存在数据库中,然后刷新数据,每24小时更新一次。

但是在我的代码中每次访问webservice以显示数据时,我想要的是24小时后要更新的数据库以及要从数据库显示的其余时间值。

代码:

public class Banking_Economics extends ListActivity implements
        OnItemClickListener {

    ProgressDialog pd;
    ListView lv;

    SQLiteDB db;
    SQLiteDatabase sdb;

    private static final String CurrentAffairs = "CurrentAffairs";

    // url to make request
    private static String url = "http://10.0.2.2:53159/WebSite5/Default2.aspx";

    // JSON Node names
    private static final String TAG_FILE_NAME = "tests";
    private static final String TAG_MESSAGE = "message";
    // private static final String TAG_STATUS = "status";
    public final ArrayList<HashMap<String, String>> testList = new ArrayList<HashMap<String, String>>();;
    public final ArrayList<String> result=new ArrayList<String>();;

    // contacts JSONArray
    JSONArray tests;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.banking_eco);
        lv = (ListView) findViewById(android.R.id.list);
        // db=new SQLiteDB(Banking_Economics.this);
        sdb = openOrCreateDatabase("me1.db", MODE_PRIVATE, null);

        /*
         * Log.i("In BankingEconomics","creating table"); String sql=
         * "create table CurrentAffairs(id integer primary key autoincrement, message varchar)"
         * ; sdb.execSQL(sql); Log.i("In BankingEconomics","table created");
         * Toast.makeText(this, "your table is created",
         * Toast.LENGTH_LONG).show();
         */
        /*
         * sql="delete from Questions where aliasname=28"; db.execSQL(sql);
         * Log.i("In BankingEconomics","Records deleted...");
         */
        // db.close();


        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    boolean connected = false;
                    ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
                    NetworkInfo[] info = connectivityManager.getAllNetworkInfo();
                        if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED || 
                                connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
                            //we are connected to a network
                            connected = true;
                            //Toast.makeText(Banking_Economics.this, "network connected", Toast.LENGTH_LONG).show();
                            json();
                            //disp();
                        }
                        else{
                            connected = false;
                           // Toast.makeText(Banking_Economics.this, "network not connected", Toast.LENGTH_LONG).show();
                           // disp();
                        }

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            // stuff that updates ui
                            /**
                             * Updating parsed JSON data into ListView
                             * */

                            disp();

                        }

                    });

                } catch (Exception ex) {
                    ex.printStackTrace();
                }

            }
        }).start();
        // new LoadList().execute();
        // sdb.close();
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public void disp() {
        try {
            Cursor c;
            // c=db.getAllData();
            String sql = "select * from CurrentAffairs LIMIT 10";
            c = sdb.rawQuery(sql, null);
            if (c != null) {
                // if (c.moveToNext()) {
                while (c.moveToNext()) {

                    String message = c.getString(c.getColumnIndex("message"));
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key =>
                    // value
                    map.put(TAG_MESSAGE, message);
                    result.add(message);

                }// while(c.moveToNext());
            }
        } catch (Exception e) {
            // TODO: handle exception
            Log.i("In Banking economics", "Error-" + e.toString());
            e.printStackTrace();
        }
        //ListAdapter adapter = new SimpleAdapter(Banking_Economics.this, result,R.layout.list_item, new String[] { TAG_MESSAGE },new int[] { R.id.textView1 });
        ListAdapter adapter=new ArrayAdapter<String>(this, R.layout.list_item,R.id.textView1, result);
        setListAdapter(adapter);
        // selecting single ListView item
        lv = getListView();

        // Launching new screen on Selecting Single ListItem
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                String message = ((TextView) view.findViewById(R.id.textView1))
                        .getText().toString();

                // Starting new intent
                Intent in = new Intent(getApplicationContext(), News.class);
                in.putExtra(TAG_MESSAGE, message);
                startActivity(in);

            }

        });
    }

    public void json(){
        // Your implementation
        // Hashmap for ListView
        File file = new File ("CurrentAffairs");
        Calendar calendar = Calendar.getInstance();
        //System.out.println("Current time => " + c.getTime());
        calendar.setTime(new Date());
        calendar.add(Calendar.HOUR, +24);
        long mSec = calendar.get(Calendar.MILLISECOND);
        SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");

        //String formattedDate = df.format(calendar.getTime());
        //Date z=df.parse(formattedDate);
        //long date=file.lastModified();
        if(file.exists()){
            if(file.lastModified()+mSec>System.currentTimeMillis()){
                final ArrayList<HashMap<String, String>> testList = new ArrayList<HashMap<String, String>>();

                // Creating JSON Parser instance
                Jsonparse jParser = new Jsonparse();
                Log.i("in Main activity", "Jsonparse object declared");

                // getting JSON string from URL
                JSONObject json = jParser.getJSONFromUrl(url);
                Log.i("in Main activity", "JSON object declared");

                try {
                    // Getting Array of Contacts
                    tests = json.getJSONArray(TAG_FILE_NAME);
                    Log.i("in Main activity", "JSON array called");

                    // looping through All Contacts
                    for (int i = 0; i < tests.length(); i++) {
                        JSONObject c = tests.getJSONObject(i);

                        // Storing each json item in variable
                        String message = c.getString(TAG_MESSAGE);
                        Log.i("In run", "" + message);
                        // adding each record to database
                        // ContentValues content=new ContentValues();
                        // content.put(TAG_MESSAGE, message);
                        // db.insert(message);
                        Log.i("In run", "" + message);

                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put(TAG_MESSAGE, message);

                        // adding HashList to ArrayList
                        testList.add(map);

                        // Log.i("In SingleMenuItem Activity","inserting values in Questions");
                        ContentValues content = new ContentValues();
                        content.put(TAG_MESSAGE, message);
                        Log.i("In SingleMenuItem Activity",
                                "inserted Ques_no");

                        sdb.insertOrThrow(CurrentAffairs, null, content);
                        // Log.i("In SingleMenuItem Activity","inserted values in Questions");

                    }
                } catch (JSONException e) {
                    Log.i("In Main", "" + e.toString());
                    e.printStackTrace();
                }
            }else{}
        }else{final ArrayList<HashMap<String, String>> testList = new ArrayList<HashMap<String, String>>();

        // Creating JSON Parser instance
        Jsonparse jParser = new Jsonparse();
        Log.i("in Main activity", "Jsonparse object declared");

        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(url);
        Log.i("in Main activity", "JSON object declared");

        try {
            // Getting Array of Contacts
            tests = json.getJSONArray(TAG_FILE_NAME);
            Log.i("in Main activity", "JSON array called");

            // looping through All Contacts
            for (int i = 0; i < tests.length(); i++) {
                JSONObject c = tests.getJSONObject(i);

                // Storing each json item in variable
                String message = c.getString(TAG_MESSAGE);
                Log.i("In run", "" + message);
                // adding each record to database
                // ContentValues content=new ContentValues();
                // content.put(TAG_MESSAGE, message);
                // db.insert(message);
                Log.i("In run", "" + message);

                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();

                // adding each child node to HashMap key => value
                map.put(TAG_MESSAGE, message);

                // adding HashList to ArrayList
                testList.add(map);

                // Log.i("In SingleMenuItem Activity","inserting values in Questions");
                ContentValues content = new ContentValues();
                content.put(TAG_MESSAGE, message);
                Log.i("In SingleMenuItem Activity",
                        "inserted Ques_no");

                sdb.insertOrThrow(CurrentAffairs, null, content);
                // Log.i("In SingleMenuItem Activity","inserted values in Questions");

            }
        } catch (JSONException e) {
            Log.i("In Main", "" + e.toString());
            e.printStackTrace();
        }}


        //getjson();
    }
}

注意:我已经尝试过类似问题的解决方案,但它无效。

我尝试使用广播接收器和alarmManager但它仍然无法正常工作。我想要改变代码,以便它每天只调用一次json函数。

2 个答案:

答案 0 :(得分:0)

最简单的方法是: -

1.从服务器获取数据,解析并存储在数据库中。

2。)24小时后触发查询以删除所有数据库。这可以使用广播接收器和报警管理器来完成。

3.。)每次访问应用程序时,检查天气数据库是否有任何数据。如果是,则显示来自数据库的数据,否则从服务器获取数据。

如果您需要上述各点的详细说明。问我

修改

Cursor cur = db.rawQuery("SELECT COUNT(*) FROM TAB", null);
if (cur != null ) {
cur.moveToFirst();                    
if (cur.getInt (0)> 0) {              
    // table has data . Show data from table 
    // eg. tv.setText(cur.getInt(0))
    }
}

}

此外,为了更新数据库,如果数据库不为空,则使用广播接收器和激活更新查询,否则将创建查询。

答案 1 :(得分:0)

对代码所做的更改:

boolean connected = false;
                ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo[] info = connectivityManager.getAllNetworkInfo();
                    if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED || 
                            connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
                        //we are connected to a network
                        connected = true;
                        //Toast.makeText(Banking_Economics.this, "network connected", Toast.LENGTH_LONG).show();
                        //File file = new File ("CurrentAffairs");
                        Calendar calendar = Calendar.getInstance();
                        //System.out.println("Current time => " + c.getTime());
                        calendar.setTime(new Date());
                        calendar.add(Calendar.DAY_OF_MONTH, +1);
                        long mSec = calendar.getTimeInMillis();
                        Intent it=new Intent(Current_Affairs.this,MyReceiver.class);
                        pendingIntent=PendingIntent.getBroadcast(Current_Affairs.this, 0, it, 0);
                        AlarmManager alarmManager=(AlarmManager)getSystemService(ALARM_SERVICE);
                        alarmManager.set(AlarmManager.RTC, mSec, pendingIntent);    
                        /*if(file.exists()){
                            if(file.lastModified()+mSec>System.currentTimeMillis()){
                                json();
                                //disp();
                            }else{
                            }
                        }else{
                            json();
                            //disp();
                        }*/

                        //disp();
                    }
                    else{
                        connected = false;
                       // Toast.makeText(Banking_Economics.this, "network not connected", Toast.LENGTH_LONG).show();
                       // disp();
                    }

BroadCastReceiver代码:

public class MyReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context arg0, Intent arg1) {
        // TODO Auto-generated method stub
        Current_Affairs ca=new Current_Affairs();
        ca.json();
    }

}

希望这有助于其他人。