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 :

Effet CoverFlow avec des images provenant d'une BD MySQL


Sujet :

Android

  1. #1
    Membre à l'essai
    Homme Profil pro
    Étudiant
    Inscrit en
    Février 2014
    Messages
    27
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Sénégal

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Matériel informatique

    Informations forums :
    Inscription : Février 2014
    Messages : 27
    Points : 16
    Points
    16
    Par défaut Effet CoverFlow avec des images provenant d'une BD MySQL
    Bonjour All,

    J'apprend a programmer en android et la j'essai de faire du CoverFlow avec des image provenant de ma BD mysql.
    J'ai suivi pas mal de tuto et j'ai reussi a le faire avec des image se trouvant dans mon drawable mai je parviens pas a l'adapter pour mes image provenant de ma BD que je stock dans un Arraylist de String.
    J'ai besoin d'aide.

    CoverFlow.java
    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
     
    @SuppressWarnings("deprecation")
    public class CoverFlow extends Gallery {
     
        private Camera mCamera = new Camera();
        private int mMaxRotationAngle = 60;
        private int mMaxZoom = -120;
        private int mCoveflowCenter;
        public CoverFlow(Context context) {
            super(context);
            this.setStaticTransformationsEnabled(true);
        }
        public CoverFlow(Context context, AttributeSet attrs) {
            super(context, attrs);
            this.setStaticTransformationsEnabled(true);
        }
        public CoverFlow(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            this.setStaticTransformationsEnabled(true);
        }
     
        public int getMaxRotationAngle() {
            return mMaxRotationAngle;
        }
        public void setMaxRotationAngle(int maxRotationAngle) {
            mMaxRotationAngle = maxRotationAngle;
        }
        public int getMaxZoom() {
            return mMaxZoom;
        }
        public void setMaxZoom(int maxZoom) {
            mMaxZoom = maxZoom;
        }
     
        private int getCenterOfCoverflow() {
            return (getWidth() - getPaddingLeft() - getPaddingRight()) / 2 + getPaddingLeft();
        }
        private static int getCenterOfView(View view) {
            return view.getLeft() + view.getWidth() / 2;
        }
     
        protected boolean getChildStaticTransformation(View child, Transformation t) {
            final int childCenter = getCenterOfView(child);
            final int childWidth = child.getWidth() ;
            int rotationAngle = 0;
            t.clear();
            t.setTransformationType(Transformation.TYPE_MATRIX);
            if (childCenter == mCoveflowCenter) {
                transformImageBitmap((ImageView) child, t, 0);
            } else {
                rotationAngle = (int) (((float) (mCoveflowCenter - childCenter)/ childWidth) *  mMaxRotationAngle);
                if (Math.abs(rotationAngle) > mMaxRotationAngle) {
                    rotationAngle = (rotationAngle < 0) ? -mMaxRotationAngle : mMaxRotationAngle;
                }
                transformImageBitmap((ImageView) child, t, rotationAngle);
            }
            return true;
        }
     
        protected void onSizeChanged(int w, int h, int oldw, int oldh) {
            mCoveflowCenter = getCenterOfCoverflow();
            super.onSizeChanged(w, h, oldw, oldh);
        }
     
        private void transformImageBitmap(ImageView child, Transformation t, int rotationAngle) {
     
            mCamera.save();
            final Matrix imageMatrix = t.getMatrix();;
            final int imageHeight = child.getLayoutParams().height;;
            final int imageWidth = child.getLayoutParams().width;
            final int rotation = Math.abs(rotationAngle);
            mCamera.translate(0.0f, 0.0f, 100.0f);
            if ( rotation < mMaxRotationAngle ) {
                float zoomAmount = (float) (mMaxZoom +  (rotation * 1.5));
                mCamera.translate(0.0f, 0.0f, zoomAmount);
            }
            mCamera.rotateY(rotationAngle);
            mCamera.getMatrix(imageMatrix);
            imageMatrix.preTranslate(-(imageWidth/2), -(imageHeight/2));
            imageMatrix.postTranslate((imageWidth/2), (imageHeight/2));
            mCamera.restore();
        }
    }
    Galerie.java
    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
     
    public class Galerie extends Fragment {
     
         ArrayList<String> maListDonnee;
         private ImageView viewer;
         String donnee = null;
         private ArrayList<String> mImageIds;
         DownloadImage dmg;
         CoverFlow coverFlow;
         ImageAdapter coverImageAdapter;
     
         @SuppressWarnings("deprecation")
    	 @Override
    	 public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
     
             View g = inflater.inflate(R.layout.image_frag, container, false);
             coverFlow = new CoverFlow(getActivity());
             coverFlow.setAdapter(new ImageAdapter(getActivity()));
             coverImageAdapter = new ImageAdapter(getActivity());
             coverFlow.setAdapter(coverImageAdapter);
             coverFlow.setSpacing(-25);
             coverFlow.setSelection(4, true);
             coverFlow.setAnimationDuration(1000);
             getActivity().setContentView(coverFlow);
    	 return g;
         }
     
         @Override
         public void onStart(){
            super.onStart();
            maListDonnee = new ArrayList<String>();
            mImageIds = new ArrayList<String>();
            Intent i = this.getActivity().getIntent();
            donnee = i.getStringExtra(Accueil.CODE);
            try {
                mImageIds = new DownloadImage().execute().get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
     
          public class ImageAdapter extends BaseAdapter {
            int mGalleryItemBackground;
            private Context mContext;
            private ImageView[] mImages;
            public ImageAdapter(Context c) {
                mContext = c;
                mImages = new ImageView[mImageIds.size()];
            }
     
            @SuppressWarnings("deprecation")
            public boolean createReflectedImages() {
                final int reflectionGap = 4;
                int index = 0;
                for (int imageId=0;imageId <= mImageIds.size();imageId++) {
                    Bitmap originalImage = BitmapFactory.decodeResource(getResources(), imageId);
                    int width = originalImage.getWidth();
                    int height = originalImage.getHeight();
                    Matrix matrix = new Matrix();
                    matrix.preScale(1, -1);
                    Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0, height / 2, width, height / 2, matrix, false);
                    Bitmap bitmapWithReflection = Bitmap.createBitmap(width,(height + height / 2), Bitmap.Config.ARGB_8888);
                    Canvas canvas = new Canvas(bitmapWithReflection);
                    canvas.drawBitmap(originalImage, 0, 0, null);
                    Paint deafaultPaint = new Paint();
                    canvas.drawRect(0, height, width, height + reflectionGap, deafaultPaint);
                    canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);
                    Paint paint = new Paint();
                    LinearGradient shader = new LinearGradient(0,
                            originalImage.getHeight(), 0,
                            bitmapWithReflection.getHeight() + reflectionGap,
                            0x70ffffff, 0x00ffffff, Shader.TileMode.CLAMP);
                    paint.setShader(shader);
                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
                    canvas.drawRect(0, height, width, bitmapWithReflection.getHeight() + reflectionGap, paint);
                    ImageView imageView = new ImageView(mContext);
                    imageView.setImageBitmap(bitmapWithReflection);
                    android.widget.Gallery.LayoutParams imgLayout = new CoverFlow.LayoutParams(320, 480);
                    imageView.setLayoutParams(imgLayout);
                    imageView.setPadding(30, 100, 20, 20);
                    mImages[index++] = imageView;
                }
                return true;
            }
     
            public int getCount() {
                return mImageIds.size();
            }
     
            public Object getItem(int position) {
                return position;
            }
     
            public long getItemId(int position) {
                return position;
            }
     
            @SuppressWarnings("deprecation")
            public View getView(int position, View convertView, ViewGroup parent) {
                ImageView i = new ImageView(mContext);
                i.setImageResource(mImageIds.get(position));
                i.setLayoutParams(new CoverFlow.LayoutParams(380, 450));
                i.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
                BitmapDrawable drawable = (BitmapDrawable) i.getDrawable();
                drawable.setAntiAlias(true);
                return i;
            }
     
            public float getScale(boolean focused, int offset) {
    			/* Formula: 1 / (2 ^ offset) */
                return Math.max(0, 1.0f / (float) Math.pow(2, Math.abs(offset)));
            }
        }
    }
    Voila j'ai comme erreur:
    java.lang.NumberFormatException: Invalid int: "http://10.0.2.2/AndroidWork/telephones/S5mini.jpg"
    at com.learn2crack.tab.Galerie$ImageAdapter.getView(Galerie.java:194)

    Merci d'avance.

  2. #2
    Modérateur
    Avatar de MasterMbg
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Octobre 2011
    Messages
    719
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Congo-Kinshasa

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Octobre 2011
    Messages : 719
    Points : 1 493
    Points
    1 493
    Par défaut
    Bonjour,
    java.lang.NumberFormatException: Invalid int: "http://10.0.2.2/AndroidWork/telephones/S5mini.jpg"
    veut simplement dire, quelque part dans ton code tu passes une données d'un autre qu'un nombre (entier ou réel). Dans ton cas tu passes une chaîne de caractère alors que tu devrais passer un entier (int).

    Christian,

  3. #3
    Membre à l'essai
    Homme Profil pro
    Étudiant
    Inscrit en
    Février 2014
    Messages
    27
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Sénégal

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Matériel informatique

    Informations forums :
    Inscription : Février 2014
    Messages : 27
    Points : 16
    Points
    16
    Par défaut
    Bonjour Christian,

    Effectivement c'est ca j'ai compri pour l'erreur et j'ai corrige mais maintenant je sai plus comment utiliser ma liste photo dans la classe ImageAdapter.
    Voila ce que j'ai essaye de faire:


    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
     
    public class ImageAdapter extends BaseAdapter {
     
            private Context mContext;
            private ImageView[] mImages;
            public ImageAdapter(Context c) {
                mContext = c;
                mImages = new ImageView[mImageIds.size()];
            }
     
            public int getCount() {
                return mImageIds.size();
            }
            public Object getItem(int position) {
                return position;
            }
            public long getItemId(int position) {
                return position;
            }
     
            @SuppressWarnings("deprecation")
            public View getView(int position, View convertView, ViewGroup parent) {
                ImageView i = new ImageView(mContext);
                Bitmap imageCall = null;
                try{
                    URL urlImage = new URL(mImageIds.get(position));
                    System.out.println(urlImage);
                    HttpURLConnection con = (HttpURLConnection) urlImage.openConnection();
                    InputStream is3 = con.getInputStream();
                    imageCall = BitmapFactory.decodeStream(is3);
                    i.setImageBitmap(imageCall);
                    i.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
                    i.setLayoutParams(new CoverFlow.LayoutParams(380, 450));
                }catch(MalformedURLException ex){
                    Log.e("log_tag", "Erreur url" + ex.toString());
                }catch(IOException e){
                    Log.e("log_tag", "IOException" + e.toString());
                }
                return i;
            }
     
            public float getScale(boolean focused, int offset) {
    			/* Formula: 1 / (2 ^ offset) */
                return Math.max(0, 1.0f / (float) Math.pow(2, Math.abs(offset)));
            }
        }

  4. #4
    Membre à l'essai
    Homme Profil pro
    Étudiant
    Inscrit en
    Février 2014
    Messages
    27
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Sénégal

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Matériel informatique

    Informations forums :
    Inscription : Février 2014
    Messages : 27
    Points : 16
    Points
    16
    Par défaut
    Et maintenant j'ai un nullpointerException parce que la liste mImageIds qui recuperait les donnees renvoit null.
    Cela est du a quoi ici?

  5. #5
    Modérateur
    Avatar de MasterMbg
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Octobre 2011
    Messages
    719
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Congo-Kinshasa

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Octobre 2011
    Messages : 719
    Points : 1 493
    Points
    1 493
    Par défaut
    Citation Envoyé par thioky Voir le message
    Et maintenant j'ai un nullpointerException parce que la liste mImageIds qui recuperait les donnees renvoit null.
    Cela est du a quoi ici?
    Parce que la variable mImageIds n'est pas déclarée, ni initialisée dans la classe ImageAdapter alors que tu l'utilises un peu partout.

    Christian,

  6. #6
    Membre à l'essai
    Homme Profil pro
    Étudiant
    Inscrit en
    Février 2014
    Messages
    27
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Sénégal

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Matériel informatique

    Informations forums :
    Inscription : Février 2014
    Messages : 27
    Points : 16
    Points
    16
    Par défaut
    Ok Christian, selon vous comment je dois proceder pour pouvoir recuperer les liens image de ma table et les utiliser dans ImageAdapter svp?
    Voila comment je recupere les lien image

    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
     
    class DownloadImage extends AsyncTask<Void, Void, ArrayList<String>> {
            List<NameValuePair> nameValuePairs;
            InputStream is = null;
            String result = null;
            protected ArrayList<String> doInBackground(Void... params) {
                try {
                    HttpClient httpclient = new DefaultHttpClient();
                    nameValuePairs = new ArrayList<NameValuePair>();
                    nameValuePairs.add(new BasicNameValuePair("id", donnee));
                    HttpPost httppost = new HttpPost("http://10.0.2.2/AndroidWork/affiche_galerie.php");
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity entity = response.getEntity();
                    is = entity.getContent();
                } catch (Exception e) {
                    Log.e("log_tag", "Exception levee " + e.toString());
                }
                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                    StringBuilder sb = new StringBuilder();
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    is.close();
                    result = sb.toString();
                } catch (Exception e) {
                    Log.e("log_tag", "Erreur de conversion du resultat " + e.toString());
                }
                try {
                    JSONArray array = new JSONArray(result.toString());
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject json_data = array.getJSONObject(i);
                        maListDonnee.add(json_data.getString("photo"));
                    }
                } catch (Exception e) {
                    Log.e("log_tag", "" + e.toString());
                }
                return  maListDonnee;
            }
            protected void onPostExecute(ArrayList<String> resultat) {}
    et dans onStart j'ai mis ceci:

    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
     
     public void onStart(){
            super.onStart();
            maListDonnee = new ArrayList<String>();
            mImageIds = new ArrayList<String>();
            Intent i = this.getActivity().getIntent();
            donnee = i.getStringExtra(Accueil.CODE);
            try {
                mImageIds = new DownloadImage().execute().get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
    }

  7. #7
    Membre à l'essai
    Homme Profil pro
    Étudiant
    Inscrit en
    Février 2014
    Messages
    27
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Sénégal

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Matériel informatique

    Informations forums :
    Inscription : Février 2014
    Messages : 27
    Points : 16
    Points
    16
    Par défaut
    Je peine vraiment a faire cela depuis ce matin. J'ai fais des recherche mais je ne voix que des tuto avec des ressources drawable comme image.

  8. #8
    Modérateur
    Avatar de MasterMbg
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Octobre 2011
    Messages
    719
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Congo-Kinshasa

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Octobre 2011
    Messages : 719
    Points : 1 493
    Points
    1 493
    Par défaut
    Citation Envoyé par thioky Voir le message
    Ok Christian, selon vous comment je dois proceder pour pouvoir recuperer les liens image de ma table et les utiliser dans ImageAdapter svp?
    Je pense que le problème vient plutôt de la classe ImageAdapter. Avant toute chose, arrives tu à bien charger le tableau qui est sensé contenir tous les liens des images provenant de base de données? Ce tableau n'est il pas vide après le chargement de données depuis la base? Tu peux vérifier à l'aide d'une boucle qui parcourt ce tableau en affichant son contenu.

    Christian,

  9. #9
    Membre à l'essai
    Homme Profil pro
    Étudiant
    Inscrit en
    Février 2014
    Messages
    27
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Sénégal

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Matériel informatique

    Informations forums :
    Inscription : Février 2014
    Messages : 27
    Points : 16
    Points
    16
    Par défaut
    Oui sans la classe ImageAdapter je parviens a recuperer les lien de mes image dans la liste mImageIds.

  10. #10
    Modérateur
    Avatar de MasterMbg
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Octobre 2011
    Messages
    719
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Congo-Kinshasa

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Octobre 2011
    Messages : 719
    Points : 1 493
    Points
    1 493
    Par défaut
    Citation Envoyé par thioky Voir le message
    Oui sans la classe ImageAdapter je parviens a recuperer les lien de mes image dans la liste mImageIds.
    Ok, tu peux faire ceci :

    - Dans l'activity principale (Là où tu fais appel à ton adaptateur) tu charges tous les liens des images dans un ArrayList(Ce que tu as déjà fait d'ailleurs). Ce sera ce ArrayList que tu passeras dans l'adaptateur par la suite;
    - Ensuite, dans la classe ImageAdapter, tu déclares un ArrayList qui va accueillir les données (les liens chargés avant l'appel à l'adaptateur). Dans le constructeur de la classe ImageAdapter, ajoute un paramètre pour accueillir la liste des liens et à l’intérieur du constructeur affecte cette liste à ton ArrayList.

    Concrètement, ta classe ImageAdapter se présenterait comme suit :
    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
     
    public class ImageAdapter extends BaseAdapter {
     
            private Context mContext;
            private ImageView[] mImages;
     
            //ArrayList qui recevra les liens des images...
            private ArrayList<String> mImageIds;
     
            //Le constructeur...
            public ImageAdapter(Context c, ArrayList<String> liens_images) {
                mContext = c;
                //Récupération des liens passés en paramètre...
                mImageIds = liens_images;
                mImages = new ImageView[mImageIds.size()];
            }
     
            public int getCount() {
                return mImageIds.size();
            }
            public Object getItem(int position) {
                return position;
            }
            public long getItemId(int position) {
                return position;
            }
     
            @SuppressWarnings("deprecation")
            public View getView(int position, View convertView, ViewGroup parent) {
                ImageView i = new ImageView(mContext);
                Bitmap imageCall = null;
                try{
                    URL urlImage = new URL(mImageIds.get(position));
                    System.out.println(urlImage);
                    HttpURLConnection con = (HttpURLConnection) urlImage.openConnection();
                    InputStream is3 = con.getInputStream();
                    imageCall = BitmapFactory.decodeStream(is3);
                    i.setImageBitmap(imageCall);
                    i.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
                    i.setLayoutParams(new CoverFlow.LayoutParams(380, 450));
                }catch(MalformedURLException ex){
                    Log.e("log_tag", "Erreur url" + ex.toString());
                }catch(IOException e){
                    Log.e("log_tag", "IOException" + e.toString());
                }
                return i;
            }
     
            public float getScale(boolean focused, int offset) {
    			/* Formula: 1 / (2 ^ offset) */
                return Math.max(0, 1.0f / (float) Math.pow(2, Math.abs(offset)));
            }
        }

    Dans la méthode onCreateView de la classe Galerie.java, laisse que des déclarations et enlève toute affectation pour éviter des problèmes parce qu'il y a certains codes qui sont mis dans la méthode onStart() qui devraient en principe intervenir avant certaines affectations faites dans la méthode onCreateView.

    Voici comment j'ai modifié ta classe Galerie.java pour répondre à la nouvelle architecture (Suis bien les recommandations en commentaires) :
    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
    public class Galerie extends Fragment {
     
        ArrayList<String> maListDonnee;
        private ImageView viewer;
        String donnee = null;
        private ArrayList<String> mImageIds;
        DownloadImage dmg;
        CoverFlow coverFlow;
        ImageAdapter coverImageAdapter;
     
        //Création d'un objet Activity qui va obtenir l'activity qui aura lancé ce fragment
        //Il va obtenir sa valeur dans la méthode onAttach du fragment
     
        Activity activity_lancer;
     
        @SuppressWarnings("deprecation")
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
     
            View g = inflater.inflate(R.layout.image_frag, container, false);
     
            coverFlow = new CoverFlow(activity_lancer);
            getActivity().setContentView(coverFlow);
     
            return g;
        }
     
        @Override
        public void onStart(){
            super.onStart();
            maListDonnee = new ArrayList<String>();
            mImageIds = new ArrayList<String>();
     
            Intent i = this.getActivity().getIntent();
            donnee = i.getStringExtra(Accueil.CODE);
            try {
                mImageIds = new DownloadImage().execute().get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
     
            /*Je pense que le code ci-dessous devrait intervenir dans la classe DownloadImage (Donc dans la méthode onPostExecute...) sinon, il s'exécuterait avant même que la liste soit complétée et cela afficherait des erreurs... 
            */
            //============================================================
            //Création de l'adaptateur, juste après le finissage du chargement des liens des images (Donc dans la méthode onPostExecute...).
            coverImageAdapter = new ImageAdapter(activity_lancer, mImageIds);
            //L'adaptateur étant prêt, on peut l'affecter où on veut
            coverFlow.setAdapter(coverImageAdapter);
            //La suite de ton code...
            coverFlow.setSpacing(-25);
            coverFlow.setSelection(4, true);
            coverFlow.setAnimationDuration(1000);
            //============================================================
     
        }
     
        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);
            //Récupérer l'activity qui a lancer le fragment
            activity_lancer = activity;
        }
     
        public class ImageAdapter extends BaseAdapter {
     
            private Context mContext;
            private ImageView[] mImages;
     
            //ArrayList qui recevra les liens des images...
            private ArrayList<String> mImageIds;
     
            //Le constructeur...
            public ImageAdapter(Context c, ArrayList<String> liens_images) {
                mContext = c;
                //Récupération des liens passés en paramètre...
                mImageIds = liens_images;
                mImages = new ImageView[mImageIds.size()];
            }
     
            public int getCount() {
                return mImageIds.size();
            }
            public Object getItem(int position) {
                return position;
            }
            public long getItemId(int position) {
                return position;
            }
     
            @SuppressWarnings("deprecation")
            public View getView(int position, View convertView, ViewGroup parent) {
                ImageView i = new ImageView(mContext);
                Bitmap imageCall = null;
                try{
                    URL urlImage = new URL(mImageIds.get(position));
                    System.out.println(urlImage);
                    HttpURLConnection con = (HttpURLConnection) urlImage.openConnection();
                    InputStream is3 = con.getInputStream();
                    imageCall = BitmapFactory.decodeStream(is3);
                    i.setImageBitmap(imageCall);
                    i.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
                    i.setLayoutParams(new CoverFlow.LayoutParams(380, 450));
                }catch(MalformedURLException ex){
                    Log.e("log_tag", "Erreur url" + ex.toString());
                }catch(IOException e){
                    Log.e("log_tag", "IOException" + e.toString());
                }
                return i;
            }
     
            public float getScale(boolean focused, int offset) {
    			/* Formula: 1 / (2 ^ offset) */
                return Math.max(0, 1.0f / (float) Math.pow(2, Math.abs(offset)));
            }
        }
    }
    Il y a pas mal des choses à corriger, mais commençons d'abord par là.
    Je n'ai pas tester le code. Au cas où il y aurait erreur, prière de ne pas me tenir rigueur

    Christian,

  11. #11
    Membre à l'essai
    Homme Profil pro
    Étudiant
    Inscrit en
    Février 2014
    Messages
    27
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Sénégal

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Matériel informatique

    Informations forums :
    Inscription : Février 2014
    Messages : 27
    Points : 16
    Points
    16
    Par défaut
    Bonjour Christian,

    Merci pour ton aide, j'avais finalement pu faire le jour même. J'étais épuisé, du cou j'ai pris quelques jour de vacance, c'est pourquoi j'ai tardé a posté mon résultat.
    Bon voila ce que j'ai fait avec la classe Galerie.java:

    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
     
    public class Galerie extends Fragment {
     
         String donnee = null;
         ArrayList<URL> maListDonnee;
         private ArrayList<URL> mImageIds;
         CoverFlow coverFlow;
         ImageAdapter coverImageAdapter;
         private ImageView imgView;
     
         @SuppressWarnings("deprecation")
    	 @Override
    	 public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
     
    	 View g = inflater.inflate(R.layout.image_frag, container, false);
             if (android.os.Build.VERSION.SDK_INT > 9) {
                 StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                 StrictMode.setThreadPolicy(policy);
             }
             mImageIds = new ArrayList<URL>();
             Intent i = this.getActivity().getIntent();
             donnee = i.getStringExtra(Accueil.CODE);
             try {
                 mImageIds = new DownloadImage().execute().get();
             } catch (InterruptedException e) {
                 e.printStackTrace();
             } catch (ExecutionException e) {
                 e.printStackTrace();
             }
     
             coverFlow = new CoverFlow(getActivity());
             coverImageAdapter = new ImageAdapter(getActivity());
             coverFlow.setAdapter(coverImageAdapter);
             coverFlow.setSpacing(-20);
             coverFlow.setSelection(4, true);
             coverFlow.setAnimationDuration(1000);
             getActivity().setContentView(coverFlow);
    	 return g;
         }
     
       public void onStart(){super.onStart();}
     
        class DownloadImage extends AsyncTask<Void, Void, ArrayList<URL>> {
            List<NameValuePair> nameValuePairs;
            InputStream is = null;
            String result = null;
            protected ArrayList<URL> doInBackground(Void... params) {
                try {
                    HttpClient httpclient = new DefaultHttpClient();
                    maListDonnee = new ArrayList<URL>();
                    nameValuePairs = new ArrayList<NameValuePair>();
                    nameValuePairs.add(new BasicNameValuePair("id", donnee));
                    HttpPost httppost = new HttpPost("http://10.0.2.2/AndroidWork/affiche_galerie.php");
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity entity = response.getEntity();
                    is = entity.getContent();
                } catch (Exception e) {
                    Log.e("log_tag", "Exception levee " + e.toString());
                }
                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                    StringBuilder sb = new StringBuilder();
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    is.close();
                    result = sb.toString();
                } catch (Exception e) {
                    Log.e("log_tag", "Erreur de conversion du resultat " + e.toString());
                }
                try {
                    JSONArray array = new JSONArray(result.toString());
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject json_data = array.getJSONObject(i);
                        maListDonnee.add(new URL(json_data.getString("photo")));
                    }
                } catch (Exception e) {
                    Log.e("log_tag", "" + e.toString());
                }
                return  maListDonnee;
            }
            protected void onPostExecute(ArrayList<String> resultat) {}
        }
     
        public class ImageAdapter extends BaseAdapter {
     
            private Context mContext;
            public ImageAdapter(Context c) {
                mContext = c;
            }
            public int getCount() {
                return mImageIds.size();
            }
            public Object getItem(int position) {
                return position;
            }
            public long getItemId(int position) {
                return position;
            }
     
            @SuppressWarnings("deprecation")
            public View getView(int position, View convertView, ViewGroup parent) {
                if (convertView == null) {
                    imgView = new ImageView(mContext);
                } else {
                    imgView = (ImageView)convertView;
                }
                setImage(imgView, mImageIds.get(position));
                imgView.setLayoutParams(new CoverFlow.LayoutParams(380,450));
                imgView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
                return imgView;
            }
     
            public float getScale(boolean focused, int offset) {
    			/* Formula: 1 / (2 ^ offset) */
                return Math.max(0, 1.0f / (float) Math.pow(2, Math.abs(offset)));
            }
        }
        public void setImage(ImageView iView, URL iurl) {
            try {
                URLConnection con = iurl.openConnection();
                conn.connect();
                InputStream is = con.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is,8192);
                Bitmap bm = BitmapFactory.decodeStream(is);
                bis.close();
                is.close();
                iView.setImageBitmap(bm);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    Ca marche bien maintenant et merci encore pour ton aide.
    J'ai testé votre code, y'a un problème de Thread (android.os.NetworkOnMainThreadException) mais ca m'a beaucoup aidé. Merci

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

Discussions similaires

  1. Récupérer des images à partir d'une BD MySql
    Par aladin2110 dans le forum Android
    Réponses: 3
    Dernier message: 14/08/2012, 17h34
  2. Tri des données provenant d'une requête mysql
    Par scrappilly dans le forum Langage SQL
    Réponses: 9
    Dernier message: 27/09/2011, 15h19
  3. [MySQL] Affichage des images insérés dans une base Mysql
    Par ines_m dans le forum PHP & Base de données
    Réponses: 3
    Dernier message: 26/05/2008, 17h54
  4. initialiser les label avec des infos provenant d'une table
    Par mouss4rs dans le forum Interfaces Graphiques en Java
    Réponses: 3
    Dernier message: 24/04/2008, 09h54
  5. Réponses: 2
    Dernier message: 14/05/2007, 09h40

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