0

我有一个简单的 android 应用程序,它使用 jSoup 从 URL 获取数据。我有一个肮脏的解决方案,TOAST 给我一个在线或离线警告。我希望能够将用户上次查询新信息时的数据存储在用户离线的情况下。我不知道从哪里开始?我阅读了有关数据缓存、SQLite 等的信息……

存储来自 jsoup 解析的数据的最佳方法是什么,以便在用户离线时可以检索它?

到目前为止,这是我的代码:

public class SlockActivity extends SherlockActivity {
    private TextView textView;
    private String url = "http://www.backcountryskiers.com/sac/sac-full.html";
    private String noDangerUrl = "http://www.sierraavalanchecenter.org/sites/default/files/images/danger_icons_and_bars/0_nodangerrate.png";
    private ImageView image;
    private TextView tvWX;

    // GLOBAL RESOURCES
    private static SlockActivity instance = null;

    // private ProgressDialog dialog = new ProgressDialog(SlockActivity.this);

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        menu.add("Emergency")
                .setIcon(R.drawable.emergencyicon)
                .setShowAsAction(
                        MenuItem.SHOW_AS_ACTION_IF_ROOM
                                | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
        menu.add("Weather")
                .setIcon(R.drawable.wx_icon)
                .setShowAsAction(
                        MenuItem.SHOW_AS_ACTION_IF_ROOM
                                | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
        menu.add("Refresh")
                .setIcon(R.drawable.ic_refresh)
                .setShowAsAction(
                        MenuItem.SHOW_AS_ACTION_IF_ROOM
                                | MenuItem.SHOW_AS_ACTION_WITH_TEXT);

        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView) findViewById(R.id.todaysReport);
        image = (ImageView) findViewById(R.id.dangerRose);
        tvWX = (TextView) findViewById(R.id.todaysWX);

        boolean check = isOnline();
        if (check == true) {
            Toast.makeText(this, "Internet is Connected", Toast.LENGTH_LONG)
                    .show();
            fetcher task = new fetcher();
            task.execute();
        }

        else {

            Toast.makeText(this, "Failed to connect to internet.",
                    Toast.LENGTH_LONG).show();
            textView.setText("No Network Connection and attempt to get Cached Data did not work. ");
        }

    }

    public static Bitmap getBitmapFromURL(String src) {
        try {
            Log.e("src", src);
            URL url = new URL(src);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            Log.e("Bitmap", "returned");
            return myBitmap;
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("Exception", e.getMessage());
            return null;
        }

    }

    class fetcher extends AsyncTask<String, Void, String> {
        // HERE DECLARE THE VARIABLES YOU USE FOR PARSING
        private ProgressDialog dialog = new ProgressDialog(SlockActivity.this);
        private Document doc = null;
        private Elements content = null;
        private Document parse = null;
        private String results = null;
        private Element dangerRatingImg = null;
        private String dangerRatingSrc = null;
        private Bitmap bimage;

        @Override
        protected String doInBackground(String... params) {
            try {
                doc = Jsoup.connect(url).get();
                Log.e("Jsoup", "...is working...");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Log.e("Exception", e.getMessage());
            }

            content = doc.select("#content");
            parse = Jsoup.parse(doc.html());
            results = doc.select("#content").outerHtml();

            // find rating image...
            dangerRatingImg = doc.select("img").first();
            dangerRatingSrc = dangerRatingImg.absUrl("src");
            // Get the rating image
            bimage = getBitmapFromURL(dangerRatingSrc);

            return results;
        }

        @Override
        protected void onPostExecute(String result) {
            dialog.dismiss();
            // smooth out the long scrolling...
            textView.setMovementMethod(ScrollingMovementMethod.getInstance());
            // Set this after the load so the background is the picture without
            // the textviews background in
            textView.setBackgroundResource(R.drawable.tvbg);
            // Set the rating image
            //
            // DO THE IMAGE REPLACE ON URL COMPARE THING HERE>>>>>>>
            if (dangerRatingSrc.equals(noDangerUrl)) {
                image.setImageDrawable(getResources().getDrawable(
                        R.drawable.nodanger));
            }
            //
            // image.setImageBitmap(bimage);
            image.setPadding(0, 10, 0, 30);
            // image.setScaleType(ScaleType.FIT_XY);

            // return the summary
            results = parse.select("#reportSummary").outerHtml();
            // String reportDate = parse.select("#reportDate").outerHtml();
            textView.setText(Html.fromHtml(results));
            // textView.append(Html.fromHtml("<a href='#'><em>Read Full Report &raquo;</em></a>"));
            textView.setPadding(30, 20, 20, 10);
            // ditch the dialog, it's all loaded.
            tvWX.setText(Html.fromHtml("Today's High: <b>26F</b>"));
        }

        @Override
        protected void onPreExecute() {
            // before we get the async results show this
            dialog.setMessage("Loading Latest Update from the Sierra Avalanche Center...");
            dialog.show();
        }

    }

    // check network connectivity
    public boolean isOnline() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            Log.i("Network", "IS CONNECTED");
            return true;
        }
        Log.i("Network", "IS NOT-CONNECTED");
        return false;
    }

    public void onClickFullReport(View v) {
        Intent intentFullReport = new Intent(getBaseContext(),
                FullReportActivity.class);
        intentFullReport.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        startActivity(intentFullReport);
    }
}
4

1 回答 1

2

我建议按照文档中的描述将字符串写入您的应用程序只能读取的文件:http: //developer.android.com/guide/topics/data/data-storage.html#filesInternal

将“数据”写入文件“filename.txt”:

String FILENAME = "filename.txt";
String string = "data";

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();

再读一遍:

FileInputStream fis = context.openFileInput(FILENAME);
StringBuffer fileContent = new StringBuffer("");

byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) != -1) {
    fileContent.append(new String(buffer));
}
String string = fileContent.toString();
于 2012-11-15T07:52:22.223 回答