简体   繁体   English

如何在android中检索下载的数据以供离线访问?

[英]How to retrieve the downloaded data for the offline access in android?

I have made an app and now I want to add feature of Multiple Choice Questions(near abt 2000)which will be available for offline access.我已经制作了一个应用程序,现在我想添加多项选择题(接近 2000 年)的功能,该功能可用于离线访问。 What I have thought till now is to upload the text file to Google's drive and get the downloading link,Once the user downloads that text file it will be saved in Internal Storage and then fetch the required data like Questions,Options,etc.到目前为止,我一直认为是将文本文件上传到 Google 的驱动器并获取下载链接,一旦用户下载该文本文件,它将被保存在内部存储中,然后获取所需的数据,如问题、选项等。 I avoided to use SQL since it will increase my app size.Kindly Help!我避免使用 SQL,因为它会增加我的应用程序大小。请帮助! Thanks in Advance!提前致谢!

You can use SharedPreferences for storing your question and Options.您可以使用SharedPreferences来存储您的问题和选项。 Just save the question and answer in a JSON format.只需将问题和答案保存为JSON格式即可。 While retriving you can use GSON for converting that JSON format into your Model class.在检索时,您可以使用GSON将该JSON格式转换为您的模型类。 This will help you in better handling of the data.这将帮助您更好地处理数据。

Like this you can use :像这样你可以使用:

private SharedPreferences sharedPreference;
 sharedPreference=context.getApplicationContext().getSharedPreferences(FILENAME, Context.MODE_PRIVATE);

public void saveQuestionOptionResponse(String response) {

        sharedPreference.edit().putString("Question", response);
        sharedPreference.edit().commit();
    }

public QuestionOptionModel getQuestionOption() {
        Gson gson = new Gson();
        String json = sharedPreference.getString("Question", "");
        QuestionOptionModel model = gson.fromJson(json, QuestionOptionModel.class);
        return response;
    }

If you want to get the questions and options format, you should use to save the questions and options in a JSON format, put the each question and options as JSONOBJECT in a JSONARRAY.如果你想获取问题和选项格式,你应该使用JSON格式保存问题和选项,将每个问题和选项作为 JSONOBJECT 放在 JSONARRAY 中。 So you can retrive it easly所以你可以很容易地检索它

Then you need to fetch the downloaded file from your sdcard using the below method然后您需要使用以下方法从您的 sdcard 中获取下载的文件

//Find the directory for the SD Card using the API
//*Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();

//Get the text file
File file = new File(sdcard,"file.txt");

//Read text from file
StringBuilder text = new StringBuilder();

try {
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line;

    while ((line = br.readLine()) != null) {
        text.append(line);
        text.append('\n');
    }
    br.close();
}
catch (IOException e) {
    //You'll need to add proper error handling here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM