Получить массив вопросов формата json и поместить их в массив в андроид студии - PullRequest
0 голосов
/ 25 октября 2018

Целью здесь является получение данных формата JSON из API, преобразование данных в массив в Android Studio.Затем отобразить случайный вопрос в текстовом представлении, и вопрос не повторится.Вопрос меняется каждый раз, когда нажимается кнопка.Что-то не так с логикой того, как я использую свой массив / парсинг данных в массив.Я не уверен, как поступить.Любая помощь приветствуется

Мой формат JSON

{
    "error": false,
    "message": "Successfully retrieved",
    "questions": [
        {
            "question": "Tell us about yourself?"
        },
        {
            "question": "Tell us about yourself2?"
        },
        {
            "question": "Tell us about yourself3?"
        },
        {
            "question": "Tell us about yourself4?"
        },
        {
            "question": "Tell us about yourself5?"
        }
    ]
}

Мой код (пока упрощенный для этой функции)

    public class MainActivity extends AppCompatActivity {
    // create arraylist to store question
    List<String> questionList = new ArrayList<>();
    // use max to decide the number of question
    // use i to find out the number of questions
    int i = 10;
    int min = 0;
    int max = i;
    int[] usedInt = new int[max];
    //create another array to put all the used integer inside for 0 repeition of question
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        final TextView textViewQuestions = (TextView) findViewById(R.id.questionView);

        usedInt = new int[i];
        Random r = new Random();
        int i1 = r.nextInt(max - min + 1) + min;
        //generate random number, set textview the question, set int to usedint array
        textViewQuestions.setText(questionList.get(i1));
        usedInt[0] = i1;

        //set first question

        findViewById(R.id.changeQuestion).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //Log.d(TAG,questionList[updateQuestions(usedInt)]);
                //final int[] usedIntTemp = usedInt;

                getQuestions();
                int n = updateQuestions(usedInt);
                textViewQuestions.setText(questionList.get(n));
                //finish();
            }
        });
    }

    }

public int updateQuestions(int usedInteger[]) {
        int min = 0;
        int max = i;
        Random r = new Random();
        int i2 = r.nextInt(max - min + 1) + min;
        int uInteger[] = usedInteger;
        int l = 0;

        while (l != max) {
            if (i2 == usedInteger[l]) {
                l++;
                if (l == max) {
                    Toast.makeText(getApplicationContext(), "No other questions available", Toast.LENGTH_LONG).show();

                }
            } else {
                usedInteger[usedInteger.length + 1] = i2;
                return i2;

            }


        }
        return i2;


    }
private void getQuestions()
    {

    class GetQuestions extends AsyncTask<Void, Void, String> {

        //private ProgressBar progressBar;

        @Override
        protected String doInBackground(Void... voids) {
            //creating request handler object
            RequestHandler requestHandler = new RequestHandler();

            //creating request parameters
            HashMap<String, String> params = new HashMap<>();
            params.put("role_id", "1");

            //returing the response
            return requestHandler.sendPostRequest(URLs.URL_QUESTIONS, params);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            //displaying the progress bar while user registers on the server
            //progressBar = (ProgressBar) findViewById(R.id.progressBar);
            //progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            //hiding the progressbar after completion
            //progressBar.setVisibility(View.GONE);
            boolean Error1 = false;
            try {
                //converting response to json object
                JSONObject obj = new JSONObject(s);


                //HashMap<String, String> questionJson = new HashMap<>();


                // success = obj.getBoolean("error");
                if (!obj.getBoolean("error")) {

                    //Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();

                    //getting the questions from the response
                    JSONArray questionsJson = obj.getJSONArray("questions");

                    //creating a new questions object

                    for (i = 0; i < questionsJson.length(); i++) {
                        JSONObject object = questionsJson.getJSONObject(i);
                        questionList.add(object.getString("question"));
                        Log.d(TAG,"objcheck");
                        Log.d(TAG,object.getString("question"));

                        //q = c.getString("question");
                        //questionJson.put("question", q);
                        //questionList.add(questionJson);
                    }

                    finish();
                    //startActivity(new Intent(getApplicationContext(), MainActivity.class));


                } else {
                    Toast.makeText(getApplicationContext(), "Some error occurred", Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }


    }
        GetQuestions gq = new GetQuestions();
        gq.execute();

}

Ответы [ 2 ]

0 голосов
/ 26 октября 2018

Я попробовал это, с

            getQuestions();
            String n = String.valueOf(next());
            textViewQuestions.setText(n);

Я также заполнил массив следующим образом:

for (i = 0; i < questionsJson.length(); i++) {
                        JSONObject object = questionsJson.getJSONObject(i);
                        array[i] = object.getString("question");
                        questionList.add(object.getString("question"));
                        Log.d(TAG,object.getString("question"));


                    }

Однако вопросы повторяются, но будут показывать только определенное количество вопросов.:( Как заставить вопросы не повторяться?

0 голосов
/ 25 октября 2018
    Object[] array = new Object[10];    // say 10 objects
int remain = array.length;
Random rnd = new Random();

public Object next () {
    if (remain == 0) {
        return null;
    } else {
        int i = rnd.nextInt(remain--);
        Object tmp = array[i];
        array[i] = array[remain];
        array[remain] = tmp;
        return tmp;
    }
}

Будет создан следующий случайный вопрос

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...