Skip to content

Conversation

@kevinmoutier
Copy link

No description provided.

@theGlenn
Copy link
Owner

theGlenn commented Jun 9, 2016

C'est dommage que l'app crash pour le add to cart
Voici une version simplifiée de ton code les try catch peuvent être groupés sous un try global avec un seul catch, ça rend le code plus lisible.

public static ArrayList<Product> Load(Context ctx) {
        ArrayList<Product> list = new ArrayList<>();
        try {
            // Get the File where data are saved
            File file = new File(ctx.getFilesDir() + "/data.txt");
            if (!file.exists()) {

                file.createNewFile();

            }
            FileInputStream fis = null;

            fis = new FileInputStream(file);

            InputStreamReader isr = new InputStreamReader(fis);
            BufferedReader br = new BufferedReader(isr);

            String test;
            int anzahl = 0;

            while ((test = br.readLine()) != null) {
                anzahl++;
            }

            fis.getChannel().position(0);

            String[] array = new String[anzahl];

            String line;
            int i = 0;
            try {
                while ((line = br.readLine()) != null) {
                    array[i] = line;
                    i++;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }


            GsonBuilder gsonBuilder = new GsonBuilder();
            Gson Gson = gsonBuilder.create();
            JsonParser jsonParser = new JsonParser();

            // Get the String Result
            for (String str : array) {
                // Convert it into ArrayList
                JsonElement element = jsonParser.parse(str);

                //Not a JSON Object
                //JsonObject result = element.getAsJsonObject();

                //Good
                JsonArray result = element.getAsJsonArray();

                // TODO: This code is not working
                list = Gson.fromJson(result, new TypeToken<ArrayList<Product>>() {}.getType());
            }


        } catch (IOException e) {
            e.printStackTrace();
        }

        return list;
    }`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants