Why data can't be retrieved from sqlite database in a listview?
Why data can't be retrieved from sqlite database in a listview?
I want to display my all data in a listview from the data added by the sqlite database.When I click on the save button,it is shown a message "Added successfully".But each time it is showing error message "Data not found". Why listview is not displayed?
The error is showing as below :
08-28 14:15:22.861 1442-1666/? E/ConnectivityService: RemoteException caught trying to send a callback msg for NetworkRequest [ LISTEN id=89, [ Capabilities: INTERNET&NOT_RESTRICTED&TRUSTED] ]
08-28 14:15:50.753 17164-17164/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.customadapterwithimage, PID: 17164
android.content.ActivityNotFoundException: No Activity found to handle Intent act=android.intent.action.PICK dat=contents://media/internal/images/media
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1816)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1525)
at android.app.Activity.startActivityForResult(Activity.java:4403)
at android.support.v4.app.BaseFragmentActivityApi16.startActivityForResult(BaseFragmentActivityApi16.java:54)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:68)
at android.app.Activity.startActivityForResult(Activity.java:4361)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:744)
at com.example.user.customadapterwithimage.TraineeListActivity$1.onClick(TraineeListActivity.java:37)
at android.view.View.performClick(View.java:5647)
at android.view.View$PerformClick.run(View.java:22462)
at android.os.Handler.handleCallback(Handler.java:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6361)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at 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 StringManifest.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)
add
TraineeListActivity.java
file in your manifest file– Rahul Chokshi
Aug 28 at 10:58
TraineeListActivity.java
I have added TraineeListActivity.java in manifest.<activity android:name="com.theartofdev.edmodo.cropper.CropImageActivity" android:theme="@style/Base.Theme.AppCompat" /> <activity android:name=".TraineeListActivity"></activity>
– Farzana
Aug 28 at 11:01
I clean your project more info github.com/ArthurHub/Android-Image-Cropper/issues/508
– Rahul Chokshi
Aug 28 at 11:12
Now there is no error but listview is not displaying.Please help
– Farzana
Aug 28 at 11:17
2 Answers
2
Try this you declare adapter before load data from database so data null try as below.
@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;
);
Still I have same problem,no record found!!!
– Farzana
Aug 28 at 11:08
better move cursor to first record before using it.
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();
using cursor.moveToNext()
in while loop may course to skip first record.
cursor.moveToNext()
I have changed the code but still listview can't be displayed
– Farzana
Aug 28 at 17:09
@Farzana please show me MyDatabaseHelper class
– George P J
Aug 29 at 9:28
I have added MyDatabaseHelper.java class .
– Farzana
Aug 30 at 15:09
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
There is problem with you declaring the activity in the manifest. Try posting your android manifest
– Pradeep Kumar
Aug 28 at 10:57