lundi 6 juillet 2015

caching json data after specific time period in android

I am having trouble in displaying json data. I want to fetch data and save it in database and then data to be updated every 24 hours. But in my code everytime the webservice is being accessed for displaying data. All I want is the database to be updated after 24 hours and rest of the time values to be displayed from database.

Code:

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://ift.tt/1RfMvt5";

// 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();
}

}

P.S. I have tried the solutions from similar questions but its not working. Please help me. Thanks in advance

Aucun commentaire:

Enregistrer un commentaire