how to put a JSON in a Spinner?

0

I bring my json from a php and I pass it as string to my activity class via onPostExecute from AsyncTask :

public String doInBackground(String... params) {

        String type = params[0];

  String registro_url = "http://10.0.2.2/spinner2.php";
            String json = "";
            String result = "";
            try {

                URL url = new URL(registro_url);
                HttpURLConnection http = (HttpURLConnection)url.openConnection();
                http.setRequestMethod("POST");

                http.setDoInput(true);
                InputStream IS =http.getInputStream();
                BufferedReader BR = new BufferedReader(new InputStreamReader(IS,"iso-8859-1"));
                String Line;
                while((Line=BR.readLine())!=null){

                    json +=Line;

                }
                BR.close();
                IS.close();
                http.disconnect();
                result=json.toString();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return result; }
        return null;    }

That gives me back this:

{"Preguntas":[{"Pregunta":"Tangananica o Tanganana?"},{"Pregunta":"Que le pasa a Lupita?"},{"Pregunta":"que sera lo que quiere el negro?"}]}

Then I have this in my class where the spinner is

public class Seleccionpregunta extends AppCompatActivity {

    static Spinner sp;
    static TextView tv;
    ArrayList<String> outputDataList  = new ArrayList<String>();

    Context ctx;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_seleccionpregunta);
        sp = (Spinner) findViewById(R.id.questionSpinner);
        tv = (TextView) findViewById(R.id.textView3);
        MyTask BW = new MyTask(this);
        String type = "spinnerq";
        try {
            String taskResultx = new MyTask(this).execute(type).get();
            tv.setText(taskResultx);

        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
}}

I need to put that into a JSON but I can not find anything.

    
asked by Sodro 17.12.2017 в 22:48
source

1 answer

2

First define a file called OnPreguntasResponse which will be the one that will receive the converted data in JSONObject to be able to access the elements of the json:

public interface OnPreguntasResponse
{
  void onResponse(JSONObject response);
}

Modify your MyTask class so that the constructor receives in addition to the context, the interface:

private OnPreguntasResponse mResponseCallback; 
public MyTask(Context context, OnPreguntasResponse responseCallback)
{
  //...

  mResponseCallback = responseCallback;
}

Now, write about the method onPostExecuted of your MyTask class that is executed when doInBackground method finishes executing. In this method you execute the callback and we will send you the instance of the JSONObject method:

@Override
public void onPostExecuted(string jsonResponse)
{
   mResponseCallback.response(new JSONObject(jsonResponse));
}

So now when you run MyTask, in the constructor you send the instance of the callback in this way:

new MyTask(this, new OnRespuestasResponse(){
  public void response(JSONObject response)
  {
     //...
  }
});

Now, within the response method you have to access the elements of the array. For that you have to access the property Preguntas that returns a JSONArray , and then for each question, get the property Pregunta . Then with an array of string ( string[] ) we assign each question to the array then use the ArrayAdapter to fill the Spinner :

new MyTask(this, new OnRespuestasResponse(){

  public void response(JSONObject response)
  {
    try{

         JSONArray preguntasJA = response.getJSONArray("Preguntas");

         String[] preguntas = new String[preguntasJA.length()];

         for(int i = 0; i < preguntasJA.length(); i++)
         {
            preguntas[i] = preguntas.getJSONObject(i).getString("Pregunta");
         }
         ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, preguntas);
         sp.setAdapter(adapter);
     }catch(Exception e)
     {
        e.printStackTrace();
     }

  }
});
    
answered by 17.12.2017 / 23:24
source