我想从sqlite数据库添加的数据中在listview中显示我的所有数据。当我单击save按钮时,它显示一条消息“added successful”。但每次它都显示错误消息“data not found”。为什么不显示listview?
错误显示如下:
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);
}
}
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;
}
});
}
}
<?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) {
}
}
在从数据库加载数据之前先声明适配器,这样数据为空,按如下方式尝试。
@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;
}
});
}
被一个问题缠住了。我是android开发的新手。我的问题是我有一个SQLite数据库,我正在其中保存映像和一些数据,但当我检索这些数据时,映像没有显示在ListView中。其他数据正在被推翻。 这是我的自定义列表布局 null 这是我的自定义适配器 } 这是activity 这是数据列表
所以我根据YouTube上的教程创建了一个房间数据库。我有两个栏day and likes,每个栏都有int.目前,我已经用三行数据手动填充了数据库。 下面是手动填充数据库的代码: 在我的Dao类中,我当前有Insert、Update、deleteAll和getall...方法。这里是道: } 现在,我要从Room数据库中检索基于当天的数据。所以我想要第6天的likes数,它是1。我想检索数据并将
关于我的上一个问题,我想从创建的sqlite数据库中检索ID,将其作为Intent putExtra()中的数据传递,以便将其用作PendingContent的ID。getActivity()。目前,我正在使用queryNumEntries为从我的DatabaseManager中的以下代码添加到数据库中的每个提醒设置id。类别: 并在AddActivity中调用它。班 在创建条目时,除了尝试此操作
我想从数据库中检索名称。但我总是收到错误: 数据库Java语言 它不断返回错误 android.database.CursorIndexOutOfBoundsException:请求索引-1,大小为1,字符串名称=helper.getProductNameT(cur); 有人知道我的编码哪里出错了吗?
我正在两个标记之间画一条路线,我想保存那条路线。为此,我将包含lat和lng的ArrayList保存在Firebase数据库中。但我在取回航路点时遇到了问题。我是这样插入的: 在检索数据时,我尝试执行以下操作:
问题内容: 我正在制作一个程序,可以从我创建的数据库中检索字段的输入数据/值。但是,当我运行它时,输出始终为null。不知道怎么了 这是我的代码: 在我的主班我有以下代码: 我不知道为什么我运行它时总是说null。 问题答案: 您实际上并没有在设置员中“设置”任何东西。 最重要的是:我对getter和setter的理解使您可以在getter中进行查询。