logcat показывает ошибку, мое приложение не показывает изображение в gridview с использованием базы данных SQLite - PullRequest
0 голосов
/ 04 июля 2018

Ошибка: после запуска builder на моем мобильном телефоне logcat показывает ошибку петлителя

at miui.util.ReflectionUtils.findMethodBestMatch(ReflectionUtils.java:338)
        at miui.util.ReflectionUtils.findMethodBestMatch(ReflectionUtils.java:375)
        at miui.util.ReflectionUtils.callMethod(ReflectionUtils.java:800)
        at miui.util.ReflectionUtils.tryCallMethod(ReflectionUtils.java:818)
        at android.os.BaseLooper.enableMonitor(BaseLooper.java:47)
        at android.os.Looper.prepareMainLooper(Looper.java:112)

Создание программы SQLiteDatabaseHelper

public class SQLiteHelper extends SQLiteOpenHelper {

    public SQLiteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    public void queryData(String sql){
        SQLiteDatabase database = getWritableDatabase();
        database.execSQL(sql);
    }

Вставка данных из базы данных с использованием базы данных Sqlite

 public void insertData(String name, String age, String phone, byte[] image){
        SQLiteDatabase database = getWritableDatabase();
        //query to insert records
        String sql = "INSERT INTO RECORD VALUES(NULL, ?, ?, ?, ?)";//we will create "RECORD" table in main activity

        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();
    }

обновление значений в базе данных

public void updateData(String name, String age, String phone, byte[] image, int id){
        SQLiteDatabase database = getWritableDatabase();
        //query to update 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();
    }

Удалить выбранные данные из базы данных

 public void deleteData(int id){
        SQLiteDatabase database = getWritableDatabase();
        // query to delete record
        String sql = "DELETE FROM RECORD WHERE id=?";

        SQLiteStatement statement = database.compileStatement(sql);
        statement.clearBindings();
        statement.bindDouble(1, (double)id);

        statement.execute();
        database.close();
    }

Получение данных из SQLite

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) {

    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {

    EditText mName,mAge,mPhone;
    Button mAdd,mView;
    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);

        mName = (EditText)findViewById(R.id.txtName);
        mAge = (EditText)findViewById(R.id.txtAge);
        mPhone = (EditText)findViewById(R.id.txtPhone);
        mAdd = (Button)findViewById(R.id.btnSave);
        mView = (Button)findViewById(R.id.BtnList);
        mimageview = (ImageView)findViewById(R.id.imgView);

        //creating datadase

        mSQLitehelper = new SQLiteHelper(this, "RECORDDB.sqlite", null, 1);

        //create table

        mSQLitehelper.queryData("CREATE TABLE IF NOT EXISTS RECORD (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, age VARCHAR, phone VARCHAR, image BLOB)");

        //select image by on imageview click
        mimageview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //read external storage permition to select the file form gallery
                ActivityCompat.requestPermissions(
                        MainActivity.this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        REQUEST_CODE_GALLERY
                );
            }
        });

        // add records to SQLite
        mAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try{
                    mSQLitehelper.insertData(
                            mName.getText().toString().trim(),
                            mAge.getText().toString().trim(),
                            mPhone.getText().toString().trim(),
                            imageViewToByte(mimageview)
                    );
                    Toast.makeText(MainActivity.this, "Add Successfully",Toast.LENGTH_SHORT).show();
                    //reset views
                    mName.setText("");
                    mAge.setText("");
                    mPhone.setText("");
                    mimageview.setImageResource(R.drawable.ic_add_image);
                }
                catch (Exception e){
                    e.printStackTrace();
                }
            }
        });

        //show record list

        mView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Record list activity
                startActivity(new Intent(MainActivity.this,RecordListActivity.class));
            }
        });
    }

    public static byte[] imageViewToByte(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 intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent, REQUEST_CODE_GALLERY);
            }
            else {
                Toast.makeText(getApplicationContext(), "You don't have permission to access file location!", Toast.LENGTH_SHORT).show();
            }
            return;
        }

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if(requestCode == REQUEST_CODE_GALLERY && resultCode == RESULT_OK && data != null){
            Uri uri = data.getData();

            try {
                InputStream inputStream = getContentResolver().openInputStream(uri);

                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                mimageview.setImageBitmap(bitmap);

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

        super.onActivityResult(requestCode, resultCode, data);
    }
}

Model.java

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;
    }
}

