Revenir à une activité précédente contenant un BaseAdapter

Fermé
Christian95 - Modifié le 7 juin 2017 à 13:53
BunoCS Messages postés 15475 Date d'inscription lundi 11 juillet 2005 Statut Modérateur Dernière intervention 23 avril 2024 - 9 juin 2017 à 11:02
Bonjour à tous,

Je détiens actuellement deux activités effectuant des requêtes HTTP.

La première activité contient une classe CustomList extends BaseAdapter.

Sur la seconde, il y a un bouton précédent me permettant de revenir à la première activité.

En revenant sur la première activité, j'aimerai pouvoir récupérer l'état dans lequel je l'ai laissé. C'est à dire pouvoir retrouver les informations qui eux aussi proviennent d'une requête HTTP. J'aimerai retrouvé la donnée "infos_user" qui est dans la première activité et les données dans le BaseAdapter.

Mon architecture est donc la suivante : Activité 0 (HTTP requête) -> Activité 1 (avec BaseAdapter et HTTP requête) -> Activité 2 (HTTP requête)


Première activité:

public class GetChildrenList extends AppCompatActivity implements View.OnClickListener {
    private ArrayList<Child> childrenImeList = new ArrayList<Child>();

    private Button btn_previous;
    private ListView itemsListView;
    private TextView tv_signin_success;

    int id = 0;
    String infos_user;
    String email;
    String password;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.get_children_list);

        infos_user = (String) getIntent().getSerializableExtra("infos_user");

        Intent intent = new Intent(GetChildrenList.this , GetLearningGoalsList.class);
        intent.putExtra("username", infos_user);

        btn_previous = (Button) findViewById(R.id.btn_previous);

        btn_previous.setOnClickListener(this);

        tv_signin_success = (TextView) findViewById(R.id.tv_signin_success);


        tv_signin_success.setText("Bonjour " + infos_user + "!");

        itemsListView  = (ListView)findViewById(R.id.list_view_children);


        new GetChildrenAsync().execute();
    }


    @Override
    public void onClick(View v) {
        Intent myIntent = new Intent(GetChildrenList.this, MainActivity.class);
        myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(myIntent);
        finish();
        return;
    }

    class GetChildrenAsync extends AsyncTask<String, Void, ArrayList<Child>>  {

        private Dialog loadingDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            loadingDialog = ProgressDialog.show(GetChildrenList.this, "Please wait", "Loading...");
        }

        @Override
        protected ArrayList<Child> doInBackground(String... params) {


            int age = 0;
            email = (String) getIntent().getSerializableExtra("email");
            password = (String) getIntent().getSerializableExtra("password");
            String first_name = null;
            String last_name = null;

            try {

                SendRequest sr = new SendRequest();
                String result = sr.sendHttpRequest("http://" + sr.getIP_ADDRESS() + "/childrenime/list", "GET", true, email, password);

                String jsonResult = "{ \"children\":" + result + "}";

                Log.d("result1", jsonResult);

                //Manage JSON result
                JSONObject jsonObject = new JSONObject(jsonResult);
                JSONArray childrenArray = jsonObject.getJSONArray("children");

                for (int i = 0; i < childrenArray.length(); ++i) {
                    JSONObject child = childrenArray.getJSONObject(i);
                    id = child.getInt("id");
                    first_name = child.getString("first_name");
                    last_name = child.getString("last_name");
                    age = child.getInt("age");

                    String name = first_name + " " + last_name;

                    childrenImeList.add(new Child(id,name,age));
                }

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

            return childrenImeList;

        }

        @Override
        protected void onPostExecute(final ArrayList<Child> childrenListInformation) {
            loadingDialog.dismiss();
            if(childrenListInformation.size() > 0) {
                CustomListChildrenAdapter adapter = new CustomListChildrenAdapter(GetChildrenList.this, childrenListInformation);
                itemsListView.setAdapter(adapter);
            }
            else{
                Toast.makeText(getApplicationContext(), "Impossible de récupérer la liste des enfants", Toast.LENGTH_LONG).show();
            }
        }
    }
}


