Partage
  • Partager sur Facebook
  • Partager sur Twitter

Erreur d'affichage avec la condition WHILE SQLite

    7 novembre 2019 à 9:29:18

    bonjour famille. Je suis un débutant en développement android. voici un petit projet qui consiste a enregistrer des informations et les afficher

    mais depuis quelques jours je suis confronter a un problème au niveau de l'affichage alors je viens vous demander de l'aide

    voici le fichier MainActivity

    <?xml version="1.0" encoding="utf-8"?>
    <ScrollView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:padding="10dp">
    
            <ImageView
                android:id="@+id/imageView"
                android:layout_alignParentTop="true"
                android:background="@color/colorPrimary"
                android:layout_width="160dp"
                android:layout_height="160dp"
                android:src="@drawable/placeholder"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="18dp"/>
            <EditText
                android:id="@+id/editName"
               android:layout_below="@id/imageView"
                android:hint="Name"
                android:layout_centerHorizontal="true"
                android:ems="10"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>
            <EditText
                android:id="@+id/editAge"
                android:layout_below="@id/editName"
                android:hint="Age"
                android:layout_centerHorizontal="true"
                android:ems="10"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>
            <EditText
                android:id="@+id/editPhone"
                android:layout_below="@id/editAge"
                android:hint="contact"
                android:layout_centerHorizontal="true"
                android:ems="10"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>
            <Button
                android:id="@+id/btnAdd"
                android:layout_below="@id/editPhone"
                android:layout_centerHorizontal="true"
                android:minWidth="160dp"
                android:text="SAVE RECORD"
                style="@style/Widget.AppCompat.Button.Colored"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
            <Button
                android:id="@+id/btnList"
                android:layout_below="@id/btnAdd"
                android:layout_centerHorizontal="true"
                android:minWidth="160dp"
                android:text="RECORD LIST"
                style="@style/Widget.AppCompat.Button.Colored"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
        </RelativeLayout>
    
    </ScrollView>

    et voici le fichier la classe MainActivity

    package com.example.monapplication;
    
    import androidx.annotation.NonNull;
    import androidx.annotation.Nullable;
    import androidx.appcompat.app.AppCompatActivity;
    import androidx.core.app.ActivityCompat;
    
    import android.Manifest;
    import android.app.Activity;
    import android.content.Intent;
    import android.content.pm.PackageManager;
    import android.graphics.Bitmap;
    import android.graphics.drawable.BitmapDrawable;
    import android.net.Uri;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ImageView;
    import android.widget.Toast;
    
    import com.theartofdev.edmodo.cropper.CropImage;
    import com.theartofdev.edmodo.cropper.CropImageView;
    
    import java.io.ByteArrayOutputStream;
    
    public class MainActivity extends AppCompatActivity {
        EditText mEditName, mEditAge, mEditPhone;
        Button mBtnAdd, mBtnList;
        ImageView mImageView;
    
        final int REQUEST_CODE_GALLERY = 999;
        public static SQLiteHelper mSQLiteHelper;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            mEditName = findViewById(R.id.editName);
            mEditAge = findViewById(R.id.editAge);
            mEditPhone = findViewById(R.id.editPhone);
            mImageView = findViewById(R.id.imageView);
            mBtnAdd= findViewById(R.id.btnAdd);
            mBtnList = findViewById(R.id.btnList);
    
            // Creation de la base de donnee
            mSQLiteHelper = new SQLiteHelper(this,"RECORDDB.sqlite",null,1);
    
            // Creation de la table dans la base de donnee
            mSQLiteHelper.queryData("CREATE TABLE IF NOT EXISTS RECORD(id INTEGER PRIMARY KEY AUTOINCREMENT,name VARCHAR," +
                    "age VARCHAR,phone VARCHAR, image BLOB)");
    
            mImageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                            REQUEST_CODE_GALLERY);
                }
            });
           // Ajouter des donnees dans la base de donnee sqlite
           mBtnAdd.setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {
                try {
                    mSQLiteHelper.insertData(mEditName.getText().toString().trim(),mEditAge.getText().toString().trim(),
                            mEditPhone.getText().toString().trim(),
                            mImageViewToByte(mImageView));
                    Toast.makeText(MainActivity.this,"Ajouter avec succes",Toast.LENGTH_SHORT).show();
                    // Vider les champs
                    mEditName.setText("");
                    mEditAge.setText("");
                    mEditPhone.setText("");
                    mImageView.setImageResource(R.drawable.placeholder);
                }catch (Exception e){
                    e.printStackTrace();
                }
               }
           });
           // Afficher le contenu de la base de donnee
             mBtnList.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                // rediriger a l'activite RecordList
                  Intent intent = new Intent(getApplicationContext(),RecordListActivity.class);
                  startActivity(intent);
                }
            });
        }
    
        public static byte[] mImageViewToByte(ImageView image) {
            Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG,100,stream);
            byte[] byteArray = stream.toByteArray();
            return byteArray;
        }
    
        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    
            if (requestCode == REQUEST_CODE_GALLERY){
                if (grantResults.length> 0 && grantResults[0]== PackageManager.PERMISSION_GRANTED){
                    Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
                    galleryIntent.setType("image/*");
                    startActivityForResult(galleryIntent,REQUEST_CODE_GALLERY);
                }
                else {
                    Toast.makeText(this,"Vous n'avez la permission pour acceder a la gallerie",Toast.LENGTH_SHORT).show();
                }
                return;
            }
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
            if (requestCode == REQUEST_CODE_GALLERY && resultCode == RESULT_OK){
                Uri imageUri = data.getData();
                CropImage.activity(imageUri).setGuidelines(CropImageView.Guidelines.ON)
                .setAspectRatio(1,1).start(this);
            }
            if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE){
                CropImage.ActivityResult result = CropImage.getActivityResult(data);
    
                if (resultCode == RESULT_OK){
                    Uri resultUri = result.getUri();
                    // attribuer l'image choisir a imageView
                    mImageView.setImageURI(resultUri);
                }
                else if(resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE){
                    Exception error = result.getError();
                }
            }
            super.onActivityResult(requestCode, resultCode, data);
        }
    }
    

    voici la classe Model

    package com.example.monapplication;
    
    public class Model {
        private int id;
        private String name;
        private String age;
        private String phone;
        private byte[] image;
    
        public Model(int id, String name, String age, String phone, byte[] image) {
            this.id = id;
            this.name = name;
            this.age = age;
            this.phone = phone;
            this.image = image;
         }
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getAge() {
            return age;
        }
    
        public void setAge(String age) {
            this.age = age;
        }
    
        public String getPhone() {
            return phone;
        }
    
        public void setPhone(String phone) {
            this.phone = phone;
        }
    
        public byte[] getImage() {
            return image;
        }
    
        public void setImage(byte[] image) {
            this.image = image;
        }
    }
    

    voici le fichier d'affichage xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".RecordListActivity"
        android:orientation="vertical">
    
        <ListView
            android:id="@+id/listView"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
    
        </ListView>
    
    </LinearLayout>
    voici la classe d'affichage
    package com.example.monapplication;
    
    import androidx.appcompat.app.AppCompatActivity;
    
    import android.database.Cursor;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.ListView;
    import android.widget.Toast;
    
    
    import java.util.ArrayList;
    
    public class RecordListActivity extends AppCompatActivity {
        ListView mListView;
        ArrayList<Model> mList;
        recordListAdapter mAdapter = null;
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_record_list);
    
            mListView = findViewById(R.id.listView);
            mList = new ArrayList<>();
            mAdapter = new recordListAdapter(this ,R.layout.row, mList);
            mListView.setAdapter(mAdapter);
            // recuperer les donnees
            Cursor cursor = MainActivity.mSQLiteHelper.getData("SELECT * FROM RECORD");
            mList.clear();
          while (cursor.moveToNext()){
              int id = cursor.getInt(0);
              String name = cursor.getString(1);
              String age = cursor.getString(2);
              String phone = cursor.getString(3);
              byte[] image = cursor.getBlob(4);
    
              mList.add(new Model(id,name,age,phone,image));
          }
    
            mAdapter.notifyDataSetChanged();
            if (mList.size()==0){
                //s'il n'y a pas de donnee dans la table de la base alors il retournera une liste vide
                Toast.makeText(this,"Pas de donnee trouvee",Toast.LENGTH_SHORT).show();
            }
            mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
    
                    return false;
                }
            });
        }
    }
    
     le ficher row.xml
    <?xml version="1.0" encoding="utf-8"?>
    <androidx.cardview.widget.CardView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:cardElevation="3dp"
        app:cardUseCompatPadding="true"
        app:cardCornerRadius="3dp"
        app:cardBackgroundColor="#fff"
        app:contentPadding="5dp">
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal"
            android:layout_gravity="center_vertical">
    
            <ImageView
                android:id="@+id/imageIcon"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:src="@drawable/placeholder"/>
    
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:layout_marginLeft="5dp"
                android:layout_marginStart="5dp">
    
                <TableLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">
    
                    <TableRow>
    
                        <TextView
                            android:id="@+id/txtName"
                            android:text="Name :"
                            android:textSize="20dp"
                            android:textColor="#000"
                            android:textStyle="bold"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"/>
    
                        <TextView
                            android:text="NameHere"
                            android:textSize="20dp"
                            android:textColor="#000"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"/>
                    </TableRow>
    
                    <TableRow>
    
                        <TextView
                            android:id="@+id/txtAge"
                            android:text="Age :"
                            android:textSize="20dp"
                            android:textColor="#000"
                            android:textStyle="bold"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"/>
    
                        <TextView
                            android:text="ageHere"
                            android:textSize="20dp"
                            android:textColor="#000"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"/>
                    </TableRow>
    
                    <TableRow>
    
                        <TextView
                            android:id="@+id/txtPhone"
                            android:text="Phone :"
                            android:textSize="20dp"
                            android:textColor="#000"
                            android:textStyle="bold"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"/>
    
                        <TextView
                            android:text="phoneHere"
                            android:textSize="20dp"
                            android:textColor="#000"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"/>
                    </TableRow>
    
                </TableLayout>
            </LinearLayout>
        </LinearLayout>
    
    </androidx.cardview.widget.CardView>
     la classe recordListAdapter
    package com.example.monapplication;
    
    import android.content.Context;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.ImageView;
    import android.widget.TextView;
    
    import java.util.ArrayList;
    
    public class recordListAdapter extends BaseAdapter {
    
        private Context context;
        private int layout;
        private ArrayList<Model> recordList;
    
        public recordListAdapter(Context context, int layout, ArrayList<Model> recordList) {
            this.context = context;
            this.layout = layout;
            this.recordList = recordList;
        }
    
        @Override
        public int getCount() {
            return recordList.size();
        }
    
        @Override
        public Object getItem(int position) {
            return recordList.get(position);
        }
    
        @Override
        public long getItemId(int position) {
            return position;
        }
          private class ViewHolder{
            ImageView imageView;
            TextView txtName, txtAge, txtPhone;
        }
    
        @Override
        public View getView(int position, View view, ViewGroup viewGroup) {
    
            View row = view;
            ViewHolder holder = new ViewHolder();
    
            if (row == null){
                LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                row = inflater.inflate(layout,null);
                holder.txtName = row.findViewById(R.id.txtName);
                holder.txtAge = row.findViewById(R.id.txtAge);
                holder.txtPhone = row.findViewById(R.id.txtPhone);
                 holder.imageView = row.findViewById(R.id.imageIcon);
    
                row.setTag(holder);
            }
            else {
                holder = (ViewHolder)row.getTag();
            }
    
            Model model = recordList.get(position);
            holder.txtName.setText(model.getName());
            holder.txtAge.setText(model.getAge());
            holder.txtPhone.setText(model.getPhone());
    
            byte[] recordImage = model.getImage();
            Bitmap bitmap = BitmapFactory.decodeByteArray(recordImage,0,recordImage.length);
            holder.imageView.setImageBitmap(bitmap);
    
            return row;
        }
    }
    
     la classe SQLIiteHelper
    package com.example.monapplication;
    
    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    import android.database.sqlite.SQLiteStatement;
    
    import androidx.annotation.Nullable;
    
    public class SQLiteHelper extends SQLiteOpenHelper {
        public SQLiteHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
            super(context, name, factory, version);
        }
        public void queryData(String sql){
            SQLiteDatabase database = getWritableDatabase();
            database.execSQL(sql);
        }
        // Insertion des donnees
        public void insertData(String name, String age, String phone, byte[]image){
         SQLiteDatabase database = getWritableDatabase();
    
         // Insertion de la table dans la base de donnee
            String sql = "INSERT INTO RECORD VALUES(NULL,?,?,?,?)";//RECORD est le nom de la table de la base de donnee que nous allons creer dans MainActivity
    
            SQLiteStatement statement = database.compileStatement(sql);
            statement.clearBindings();
    
            statement.bindString(1,name);
            statement.bindString(2,age);
            statement.bindString(3,phone);
            statement.bindBlob(4,image);
    
            statement.executeInsert();
        }
        // Mise a jour des donnees
        public void updateData(String name, String age, String phone, byte[]image, int id){
         SQLiteDatabase database = getWritableDatabase();
         // la requete de mise a jour de la table RECORD
           String sql = "UPDATE RECORD SET name=?, age=?, phone=?,image=? WHERE id=?";
    
           SQLiteStatement statement = database.compileStatement(sql);
    
            statement.bindString(1,name);
            statement.bindString(2,age);
            statement.bindString(3,phone);
            statement.bindBlob(4,image);
            statement.bindDouble(5,(double)id);
    
            statement.execute();
            database.close();
        }
        //Suppression de donnees
        public void deleteData(int id){
            SQLiteDatabase database = getWritableDatabase();
            // requete de suppression a partir de son identifiant
            String sql = "DELETE FROM RECORD WHERE id=?";
    
            SQLiteStatement statement = database.compileStatement(sql);
            statement.clearBindings();
            statement.bindDouble(1,(double)id);
    
            statement.execute();
            database.close();
        }
        public Cursor getData(String sql){
            SQLiteDatabase database = getReadableDatabase();
    
            return database.rawQuery(sql,null);
        }
    
        @Override
        public void onCreate(SQLiteDatabase db) {
    
        }
    
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    
        }
    }
    
     voici le message d'erreur
    at com.example.monapplication.RecordListActivity.onCreate(RecordListActivity.java:34)
            at android.app.Activity.performCreate(Activity.java:7044)
            at android.app.Activity.performCreate(Activity.java:7035)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2759)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2884) 
            at android.app.ActivityThread.-wrap11(Unknown Source:0) 
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1614) 
            at android.os.Handler.dispatchMessage(Handler.java:106) 
            at android.os.Looper.loop(Looper.java:164) 
            at android.app.ActivityThread.main(ActivityThread.java:6524) 
            at java.lang.reflect.Method.invoke(Native Method) 
            at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:451) 
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:888) 
    



     

    -
    Edité par dieudonnekouadio 7 novembre 2019 à 11:00:55

    • Partager sur Facebook
    • Partager sur Twitter
      7 novembre 2019 à 10:21:04

      Bonjour,

      Mauvais titre

      Le titre est un élément important qui ne doit pas être négligé. N'oubliez pas cette règle simple : le titre idéal résume la question que vous allez poser en une petite phrase. Il doit permettre aux visiteurs de se repérer facilement dans le forum visité et d'identifier le sujet à sa seule lecture.

      Vous pouvez utiliser divers préfixes comme [Erreur], [MySQL], [Compatibilité], etc... Aussi, pensez à consulter les règles propres à chaque forum (visibles dans les topics épinglés en haut des sections).

      De plus, choisir un bon titre permet de rendre plus faciles les recherches des autres membres.

      Les titres de type "besoin d'aide" ou "problème" ne sont pas tolérés.

      Pour modifier votre titre, éditez le premier message de votre sujet.

      (titre originel : demande d'aide)

      Liens conseillés

      • Partager sur Facebook
      • Partager sur Twitter

      Erreur d'affichage avec la condition WHILE SQLite

      × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
      × Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.
      • Editeur
      • Markdown