简体   繁体   中英

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. 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. I avoided to use SQL since it will increase my app size.Kindly Help! Thanks in Advance!

You can use SharedPreferences for storing your question and Options. Just save the question and answer in a JSON format. While retriving you can use GSON for converting that JSON format into your Model class. 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. So you can retrive it easly

Then you need to fetch the downloaded file from your sdcard using the below method

//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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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