Pass a json object from one activity to another

1

I have the following problem I am trying to bring a list of items that I get from a json , from a activity through a controlador q you request it to a class that has the json . Inside the code that I am attaching what I am looking for is to pass to my MainActivity the list of specialties through a method.

MainActivity

public class MainActivity extends Activity {

    ArrayList<Especialidad> ep;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Especialidad_connect e = new Especialidad_connect();
        e.execute("http://192.168.1.55:8080/especialidad/");
        ep = new ArrayList<>();
        final Consultas_Especialidad ce = new Consultas_Especialidad(MainActivity.this);
        ep = ce.getAll();
    }
}

Consultation_speciality

public class Consultas_Especialidad {

     Context context;
     ArrayList<Especialidad> espList, lista;

    public Consultas_Especialidad(Context context) {
        this.context = context;
    }

public void setLista(ArrayList<Especialidad> e){
    espList = new ArrayList<>();
    espList = e;
}

public ArrayList<Especialidad> getAll(){
    lista = new ArrayList<>();
    lista = espList;
    return lista;
    }

}

Specialty_connect

public class Especialidad_connect extends AsyncTask<String, Void, String> {


    public static Especialidad[]  especialidad_arreglo;
    public ArrayList<Especialidad> listaEspecialidades;
    Especialidad especialidad;

        @Override
        public String doInBackground(String... urls) {

            return GET(urls[0]);
        }

        // onPostExecute displays the results of the AsyncTask.
        @Override
        public void onPostExecute(String r) {
            listaEspecialidades = new ArrayList<>();
            especialidad = new Especialidad();
            Gson gson = new Gson();
            especialidad_arreglo = gson.fromJson(r, Especialidad[].class);
            int t = especialidad_arreglo.length;
            for (int i=0; i < t; i++){
              especialidad.setId(especialidad_arreglo[i].getId());
              especialidad.setNombre(especialidad_arreglo[i].getNombre());
                listaEspecialidades.add(especialidad);
            }
            Consultas_Especialidad ce = new Consultas_Especialidad(null);
            ce.setLista(listaEspecialidades);
        }

    public static String GET(String url){
        InputStream inputStream = null;
        String result = "";
        try {
            // create HttpClient
            HttpClient httpclient = new DefaultHttpClient();
            // make GET request to the given URL
            HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
            // receive response as inputStream
            inputStream = httpResponse.getEntity().getContent();
            // convert inputstream to string
            if(inputStream != null)
                result = convertInputStreamToString(inputStream);
            else
                result = "Did not work!";
        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }
        return result;
    }
    public static String convertInputStreamToString(InputStream inputStream) throws IOException{
        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while((line = bufferedReader.readLine()) != null)
            result += line;
        inputStream.close();
        return result;
    }
}
    
asked by Germanccho 31.01.2018 в 00:39
source

2 answers

1

For what you answered in a comment, you are looking to implement a solution more focused on mvp. If that is the case, I tell you that you need a few things. I'll leave you an answer so you do not have to modify your code so much and it's slightly more focused on mvp, but the structure is still complete.

interface MainActivityContract{
    interface View{
        void mostrarEspecialidades(ArrayList<Especialidad> especialidades);
    }
}

public class MainActivity extends Activity implements MainActivityContract.View {

    private Especialidad_connect e;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        e = new Especialidad_connect(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        e.execute("http://192.168.1.55:8080/especialidad/");
    }

    @Override
    void mostrarEspecialidades(ArrayList<Especialidad> especialidades){
        //todo, haz lo que tengas que hacer para mostrar tus especialidades
    }

}


public class Especialidad_connect extends AsyncTask<String, Void, String>{
    private MainActivityContract.View mView;
    .............

    public Especialidad_connect(MainActivityContract.View view){
        mView = view;
    }

    @Override
    public void onPostExecute(String r) {
        listaEspecialidades = new ArrayList<>();
        //etc etc
        //estas ultimas 2 lineas estan de sobra, lo demas esta bien
        //Consultas_Especialidad ce = new Consultas_Especialidad(null);
        //ce.setLista(listaEspecialidades);
        mView.mostrarEspecialidades(listaEspecialidades);

The problem is that when you do the getAll, it is not that it has not been executed (maybe it is already executed, who knows), but that you inside the doinbackground, you make an instance of query_speciality, in these lines

Consultas_Especialidad ce = new Consultas_Especialidad(null);
ce.setLista(listaEspecialidades);

and then in the activity you make another instance of specialty query. Unless you handle it as a singleton, you're never going to get anything. So, if you want to use something more focused on MVP, keep in mind that the layer of the view, should not handle any data (in your case you have declared ArrayList<Especialidad> ep; that I think should go on the presenter's layer.

My code does not stop having errors / deficiencies because it would imply a bit more change in several places, like first a presenter, and that presenter would be in charge of sending the call to run the asyctask, so I can recommend this reading where they use mvp and async task

link

    
answered by 01.02.2018 в 00:04
0
  

What I'm looking for is to pass the list of specialties to my MainActivity   through a method.

you can actually get the data directly from the execution of your AsyncTask in the class MainActivity , one option is to implement an interface that obtains the data when the AsyncTask execution is finished:

How to get the return value of the onPostExecute method of my AsyncTask in my Activity?

You implement the interface AsyncResponse in your AsyncTask and in the method processFinish() you would get the .json or the result of your AsyncTask in your MainActivity

public class MainActivity extends Activity  implements AsyncResponse {

    ArrayList<Especialidad> ep;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Especialidad_connect e = new Especialidad_connect();
        e.execute("http://192.168.1.55:8080/especialidad/");
        ep = new ArrayList<>();
        final Consultas_Especialidad ce = new Consultas_Especialidad(MainActivity.this);
        ep = ce.getAll();
    }


      ...
      ...
    @Override
    public void processFinish(String resultado){

        //Aquí obtienes el resultado del AsyncTask.
    }


}
    
answered by 31.01.2018 в 01:21