BaseAdapter:

public class CustomListChildrenAdapter extends BaseAdapter implements View.OnClickListener {
    private Context context;
    private ArrayList<Child> children;
    private Button btnChoose;
    private TextView childrenName;
    private TextView childrenAge;

    public CustomListChildrenAdapter(Context context, ArrayList<Child> children) {
        this.context = context;
        this.children = children;
    }

    @Override
    public int getCount() {
        return children.size(); //returns total item in the list
    }

    @Override
    public Object getItem(int position) {
        return children.get(position); //returns the item at the specified position
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        View view;

        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.layout_list_view_children,null);
            childrenName = (TextView)view.findViewById(R.id.tv_childrenName);
            childrenAge = (TextView) view.findViewById(R.id.tv_childrenAge);
            btnChoose = (Button) view.findViewById(R.id.btn_choose);
            btnChoose.setOnClickListener(this);

        } else {
            view = convertView;
        }

        btnChoose.setTag(position);

        Child currentItem = (Child) getItem(position);
        childrenName.setText(currentItem.getChildName());
        childrenAge.setText(currentItem.getChildAge() + "");

        return view;
    }

    @Override
    public void onClick(View v) {
        Integer position = (Integer) v.getTag();
        Child item = (Child) getItem(position);
        String email = (String) ((Activity) context).getIntent().getSerializableExtra("email");
        String password = (String) ((Activity) context).getIntent().getSerializableExtra("password");

        Intent intent = new Intent(context, GetLearningGoalsList.class);
        intent.putExtra("idChild",item.getId());
        intent.putExtra("email",email);
        intent.putExtra("password",password);

        context.startActivity(intent);

    }
}


Deuxième activité:

public class GetLearningGoalsList extends AppCompatActivity implements View.OnClickListener {
    private ArrayList<LearningGoal> childrenLearningList = new ArrayList<LearningGoal>();

    private Button btn_previous;
    private ListView itemsListView;

    String email;
    String password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.get_learning_goals_list);

        btn_previous = (Button) findViewById(R.id.btn_previous);

        btn_previous.setOnClickListener(this);

        itemsListView  = (ListView)findViewById(R.id.list_view_learning_goals);


        new GetLearningGoalsAsync().execute();
    }

    @Override
    public void onClick(View v) {
        Intent myIntent = new Intent(GetLearningGoalsList.this, GetChildrenList.class);
        myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(myIntent);
        return;
    }

    class GetLearningGoalsAsync extends AsyncTask<String, Void, ArrayList<LearningGoal>>  {

        private Dialog loadingDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            loadingDialog = ProgressDialog.show(GetLearningGoalsList.this, "Please wait", "Loading...");
        }

        @Override
        protected ArrayList<LearningGoal> doInBackground(String... params) {

            int id = 0;
            email = (String) getIntent().getSerializableExtra("email");
            password = (String) getIntent().getSerializableExtra("password");
            int idChild = (int) getIntent().getSerializableExtra("idChild");
            String name = null;
            String start_date = null;
            String end_date = null;

            try {

                List<BasicNameValuePair> parameters = new LinkedList<BasicNameValuePair>();
                parameters.add(new BasicNameValuePair("idchild", Integer.toString(idChild)));

                SendRequest sr = new SendRequest();
                String result = sr.sendHttpRequest("http://" + sr.getIP_ADDRESS() + "/learningchild/list"+ "?"+ URLEncodedUtils.format(parameters, "utf-8"), "POST", true, email, password);

                String jsonResult = "{ \"learningGoals\":" + result + "}";

                Log.d("result1", jsonResult);


                //Manage JSON result
                JSONObject jsonObject = new JSONObject(jsonResult);
                JSONArray learningGoalsArray = jsonObject.getJSONArray("learningGoals");

                for (int i = 0; i < learningGoalsArray.length(); ++i) {
                    JSONObject learningGoal = learningGoalsArray.getJSONObject(i);
                    id = learningGoal.getInt("id");
                    name = learningGoal.getString("name");
                    start_date = learningGoal.getString("start_date");
                    end_date = learningGoal.getString("end_date");


                    childrenLearningList.add(new LearningGoal(id,name,start_date,end_date));
                }

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

            return childrenLearningList;

        }

        @Override
        protected void onPostExecute(final ArrayList<LearningGoal> learningListInformation) {
            loadingDialog.dismiss();
            if(learningListInformation.size() > 0) {
                CustomListLearningGoalAdapter adapter = new CustomListLearningGoalAdapter(GetLearningGoalsList.this, learningListInformation);
                itemsListView.setAdapter(adapter);
            }
            else{
                Toast.makeText(getApplicationContext(), "Impossible de récupérer la liste des scénarios de cet enfant", Toast.LENGTH_LONG).show();
            }
        }
    }
}


