为什么无法在列表视图中从sqlite数据库检索数据?

时间:2018-08-28 10:50:43

标签: android sqlite listview

我想从sqlite数据库添加的数据中以列表视图显示我的所有数据。当我单击保存按钮时,显示消息“添加成功”。但是每次显示错误消息“数据”未找到”。为什么不显示列表视图?

错误显示如下:

  

08-28 14:15:22.861 1442-1666 /? E / ConnectivityService:RemoteException异常,试图为NetworkRequest发送回调消息[LISTEN id = 89,[功能:INTERNET&NOT_RESTRICTED&TRUSTED]]               08-28 14:15:50.753 17164-17164 /? E / AndroidRuntime:致命异常:main                   流程:com.example.user.customadapterwithimage,PID:17164                   android.content.ActivityNotFoundException:找不到用于处理Intent的活动{act = android.intent.action.PICK dat = contents:// media / internal / images / media}                       在android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1816)                       在android.app.Instrumentation.execStartActivity(Instrumentation.java:1525)                       在android.app.Activity.startActivityForResult(Activity.java:4403)                       在android.support.v4.app.BaseFragmentActivityApi16.startActivityForResult(BaseFragmentActivityApi16.java:54)                       在android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:68)                       在android.app.Activity.startActivityForResult(Activity.java:4361)                       在android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:744)                       在com.example.user.customadapterwithimage.TraineeListActivity $ 1.onClick(TraineeListActivity.java:37)                       在android.view.View.performClick(View.java:5647)                       在android.view.View $ PerformClick.run(View.java:22462)                       在android.os.Handler.handleCallback(Handler.java:754)                       在android.os.Handler.dispatchMessage(Handler.java:95)                       在android.os.Looper.loop(Looper.java:163)                       在android.app.ActivityThread.main(ActivityThread.java:6361)                       在java.lang.reflect.Method.invoke(本机方法)                       在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:904)                       在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)

MainActivity.java

package com.example.user.finalprojectsqlite;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
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 {

    private static final int REQUEST_CODE_GALLERY=999;
    MyDatabaseHelper myDatabaseHelper;

    private EditText nameET,ageET,phnET,idET;
    private Button saveBT,showBT;
    private ImageView newTraineeIV;

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

        nameET=findViewById(R.id.nameET);
        ageET=findViewById(R.id.ageET);
        phnET=findViewById(R.id.phoneET);


        saveBT=findViewById(R.id.saveBtn);
        showBT=findViewById(R.id.displayBtn);

        myDatabaseHelper=new MyDatabaseHelper(this);
        myDatabaseHelper.queryData(MyDatabaseHelper.CREATE_TABLE_TRAINEE);


        newTraineeIV=findViewById(R.id.add_img);

        newTraineeIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        REQUEST_CODE_GALLERY);

            }
        });
        saveBT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                try{
                    myDatabaseHelper.insertTrainee(
                            nameET.getText().toString().trim(),
                            ageET.getText().toString().trim(),
                            phnET.getText().toString().trim(),
                            imageViewToByte(newTraineeIV)
                    );
                    Toast.makeText(MainActivity.this,"Added successfully",Toast.LENGTH_SHORT).show();
                    nameET.setText(" ");
                    ageET.setText(" ");
                    phnET.setText(" ");
                    newTraineeIV.setImageResource(R.drawable.add_img);
                }
                catch (Exception e){
                    e.printStackTrace();


                }

            }
        });

        showBT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent traineeIntent=new Intent(MainActivity.this,TraineeListActivity.class);
                startActivity(traineeIntent);

            }
        });
    }

    public static byte[] imageViewToByte(ImageView image) {
        Bitmap bitmap=((BitmapDrawable)image.getDrawable()).getBitmap();
        ByteArrayOutputStream stream=new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG,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){
                //gallery insert
                Intent galleryIntent=new Intent(Intent.ACTION_GET_CONTENT);
                galleryIntent.setType("image/*");
                startActivityForResult(galleryIntent,REQUEST_CODE_GALLERY);
            }else {
                Toast.makeText(this,"Don't have permission to access file",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){
            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();
                newTraineeIV.setImageURI(resultUri);
            }
            else if(resultCode==CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE){
                Exception err=result.getError();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}

TraineeListActivity.java:

package com.example.user.finalprojectsqlite;

import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
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 TraineeListActivity extends AppCompatActivity {

    ListView mListView;
    ArrayList<TraineeModel> mList;
    TraineeListAdapter mAdapter = null;
    MyDatabaseHelper myDatabaseHelper;

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

        myDatabaseHelper = new MyDatabaseHelper(this);

        mListView = findViewById(R.id.traineeList);
        mList = new ArrayList<>();
        mAdapter = new TraineeListAdapter(this, R.layout.trainee_row, mList);
        mListView.setAdapter(mAdapter);

        //get all data
        Cursor cursor = myDatabaseHelper.getData("SELECT * FROM trainee");
        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 listrayLis
            mList.add(new TraineeModel(id, name, age, phone, image));
        }
        mAdapter.notifyDataSetChanged();
        if (mList.size() == 0) {
            //if no record in db
            Toast.makeText(TraineeListActivity.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;
            }
        });
    }
}

trainee_list_activity.xml:

<?xml version="1.0" encoding="utf-8"?>
<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:cardBackgroundColor="#71d4c7"
    app:contentPadding="5dp">

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

        <ImageView
            android:id="@+id/traineeIcon"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:src="@mipmap/ic_launcher_round"/>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:layout_marginLeft="5dp">
        <TableLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <TableRow>
                <TextView
                    android:textStyle="bold"
                    android:text="Name :"
                    android:textAllCaps="false"
                    android:textSize="20sp"
                    android:layout_height="wrap_content"
                    android:layout_width="match_parent"

                    />
                <TextView
                    android:id="@+id/traineeNameText"
                    android:textStyle="normal"
                    android:text="Name here"
                    android:textAllCaps="false"
                    android:textSize="20sp"
                    android:layout_height="wrap_content"
                    android:layout_width="match_parent"

                    />
            </TableRow>
            <TableRow>
                <TextView
                    android:textStyle="bold"
                    android:text="Age :"
                    android:textAllCaps="false"
                    android:textSize="20sp"
                    android:layout_height="wrap_content"
                    android:layout_width="match_parent"

                    />
                <TextView
                    android:id="@+id/traineeAgeText"
                    android:textStyle="normal"
                    android:text="Age here"
                    android:textAllCaps="false"
                    android:textSize="20sp"
                    android:layout_height="wrap_content"
                    android:layout_width="match_parent"

                    />
            </TableRow>
            <TableRow>
                <TextView
                    android:textStyle="bold"
                    android:text="Phone no :"
                    android:textAllCaps="false"
                    android:textSize="20sp"
                    android:layout_height="wrap_content"
                    android:layout_width="match_parent"

                    />
                <TextView
                    android:id="@+id/traineePhnText"
                    android:textStyle="normal"
                    android:text="Phone no here"
                    android:textAllCaps="false"
                    android:textSize="20sp"
                    android:layout_height="wrap_content"
                    android:layout_width="match_parent"

                    />
            </TableRow>

        </TableLayout>

        </LinearLayout>

    </LinearLayout>

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

MyDatabaseHelper.java

package com.example.user.finalprojectsqlite;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;

public class MyDatabaseHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME="Gymnesium";
    private static final String TRAINEE_TABLE_NAME="trainee";
    private static final int VERSION_NUMBER=1;

    static final String CREATE_TABLE_TRAINEE= "CREATE TABLE IF NOT EXISTS "+TRAINEE_TABLE_NAME+"(id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, age VARCHAR, phone VARCHAR, traineeimg BLOB)";

    public MyDatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, VERSION_NUMBER);
    }



    public void queryData(String sql){
        SQLiteDatabase sqLiteDatabase=getWritableDatabase();
        sqLiteDatabase.execSQL(sql);
    }
    public void insertTrainee(String name,String age,String phone,byte[] traineeimg)
    {
        SQLiteDatabase sqLiteDatabase=getWritableDatabase();
        String sql="INSERT INTO trainee VALUES(NULL, ?, ?, ?, ?)";
        SQLiteStatement statement=sqLiteDatabase.compileStatement(sql);
        statement.clearBindings();

        statement.bindString(1,name);
        statement.bindString(2,age);
        statement.bindString(3,phone);
        statement.bindBlob(4,traineeimg);

        statement.executeInsert();

    }
    public void updateData(String name,String age,String phone,byte[] traineeimg,int id)
    {
        SQLiteDatabase sqLiteDatabase=getWritableDatabase();

        String sql="UPDATE trainee SET name=?, age=?, phone=?, traineeimg=? WHERE id=?";
        SQLiteStatement statement=sqLiteDatabase.compileStatement(sql);

        statement.bindString(1,name);
        statement.bindString(2,age);
        statement.bindString(3,phone);
        statement.bindBlob(4,traineeimg);
        statement.bindDouble(5,(double) id);

        statement.execute();
        sqLiteDatabase.close();

    }
    public void deleteTrainee(int id){
        SQLiteDatabase sqLiteDatabase=getWritableDatabase();
        String sql="DELETE FROM trainee WHERE id=?";

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

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

    public Cursor getData(String sql){
        SQLiteDatabase sqLiteDatabase=getReadableDatabase();
        return  sqLiteDatabase.rawQuery(sql,null);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

}

2 个答案:

答案 0 :(得分:0)

尝试此操作,以便在从数据库加载数据之前声明适配器,因此数据null尝试如下。

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

    myDatabaseHelper = new MyDatabaseHelper(this);

    mListView = findViewById(R.id.traineeList);
    mList = new ArrayList<>();


    //get all data
    Cursor cursor = myDatabaseHelper.getData("SELECT * FROM trainee");
    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 listrayLis
        mList.add(new TraineeModel(id, name, age, phone, image));
    }
   mAdapter = new TraineeListAdapter(this, R.layout.trainee_row, mList);
    mListView.setAdapter(mAdapter);
    mAdapter.notifyDataSetChanged();
    if (mList.size() == 0) {
        //if no record in db
        Toast.makeText(TraineeListActivity.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;
        }
    });
}

答案 1 :(得分:0)

在使用光标之前,最好将光标移动到第一条记录。

    if (cursor !=null && cursor.getCount() != 0 && cursor.moveToFirst()) {
    do {
            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 listrayLis
            mList.add(new TraineeModel(id, name, age, phone, image));
        }while (cursor.moveToNext());

    }

    if (cursor !=null){
       cursor.close();
      }

在while循环中使用cursor.moveToNext()可能会跳过第一条记录。