RecordListActivity.java

public class RecordListActivity extends AppCompatActivity {

    ListView mListView;
    ArrayList<Model> mList;
    RecordListAdapter mAdapter = null;

    ImageView imageViewIcon;

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

        mListView = (ListView)findViewById(R.id.listView);
        mList = new ArrayList<>();
        mAdapter = new RecordListAdapter(this, R.layout.row, mList);
        mListView.setAdapter(mAdapter);

        //get all data from sqlite

        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);

            //add to list
            mList.add(new Model(id, name, age, phone, image));
        }

        mAdapter.notifyDataSetChanged();
        if(mList.size()==0){
            // if there is no records in database
            Toast.makeText(this,"No Record Found",Toast.LENGTH_SHORT).show();
        }

        mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                return false;
            }
        });
    }
}

RecordListAdapter

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 textName, textAge, textPhone;
    }

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

        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.textName = row.findViewById(R.id.textName);
            holder.textAge = row.findViewById(R.id.textAge);
            holder.textPhone = row.findViewById(R.id.textPhone);
            holder.imageView = row.findViewById(R.id.imgIcon);
            row.setTag(holder);
        }
        else{
            holder = (ViewHolder)row.getTag();
        }

        Model model = recordList.get(position);

        holder.textName.setText(model.getName());
        holder.textAge.setText(model.getAge());
        holder.textPhone.setText(model.getPhone());

        byte[] recordImage = model.getImage();
        Bitmap bitmap = BitmapFactory.decodeByteArray(recordImage, 0, recordImage.length );
        holder.imageView.setImageBitmap(bitmap);

        return row;
    }
}

activity_main.xml

<RelativeLayout 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"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/imgView"
        android:layout_width="160dp"
        android:layout_height="160dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="38dp"
        app:srcCompat="@drawable/ic_add_image" />

    <EditText
        android:id="@+id/txtName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="221dp"
        android:ems="10"
        android:hint="Name"
        android:inputType="textPersonName" />

    <EditText
        android:id="@+id/txtAge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:ems="10"
        android:hint="Age"
        android:inputType="textPersonName" />

    <EditText
        android:id="@+id/txtPhone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="219dp"
        android:ems="10"
        android:hint="Phone no"
        android:inputType="textPersonName" />

    <Button
        android:id="@+id/btnSave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="139dp"
        android:text="Save" />

    <Button
        android:id="@+id/BtnList"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="70dp"
        android:text="View" />
</RelativeLayout>

activity_record_list.xml

<RelativeLayout 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"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:padding="10dp"
        android:layout_alignParentLeft="true" />
</RelativeLayout>

row.xml

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    app:cardElevation="3dp"
    app:cardUseCompatPadding="true"
    app:cardCornerRadius="3dp"
    app:cardBackgroundColor="#fff"
    app:contentPadding="5dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_gravity="center">

        <ImageView
            android:id="@+id/imgIcon"
            android:layout_width="100dp"
            android:layout_height="100dp"
            app:srcCompat="@mipmap/ic_launcher_round" />
        <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:text="Name :"
                        android:textSize="20sp"
                        android:textColor="#000"
                        android:textStyle="bold"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"/>
                    <TextView
                        android:id="@+id/textName"
                        android:text="Name here"
                        android:textSize="20sp"
                        android:textColor="#000"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"/>
                </TableRow>
                <TableRow>
                    <TextView
                        android:text="Age :"
                        android:textSize="20sp"
                        android:textColor="#000"
                        android:textStyle="bold"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"/>
                    <TextView
                        android:id="@+id/textAge"
                        android:text="Age here"
                        android:textSize="20sp"
                        android:textColor="#000"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"/>
                </TableRow>
                <TableRow>
                    <TextView
                        android:text="Phone :"
                        android:textSize="20sp"
                        android:textColor="#000"
                        android:textStyle="bold"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"/>
                    <TextView
                        android:id="@+id/textPhone"
                        android:text="Phone here"
                        android:textSize="20sp"
                        android:textColor="#000"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"/>
                </TableRow>
            </TableLayout>
        </LinearLayout>
    </LinearLayout>

</android.support.v7.widget.CardView>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.krish.liteimageview">

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".RecordListActivity"></activity>
    </application>

</manifest>

Я приложу свой короткий экран, вот эта ошибка произошла в моем приложении

Ошибка логпера петлителя

Lopper.java

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...