Merci à vous.
A voir également:

3 réponses

BunoCS Messages postés 15475 Date d'inscription lundi 11 juillet 2005 Statut Modérateur Dernière intervention 23 avril 2024 3 895
7 juin 2017 à 13:56
Re,
Si tu veux pouvoir gérer le bouton "Précédent", il ne faut pas appeler la méthode
finish()
dans la 1ère Activity
0
Bonjour Buno,

A aucun moment je n'appelle
finish() 
dans la 1ère activité ni dans le BaseAdapter sauf sur le
onClick()
mais à l'heure actuelle il n'est pas utilisé.
0
BunoCS Messages postés 15475 Date d'inscription lundi 11 juillet 2005 Statut Modérateur Dernière intervention 23 avril 2024 3 895
8 juin 2017 à 10:15
Désolé, j'ai du mal à comprendre.
En revenant sur la première activité, j'aimerai pouvoir récupérer l'état dans lequel je l'ai laissé.
Ce n'est pas le cas? Ton écran change?
Généralement, pour des listes "simples", on traite la callback de click dans l'Activity, c'est-à-dire que l'Activity étend l'interface OnClickListener et peut stocker des infos récupérer dans la callback onClick()
0
Non à l'heure actuelle quand je reviens sur ma première activité, je perds toute mes informations.

Par exemple: Pour la donnée "infos_user" sur ma première activité j'ai Bonjour null ! :

 infos_user = (String) getIntent().getSerializableExtra("infos_user");
tv_signin_success.setText("Bonjour " + infos_user + "!");


De même pour la CustomList dans mon BaseAdapter, elle n'apparait pas.
0
BunoCS Messages postés 15475 Date d'inscription lundi 11 juillet 2005 Statut Modérateur Dernière intervention 23 avril 2024 3 895
Modifié le 9 juin 2017 à 11:07
Ok, j'ai compris! ;)

Dans ta 2e Activity, tu as ça:
    @Override
    public void onClick(View v) {
        Intent myIntent = new Intent(GetLearningGoalsList.this, GetChildrenList.class);
        myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(myIntent);
        return;
    } 

Tu relances donc une nouvelle Activity et tu ne reviens pas sur la précédente. Et vu que tu ne passes pas de paramètres à l'Intent, tu as un écran vide.

Je t'ai indiqué ici comment revenir à l'écran précédent. Or, je ne le vois pas dans ton code...

2 solutions donc.

Pour revenir à l'écran précédent, cela suffit:
    @Override
    public void onClick(View v) {
        finish();
    } 


Pour passer des paramètres à l'écran précédent, il faut passer par un Intent:
    @Override
    public void onClick(View v) {
      Intent output = new Intent();
      output.putExtra(...);
      output.putExtra(...);
      setResult(RESULT_OK, output);
      finish();
    } 

Mais ceci implique 2 choses:
- lancer la 2nde Activity à l'aide de
startActivityForResult()

- récupérer le résultat de retour en surchargeant
onActivityResult()

Plus d'infos ici: https://developer.android.com/training/basics/intents/result.html

Note: ton problème n'a effectivement rien à voir avec ton Adapter.

@+ 
Buno, Modo CS-CCM 
L'urgent est fait, l'impossible est en cours. Pour les miracles, prévoir un délai... 
The urgent is done, the impossible is underway. For miracles, provide for a delay...
0