IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Android Discussion :

asyntask et recycleview


Sujet :

Android

  1. #1
    Membre à l'essai
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Mars 2014
    Messages
    36
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Côte d'Ivoire

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Mars 2014
    Messages : 36
    Points : 17
    Points
    17
    Par défaut asyntask et recycleview
    bonjour voila j'ai un webservice et j essaie de remplir les elements de mon recycleview avec les elements que ramene mon webservie avec la classe card de ma fonction prepare album sauf que mon webservice s'execute apres que ma vu soit creer
    voila mon code :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
     
    package kori.dev.kori.activity;
     
    import android.content.res.Resources;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.graphics.Rect;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.support.design.widget.AppBarLayout;
    import android.support.design.widget.CollapsingToolbarLayout;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.DefaultItemAnimator;
    import android.support.v7.widget.GridLayoutManager;
    import android.support.v7.widget.RecyclerView;
    import android.support.v7.widget.Toolbar;
    import android.util.Log;
    import android.util.TypedValue;
    import android.view.View;
    import android.widget.ImageView;
    import android.widget.TextView;
     
    import com.bumptech.glide.Glide;
     
    import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
    import org.springframework.web.client.RestTemplate;
     
    import java.io.InputStream;
    import java.util.ArrayList;
    import java.util.List;
     
    import kori.dev.kori.R;
    import kori.dev.kori.adapters.CardAdapter;
    import kori.dev.kori.model.Card;
    import kori.dev.kori.model.Carte;
     
    /**
     * Created by Thefractus Bombatus on 13/12/2016.
     */
     
    public class MainCard extends AppCompatActivity {
     
        private RecyclerView recyclerView;
        private CardAdapter adapter;
        private List<Card> cardList;
        public static Carte[] carte;
     
     
     
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main_card);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            TextView sub_title = (TextView) findViewById(R.id.sub_title);
            String title_sub = getIntent().getStringExtra("name_cat") ;
            sub_title.setText(title_sub);
     
     
          //  new DownloadImageTask((ImageView) findViewById(R.id.overflow))
           //         .execute("https://cdn1.iconfinder.com/data/icons/appicns/513/appicns_Chrome.png");
     
            initCollapsingToolbar();
     
            recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
     
            cardList = new ArrayList<>();
            adapter = new CardAdapter(this, cardList);
     
            RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 2);
            recyclerView.setLayoutManager(mLayoutManager);
            recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(10), true));
            recyclerView.setItemAnimator(new DefaultItemAnimator());
            recyclerView.setAdapter(adapter);
     
            prepareAlbums();
     
            try {
                Glide.with(this).load(R.drawable.carte_sport).into((ImageView) findViewById(R.id.backdrop));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
     
        /**
         * Initializing collapsing toolbar
         * Will show and hide the toolbar title on scroll
         */
        private void initCollapsingToolbar() {
            final CollapsingToolbarLayout collapsingToolbar =
                    (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
            collapsingToolbar.setTitle("dride");
     
            AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.appbar);
            appBarLayout.setExpanded(true);
     
            // hiding & showing the title when toolbar expanded & collapsed
            appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
                boolean isShow = false;
                int scrollRange = -1;
     
                @Override
                public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                    if (scrollRange == -1) {
                        scrollRange = appBarLayout.getTotalScrollRange();
                    }
                    if (scrollRange + verticalOffset == 0) {
                        collapsingToolbar.setTitle(getString(R.string.app_name));
                        isShow = true;
                    } else if (isShow) {
                        collapsingToolbar.setTitle(" ");
                        isShow = false;
                    }
                }
            });
        }
     
        /**
         * Adding few albums for testing
         */
        private void prepareAlbums() {
     
     
                new HttpRequestTaskCarte().execute();
     
     
     
     
     
            int[] covers = new int[]{
                    R.drawable.album1,
                    R.drawable.album2,
                    R.drawable.album3,
                    R.drawable.album4,
                    R.drawable.album5,
                    R.drawable.album6,
                    R.drawable.album7,
                    R.drawable.album8,
                    R.drawable.album9,
                    R.drawable.album10,
                    R.drawable.album11};
     
            Card a = new Card(carte[0].getCarte(), carte[0].getVendeur(), covers[0]);
            cardList.add(a);
     
            a = new Card("Xscpae", "technofream", covers[1]);
            cardList.add(a);
     
            a = new Card("Maroon 5", "Bicici", covers[2]);
            cardList.add(a);
     
            a = new Card("Born to Die", "Canal Sat", covers[3]);
            cardList.add(a);
     
            a = new Card("Honeymoon", "Startime", covers[4]);
            cardList.add(a);
     
            a = new Card("I Need a Doctor", "fitnesse", covers[5]);
            cardList.add(a);
     
            a = new Card("Loud", "FNAC", covers[6]);
            cardList.add(a);
     
            a = new Card("Legend", "KIABI", covers[7]);
            cardList.add(a);
     
            a = new Card("Hello", "Cash center", covers[8]);
            cardList.add(a);
     
            a = new Card("Greatest Hits", "THEOPHRACTUS", covers[9]);
            cardList.add(a);
     
            adapter.notifyDataSetChanged();
        }
     
        /**
         * RecyclerView item decoration - give equal margin around grid item
         */
        public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {
     
            private int spanCount;
            private int spacing;
            private boolean includeEdge;
     
            public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
                this.spanCount = spanCount;
                this.spacing = spacing;
                this.includeEdge = includeEdge;
            }
     
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                int position = parent.getChildAdapterPosition(view); // item position
                int column = position % spanCount; // item column
     
                if (includeEdge) {
                    outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
                    outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)
     
                    if (position < spanCount) { // top edge
                        outRect.top = spacing;
                    }
                    outRect.bottom = spacing; // item bottom
                } else {
                    outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
                    outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f /    spanCount) * spacing)
                    if (position >= spanCount) {
                        outRect.top = spacing; // item top
                    }
                }
            }
        }
     
        /**
         * Converting dp to pixel
         */
        private int dpToPx(int dp) {
            Resources r = getResources();
            return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
        }
     
        private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
            ImageView bmImage;
     
            public DownloadImageTask(ImageView bmImage) {
                this.bmImage = bmImage;
            }
     
            protected Bitmap doInBackground(String... urls) {
                String urldisplay = urls[0];
                Bitmap mIcon11 = null;
                try {
                    InputStream in = new java.net.URL(urldisplay).openStream();
                    mIcon11 = BitmapFactory.decodeStream(in);
                } catch (Exception e) {
                    Log.e("Error", e.getMessage());
                    e.printStackTrace();
                }
                return mIcon11;
            }
     
            protected void onPostExecute(Bitmap result) {
                bmImage.setImageBitmap(result);
            }
        }
     
        public static class HttpRequestTaskCarte extends AsyncTask<Void,Void,Carte[]> {
     
            @Override
            protected Carte[] doInBackground(Void... params) {
                try {
                    final String url = "http://ayelive.xyz/website/testRest/RestController.php?carte=shopping";
                    RestTemplate restTemplate = new RestTemplate();
                    restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
                    Carte[] greeting = restTemplate.getForObject(url, Carte[].class);
                    return greeting;
                } catch (Exception e) {
                    Log.e("MainActivity", e.getMessage(), e);
                }
     
                return null;
            }
            @Override
            protected void onPostExecute(Carte[] greeting) {
     
                Carte[] greet =greeting;
     
                carte = greet ;
                // TextView greetingIdText = (TextView) findViewById(R.id.id_value);
                //  TextView greetingContentText = (TextView) findViewById(R.id.content_value);
                //greetingIdText.setText(greeting.getId());
                //greetingContentText.setText(greeting.getlibellet());
                Log.d("carte",greet[0].getLibelle());
                Log.d("carte",greet[1].getCarte());
     
     
            }
     
        }
    }
    need help

  2. #2
    Modérateur
    Avatar de Hizin
    Homme Profil pro
    Développeur mobile
    Inscrit en
    Février 2010
    Messages
    2 180
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : France

    Informations professionnelles :
    Activité : Développeur mobile

    Informations forums :
    Inscription : Février 2010
    Messages : 2 180
    Points : 5 072
    Points
    5 072
    Par défaut
    Je n'ai pas le temps de regarder le code en détail, mais dans cette situation-là, le but est de :
    - afficher un loader, ou une image de fond
    - appeler le WS pour reprendre tes données
    - une fois celui-ci terminé et traité (donc dans le onPostExecute de ton AsyncTask), nourrir ta RecyclerView
    - Afficher a RecyclerView à la place du placeholder signifiant "on a pas encore les données, on les récupères"
    C'est Android, PAS Androïd, ou Androïde didiou !
    Le premier est un OS, le second est la mauvaise orthographe du troisième, un mot français désignant un robot à forme humaine.

    Membre du comité contre la phrase "ça marche PAS" en titre et/ou explication de problème.

    N'oubliez pas de consulter les FAQ Android et les cours et tutoriels Android

  3. #3
    Membre à l'essai
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Mars 2014
    Messages
    36
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Côte d'Ivoire

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Mars 2014
    Messages : 36
    Points : 17
    Points
    17
    Par défaut
    merci j ai essayé il marche

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. OpenGL Moving map et asyntask : problème de performances
    Par UbuntuMan dans le forum Android
    Réponses: 2
    Dernier message: 25/04/2014, 14h05
  2. plusieurs asyntask en meme temps
    Par momedalhouma dans le forum Android
    Réponses: 8
    Dernier message: 22/05/2013, 12h45
  3. appeler onactivityresult() depuis asyntask
    Par momedalhouma dans le forum Android
    Réponses: 4
    Dernier message: 10/05/2013, 15h36
  4. Comment mettre à jour un ListView depuis un Asyntask
    Par Arwa89 dans le forum Composants graphiques
    Réponses: 10
    Dernier message: 24/04/2013, 18h02
  5. Exécuter deux Asyntask a la fois?
    Par anto2b dans le forum Android
    Réponses: 6
    Dernier message: 25/02/2013, 18h39

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo