Display image from sqlite in listview? - android

i am working on small project. I inserted .sqlite database file in assets folder and getting information in listview. Now i have to display image with text. I created imageview in xml file, then add some function in my code. But it doesn't work. Here is source.
MainActivity.java
package com.example.arlequina.sqlitefromassetexample;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;
import com.example.arlequina.sqlitefromassetexample.adapter.ListProductAdapter;
import com.example.arlequina.sqlitefromassetexample.database.DatabaseHelper;
import com.example.arlequina.sqlitefromassetexample.model.Product;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
/**
* Created by ARLEQUINA on 2/10/2017.
*/
public class MainActivity extends Activity {
private ListView lvProduct;
private ListProductAdapter adapter;
private List<Product> mProductList;
private DatabaseHelper mDBHelper;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvProduct = (ListView)findViewById(R.id.listview_product);
mDBHelper = new DatabaseHelper(this);
//Check exists database
File database = getApplicationContext().getDatabasePath(DatabaseHelper.dbname);
if(false == database.exists()){
mDBHelper.getReadableDatabase();
//Copy db
if(copyDatabase(this)){
Toast.makeText(this,"Copy database success", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "Copy data error", Toast.LENGTH_SHORT).show();
return;
}
}
//Get product list in db when db exists
mProductList = mDBHelper.getListProduct();
//Init adapter
adapter = new ListProductAdapter(this,mProductList);
//Set adapter for listview
lvProduct.setAdapter(adapter);
}
private boolean copyDatabase(Context context){
try{
InputStream inputStream = context.getAssets().open(DatabaseHelper.dbname);
String outFileName = DatabaseHelper.dblocation + DatabaseHelper.dbname;
OutputStream outputStream = new FileOutputStream(outFileName);
byte[] buff = new byte[1024];
int length = 0;
while((length = inputStream.read(buff)) > 0){
outputStream.write(buff, 0, length);
}
outputStream.flush();
outputStream.close();
Log.v("MainActivity", "DB copied");
return true;
} catch(Exception e){
e.printStackTrace();
return false;
}
}
}
Product.java
package com.example.arlequina.sqlitefromassetexample.model;
import java.sql.Blob;
/**
* Created by ARLEQUINA on 2/10/2017.
*/
public class Product {
private int id;
private String name;
private String price;
private String desc;
private Blob img;
public Product(int id, String name, String price, String desc, Blob img){
this.id = id;
this.name = name;
this.price = price;
this.desc = desc;
this.img = img;
}
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 getPrice(){
return price;
}
public void setPrice(String price){
this.price = price;
}
public String getDesc(){
return desc;
}
public void setDesc(){
this.desc = desc;
}
public Blob getImage(){
return img;
}
public void setImage(Blob img){
this.img = img;
}
}
DatabaseHelper.java
package com.example.arlequina.sqlitefromassetexample.database;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.example.arlequina.sqlitefromassetexample.model.Product;
import java.util.ArrayList;
import java.util.List;
import java.sql.Blob;
/**
* Created by ARLEQUINA on 2/10/2017.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String dbname = "sample.db";
public static final String dblocation = "/data/data/com.example.arlequina.sqlitefromassetexample/databases/";
private Context mContext;
private SQLiteDatabase mDatabase;
public DatabaseHelper(Context context){
super(context, dbname, null, 1);
this.mContext = context;
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public void openDatabase(){
String dbPath = mContext.getDatabasePath(dbname).getPath();
if(mDatabase != null && mDatabase.isOpen()){
return;
}
mDatabase = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READWRITE);
}
public void closeDatabase(){
if(mDatabase != null){
mDatabase.close();
}
}
public List<Product> getListProduct(){
Product product = null;
List<Product> productList = new ArrayList<>();
openDatabase();
Cursor cursor = mDatabase.rawQuery("SELECT * FROM Product", null);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
product = new Product(cursor.getInt(0), cursor.getString(1), cursor.getString(2),cursor.getString(3),cursor.getBlob(4));
productList.add(product);
cursor.moveToNext();
}
cursor.close();
closeDatabase();
return productList;
}
}
ListProductAdapter.java
package com.example.arlequina.sqlitefromassetexample.adapter;
import android.content.Context;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.arlequina.sqlitefromassetexample.R;
import com.example.arlequina.sqlitefromassetexample.model.Product;
import org.w3c.dom.Text;
import java.util.List;
/**
* Created by ARLEQUINA on 2/10/2017.
*/
public class ListProductAdapter extends BaseAdapter{
private Context mContext;
private List<Product> mProductList;
public ListProductAdapter(Context mContext, List<Product> mProductList){
this.mContext = mContext;
this.mProductList = mProductList;
}
#Override
public int getCount() {
return mProductList.size();
}
#Override
public Object getItem(int position) {
return mProductList.get(position);
}
#Override
public long getItemId(int position) {
return mProductList.get(position).getId();
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
View v = View.inflate(mContext, R.layout.item_listview, null);
TextView tvName = (TextView)v.findViewById(R.id.tv_product_name);
TextView tvPrice = (TextView)v.findViewById(R.id.tv_product_price);
TextView tvDesc = (TextView)v.findViewById(R.id.tv_product_desc);
ImageView tvImage = (ImageView)v.findViewById(R.id.tv_product_img);
tvName.setText(mProductList.get(position).getName());
tvPrice.setText(String.valueOf(mProductList.get(position).getPrice()) + " $");
tvDesc.setText(mProductList.get(position).getDesc());
// tvImage.setImageIcon(mProductList.get(position).getImage());
return v;
}
}
item_listview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:paddingBottom="5dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tv_product_name"
android:text = "Name"
android:textColor="#4bb6d6"
android:textSize="20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id = "#+id/tv_product_price"
android:text="100$"
android:textColor="#b30000"
android:textSize="18dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id = "#+id/tv_product_desc"
android:text="Description"
android:textSize="16dp"
android:textStyle="italic"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id = "#+id/tv_product_img"
android:layout_gravity="right"
android:paddingRight="10dp"
android:paddingBottom="10dp"/>
</LinearLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#d1d1d1">
<ListView
android:id = "#+id/listview_product"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:divider="#d1d1d1"
android:dividerHeight="10dp"></ListView>
</LinearLayout>
And here is image of sqlite database attached file picture.
enter image description here
Here is database source. database name is "sample", and table product.
CREATE TABLE `Product` (
`ID` INTEGER PRIMARY KEY AUTOINCREMENT,
`Name` TEXT,
`Price` TEXT,
`Desc` TEXT,
`Image` BLOB
);

cursor.getBlob() returns a byte[] array, use BitmapFactory.decodeByteArray() method to convert byte array to an image . In your Product.java change the img type from Blob to byte[]. Here's a link to official documentation.

Related

Retrieve data from SQLite in RecyclerView inside fragment

I have an activity that contain custom Tablayout.
the Tablayot has pageViewer and link to a fragment.
I want to show data from my SQLite database in RecyclerView in fragment.
this is my codes:
DatabaseHelper.java:
package ir.shirazmetro;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String TAG = "DatabaseHelper";
public static final String DATABASE_NAME = "MetroDB.db";
public static final String TABLE_NAME = "estation";
public static final String COL_1 = "station";
public static final String COL_2 = "time";
public static final String COL_3 = "line";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (COL_1,COL_2,COL_3)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String station, String time, String line) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, time);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1)
return false;
else
return true;
}
public Cursor getData() {
SQLiteDatabase db = this.getWritableDatabase();
return db.rawQuery("select "+COL_2+" from " + TABLE_NAME, null);
}
}
My activity(station.java):
package ir.shirazmetro.views.activities;
import android.content.Intent;
import android.support.v4.view.ViewPager;
import android.support.design.widget.TabLayout;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
import ir.shirazmetro.DatabaseHelper;
import ir.shirazmetro.R;
import ir.shirazmetro.other.components.ButtonCell;
import ir.shirazmetro.other.components.TextViewCell;
import ir.shirazmetro.views.adapters.BasePagerAdapter;
import ir.shirazmetro.views.adapters.MoviesAdapter;
public class estation extends BaseActivity {
Toolbar mToolbar;
private TabLayout tbLayout;
private ViewPager vPager;
private List<DatabaseHelper> movies = new ArrayList<DatabaseHelper>();
private RecyclerView recyclerView;
private MoviesAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_estation);
mToolbar = findViewById(R.id.tlbr1);
setSupportActionBar(mToolbar);
initView();
setupWithViewPager();
tbLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
recyclerView = findViewById(R.id.myRecycler);
adapter = new MoviesAdapter(movies);
recyclerView.setLayoutManager(new LinearLayoutManager(estation.this));
recyclerView.setAdapter(adapter);
DatabaseHelper getData = (DatabaseHelper) new DatabaseHelper(this).getData();
movies.add(getData);
adapter.notifyDataSetChanged();
}
}
private void setupWithViewPager() {
BasePagerAdapter basePagerAdapter = new BasePagerAdapter(this, getSupportFragmentManager());
vPager.setAdapter(basePagerAdapter);
tbLayout.setupWithViewPager(vPager);
}
private void initView() {
vPager = findViewById(R.id.view_pager);
tbLayout = findViewById(R.id.tab_layout);
backBtn = findViewById(R.id.backBtn);
backBtn.setOnClickListener((View.OnClickListener) this);
}
}
and this code is my Adapter:
package ir.shira.views.adapters;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
import ir.shira.DatabaseHelper;
import ir.shira.R;
import ir.shira.models.movie;
public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MovieViewHolder> {
private List<movie> movies;
private Context context;
public MoviesAdapter(List<DatabaseHelper> movies) {
movies = movies;
}
#NonNull
#Override
public MovieViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_to_dastgheyb,parent,false);
return new MovieViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MovieViewHolder holder, int position) {
holder.txtTime.setText(movies.get(position).getTime());
}
#Override
public int getItemCount() {
return movies.size();
}
public class MovieViewHolder extends RecyclerView.ViewHolder
{
public TextView txtTime;
public MovieViewHolder(View itemView)
{
super(itemView);
txtTime = itemView.findViewById(R.id.textView);
}
}
}
my app crash when I run the project, any ideas?
movies.get(position).getTime() retrieve DatabaseHelper, I think it is checked exception.
You are making mistake hear
When You creating List Obj.
private List<DatabaseHelper> movies = new ArrayList<DatabaseHelper>();
//.. List Type DatabaseHelper But You want movie ? so change this line to like this
private List<movie> movies = new ArrayList<movie>();
//movie is your model

AS how to setOnClickListener in listview item from assets database file

i want to ask about OnClickListener. I called external database file[assets folder] in listview. I want to set onClicklistener at each item in listview. When listview item clicks, wanna appear a little fragment with data fields.I tried many sources but still not working.
Here is example fragment want to do.
enter image description here
Here is database structure.
enter image description here
Here is DatabaseHelper.java
package com.example.arlequina.sqlitefromassetexample.database;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.example.arlequina.sqlitefromassetexample.model.Product;
import java.util.ArrayList;
import java.util.List;
import java.sql.Blob;
/**
* Created by ARLEQUINA on 2/10/2017.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String dbname = "sample.db";
public static final String dblocation = "/data/data/com.example.arlequina.sqlitefromassetexample/databases/";
private Context mContext;
private SQLiteDatabase mDatabase;
public DatabaseHelper(Context context){
super(context, dbname, null, 1);
this.mContext = context;
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public void openDatabase(){
String dbPath = mContext.getDatabasePath(dbname).getPath();
if(mDatabase != null && mDatabase.isOpen()){
return;
}
mDatabase = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READWRITE);
}
public void closeDatabase(){
if(mDatabase != null){
mDatabase.close();
}
}
public List<Product> getListProduct(){
Product product = null;
List<Product> productList = new ArrayList<>();
openDatabase();
Cursor cursor = mDatabase.rawQuery(" SELECT * FROM Product ", null);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
product = new Product(cursor.getInt(0), cursor.getString(1), cursor.getString(2),cursor.getString(3));
productList.add(product);
cursor.moveToNext();
}
cursor.close();
closeDatabase();
return productList;
}
}
Here is ListProductAdapter.java
package com.example.arlequina.sqlitefromassetexample.adapter;
import android.content.Context;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.arlequina.sqlitefromassetexample.R;
import com.example.arlequina.sqlitefromassetexample.model.Product;
import org.w3c.dom.Text;
import java.util.List;
/**
* Created by ARLEQUINA on 2/10/2017.
*/
public class ListProductAdapter extends BaseAdapter{
private Context mContext;
private List<Product> mProductList;
public ListProductAdapter(Context mContext, List<Product> mProductList){
this.mContext = mContext;
this.mProductList = mProductList;
}
#Override
public int getCount() {
return mProductList.size();
}
#Override
public Object getItem(int position) {
return mProductList.get(position);
}
#Override
public long getItemId(int position) {
return mProductList.get(position).getId();
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
View v = View.inflate(mContext, R.layout.item_listview, null);
TextView tvName = (TextView)v.findViewById(R.id.tv_product_name);
TextView tvPrice = (TextView)v.findViewById(R.id.tv_product_price);
TextView tvDesc = (TextView)v.findViewById(R.id.tv_product_desc);
//ImageView tvImage = (ImageView)v.findViewById(R.id.tv_product_img);
tvName.setText(mProductList.get(position).getName());
tvPrice.setText(String.valueOf(mProductList.get(position).getPrice()) + " $");
tvDesc.setText(mProductList.get(position).getDesc());
// tvImage.setImageIcon(mProductList.get(position).getImage());
return v;
}
}
Here is MainActivity
package com.example.arlequina.sqlitefromassetexample;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.arlequina.sqlitefromassetexample.adapter.ListProductAdapter;
import com.example.arlequina.sqlitefromassetexample.database.DatabaseHelper;
import com.example.arlequina.sqlitefromassetexample.model.Product;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
/**
* Created by ARLEQUINA on 2/10/2017.
*/
public class MainActivity extends Activity {
private ListView lvProduct;
private ListProductAdapter adapter;
private List<Product> mProductList;
private DatabaseHelper mDBHelper;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvProduct = (ListView)findViewById(R.id.listview_product);
mDBHelper = new DatabaseHelper(this);
//Check exists database
File database = getApplicationContext().getDatabasePath(DatabaseHelper.dbname);
if(false == database.exists()){
mDBHelper.getReadableDatabase();
//Copy db
if(copyDatabase(this)){
Toast.makeText(this,"Copy database success", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "Copy data error", Toast.LENGTH_SHORT).show();
return;
}
}
//Get product list in db when db exists
mProductList = mDBHelper.getListProduct();
//Init adapter
adapter = new ListProductAdapter(this,mProductList);
//Set adapter for listview
lvProduct.setAdapter(adapter);
}
private boolean copyDatabase(Context context){
try{
InputStream inputStream = context.getAssets().open(DatabaseHelper.dbname);
String outFileName = DatabaseHelper.dblocation + DatabaseHelper.dbname;
OutputStream outputStream = new FileOutputStream(outFileName);
byte[] buff = new byte[1024];
int length = 0;
while((length = inputStream.read(buff)) > 0){
outputStream.write(buff, 0, length);
}
outputStream.flush();
outputStream.close();
Log.v("MainActivity", "DB copied");
return true;
} catch(Exception e){
e.printStackTrace();
return false;
}
}
}
item_listview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:paddingBottom="5dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tv_product_name"
android:text = "Name"
android:textColor="#4bb6d6"
android:textSize="20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id = "#+id/tv_product_price"
android:text="100$"
android:textColor="#b30000"
android:textSize="18dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id = "#+id/tv_product_desc"
android:text="Description"
android:textSize="16dp"
android:textStyle="italic"/>
</LinearLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#d1d1d1">
<ListView
android:id = "#+id/listview_product"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:divider="#d1d1d1"
android:dividerHeight="10dp"></ListView>
</LinearLayout>
Product.java
package com.example.arlequina.sqlitefromassetexample.model;
import java.sql.Blob;
/**
* Created by ARLEQUINA on 2/10/2017.
*/
public class Product {
private int id;
private String name;
private String price;
private String desc;
//private Blob img;
public Product(int id, String name, String price, String desc){
this.id = id;
this.name = name;
this.price = price;
this.desc = desc;
//this.img = img;
}
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 getPrice(){
return price;
}
public void setPrice(String price){
this.price = price;
}
public String getDesc(){
return desc;
}
public void setDesc(String desc){
this.desc = desc;
}
}
Since your problem is make your list item clickable, you can use this after init listview in activity.
lvProduct.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
position is position of that clicked item in list. So you can get that item using mProductList.get(position)
After you can get that item, now it's time to show your item up. You can use custom dialog to make it like your demo (of cause you have to create 1 more xml):
Check section Custom Dialog in this official link: https://developer.android.com/guide/topics/ui/dialogs.html
You can use listview.setOnItemClickListener or v.setOnClickListener to solve your problem.That is the most basic ,man.

Not getting the number after decimal point in android

I'm a new in android.I tried to take the floating value in edittext and store it on the database. Then i got the total number of those stored value. But i'm not getting the value after the decimal point.
Here is my code...
package com.example.usaukglu.tablayoyt;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Income extends AppCompatActivity implements View.OnClickListener {
TextView amount, payer, note, show;
EditText edi_amount, payer_name, edit_note;
Button save, cancel;
DatabaseHandler db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_income);
save = (Button) findViewById(R.id.save);
cancel = (Button) findViewById(R.id.cancel);
amount = (TextView) findViewById(R.id.amount);
payer = (TextView) findViewById(R.id.payer);
note = (TextView) findViewById(R.id.note);
show = (TextView) findViewById(R.id.show);
edi_amount = (EditText) findViewById(R.id.edit_amount);
payer_name = (EditText) findViewById(R.id.edit_payer);
edit_note = (EditText) findViewById(R.id.edit_note);
//date= (EditText) findViewById(R.id.date);
db = new DatabaseHandler(this);
save.setOnClickListener(this);
cancel.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.save) {
String amounts,payers,notes;
amounts=edi_amount.getText().toString();
payers= payer_name.getText().toString();
notes= edit_note.getText().toString();
if(amounts.isEmpty())
{
edi_amount.setError("Amounts should not be blank");
}
else if (payers.isEmpty()){
payer_name.setError("Payer name should not be blank");
}
else {
Double a =new Double(amounts);
DataProvider provider = new DataProvider(""+a, payers, notes);
db.addInformation(provider);
Intent i = new Intent(this, MainActivity.class);
startActivity(i);
}
}
if (view.getId() == R.id.cancel) {
Intent i =new Intent(this,MainActivity.class);
startActivity(i);
}
}
public void show(String data) {
show.setText(data);
}
}
Here is the dataProvider class:
package com.example.usaukglu.tablayoyt;
public class DataProvider {
private String money;
private String name;
private String desc;
public DataProvider(String money, String name, String desc) {
this.money = money;
this.name = name;
this.desc = desc;
}
public String getMoney() {
return money;
}
public void setMoney(String money) {
this.money = money;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
DatabaseHandler Class:
package com.example.usaukglu.tablayoyt;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import static com.example.usaukglu.tablayoyt.R.id.amount;
import static com.example.usaukglu.tablayoyt.R.id.note;
import static com.example.usaukglu.tablayoyt.R.id.payer;
public class DatabaseHandler extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "income.db";
public static final String TABLE_NAME = "income_table";
public static final String ID="id";
public static final String AMOUNT = "amount";
public static final String PAYER_NAME = "payer";
public static final String NOTE = "note";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String query = "CREATE TABLE " + TABLE_NAME +
"(" +ID+ " integer primary key autoincrement, " + AMOUNT + " real, " + PAYER_NAME + " text, " + NOTE + " text " + ")";
sqLiteDatabase.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(sqLiteDatabase);
}
public void addInformation(DataProvider provider){
SQLiteDatabase db = getWritableDatabase();
ContentValues values=new ContentValues();
values.put(AMOUNT,provider.getMoney());
values.put(PAYER_NAME,provider.getName());
values.put(NOTE,provider.getDesc());
db.insert(TABLE_NAME, null, values);
db.close();
}
public Cursor display()
{
SQLiteDatabase sqLiteDatabase=getReadableDatabase();
Cursor res= sqLiteDatabase.rawQuery("SELECT * FROM "+TABLE_NAME,null);
return res;
}
public double getTotalOfAmount() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT SUM(AMOUNT) FROM " + TABLE_NAME, null);
c.moveToFirst();
double i = c.getInt(0);
c.close();
return i;
}
}
FragmentIncome class whre i want o show the data:
package com.example.usaukglu.tablayoyt;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class FragmentIncome extends Fragment {
ListView list;
private DatabaseHandler handler;
private SQLiteDatabase database;
private List<DataProvider> amountList;
private ListDataAdaptar listDataAdaptar;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.fragment_income,container,false);
list=(ListView) view.findViewById(R.id.listView);
amountList=new ArrayList<>();
handler=new DatabaseHandler(getContext());
database=handler.getReadableDatabase();
Cursor cursor=handler.display();
if(cursor.moveToFirst()){
do {
String amount,payer,note;
amount= cursor.getString(cursor.getColumnIndex(handler.AMOUNT));
payer=cursor.getString(cursor.getColumnIndex(handler.PAYER_NAME));
note=cursor.getString(cursor.getColumnIndex(handler.NOTE));
DataProvider provider=new DataProvider(amount,payer,note);
amountList.add(provider);
listDataAdaptar=new ListDataAdaptar(getContext(),R.layout.display_income_row,amountList);
list.setAdapter(listDataAdaptar);
}while (cursor.moveToNext());
}
return view;
}
}
You are using String variables in your database.Use float datatype in your tables to run a SUM query.
Your DataProvider class should be like this-
public class DataProvider {
private Float money;
private String name;
private String desc;
public DataProvider(Float money, String name, String desc) {
this.money = money;
this.name = name;
this.desc = desc;
}
public Float getMoney() {
return money;
}
public void setMoney(Float money) {
this.money = money;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}

i am getting an error while calling a method and storing its object [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm trying to create an activity where i can select a particular row from the ListView which is being retrived from the database so that i can manipulate it but when I'm selecting that row my application unfortunately stops.
Here I am getting a android.content.res.Resources$NotFoundException: String resource ID #0x0
While trying to select a row from the database i'm getting an runtime exception.
this is my databasehelper class
databasehelper.java
package com.example.ashwanislaptop.expensemanager;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME="Transaction.db";
public static final String TABLE_NAME="transaction_table";
public static final String COL_1="ID";
public static final String COL_2="PRICE";
public static final String COL_3="DATE";
public static final String COL_4="TIME";
public static final String COL_5="DESCRIPTION";
public static final String COL_6="CATEGORY";
public static final String COL_7="PAYMENT_MODE";
private static final String TAG="DatabaseHelper";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS "+TABLE_NAME+"(ID INTEGER PRIMARY KEY AUTOINCREMENT,PRICE INTEGER NOT NULL,DATE TEXT NOT NULL,TIME TEXT NOT NULL,DESCRIPTION TEXT NOT NULL,CATEGORY TEXT NOT NULL,PAYMENT_MODE TEXT NOT NULL);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS transaction_table");
onCreate(db);
}
void InsertData(Transaction t){
SQLiteDatabase db=getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(COL_2,t.getPrice());
cv.put(COL_3,t.getDate());
cv.put(COL_4,t.getTime());
cv.put(COL_5,t.getDescription());
cv.put(COL_6,t.getCategory());
cv.put(COL_7,t.getPayment_mode());
db.insert(TABLE_NAME,null,cv);
db.close();
}
public ArrayList<Transaction> getAllTransaction() {
SQLiteDatabase db = getReadableDatabase();
Log.i(TAG, "getAllTransaction: getting Transaction Record");
Cursor c = db.rawQuery("Select * From transaction_table", null);
if (c.moveToFirst()) {
ArrayList<Transaction> list = new ArrayList<>();
do {
Transaction t = new Transaction(c.getString(1),c.getString(2), c.getString(5));
list.add(t);
Log.i(TAG, "GetAllTranscRecords: one record retrieved");
}while (c.moveToNext());
return list;
}
else
{
Log.i(TAG,"No record found");
db.close();
return null;
}
}
[getting an runtime error while calling it from the Transaction_Detail.java]
***Transaction getAllTransactionssecond(int idd) {
Log.i(TAG, "getAllTransactionssecond: "+idd);
SQLiteDatabase db = getReadableDatabase();
Log.i(TAG, "getAllTransaction: getting Transaction Record of id "+idd);
Cursor c = db.rawQuery("Select * From transaction_table where id="+idd+";", null);
[The Execution crashes exactly at this point how do i send the data to the Transaction_details so that i can print the data in the textviews]
Transaction t = new Transaction(c.getString(1),c.getString(2),c.getString(3),c.getString(4),c.getString(5),c.getString(6));
Log.i(TAG, "GetAllTranscRecords: one record retrieved");
// Log.i(TAG,"No record found");
db.close();
return t;
}***
public ArrayList<Transaction> getAllTransactioncategorywise(){
SQLiteDatabase db=getReadableDatabase();
Log.i(TAG,"getAllTransaction: getting Transaction Record");
Cursor c=db.rawQuery("Select * From transaction_table order by "+COL_6+";",null);
if(c.moveToFirst()){
ArrayList<Transaction> list=new ArrayList<>();
do{
Transaction t=new Transaction(c.getString(1),c.getString(2),c.getString(5));
list.add(t);
Log.i(TAG,"GetAllTranscRecords: one record retrieved");
}while (c.moveToNext());
return list;
}
else
{
Log.i(TAG,"No record found");
db.close();
return null;
}
}
public ArrayList<Transaction> getAllTransactiondatewise(){
SQLiteDatabase db=getReadableDatabase();
Log.i(TAG,"getAllTransaction: getting Transaction Record");
Cursor c=db.rawQuery("Select * From transaction_table order by "+COL_3+" desc",null);
if(c.moveToFirst()){
ArrayList<Transaction> list=new ArrayList<>();
do{
Transaction t=new Transaction(c.getString(1),c.getString(2),c.getString(5));
list.add(t);
Log.i(TAG,"GetAllTranscRecords: one record retrieved");
}while (c.moveToNext());
return list;
}
else
{
Log.i(TAG,"No record found");
db.close();
return null;
}
}
}
[This is my Transaction Details Class]
transaction detail.java
package com.example.ashwanislaptop.expensemanager;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import java.util.ArrayList;
public class Transaction_Details extends AppCompatActivity {
private TextView txtid,txtprice,txtdate,txttime,txtcateg,txtpayment,txtdecription;
private DatabaseHelper ta;
public static final String TAG="Trasaction detail";
public int sentid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transaction__details);
Log.i(TAG, "onCreate: before intent");
Intent i1=getIntent();
sentid=i1.getIntExtra("STRING",0);
Log.i(TAG, "onCreate: after intent "+sentid);
txtid=(TextView)findViewById(R.id.txtid);
txtdate=(TextView)findViewById(R.id.txtdate);
txttime=(TextView)findViewById(R.id.txttime);
txtcateg=(TextView)findViewById(R.id.txtcateg);
txtpayment=(TextView)findViewById(R.id.txtpayment);
txtdecription=(TextView)findViewById(R.id.txtdescription);
ta=new DatabaseHelper(this);
[ I'm able to retrieve the data]
**Transaction details=ta.getAllTransactionssecond(sentid);**
txtid.setText(details.getId());
txtdate.setText(details.getDate());
txttime.setText(details.getTime());
txtcateg.setText(details.getCategory());
txtprice.setText(details.getPrice());
txtpayment.setText(details.getPayment_mode());
txtdecription.setText(details.getDescription());
}
}
Transaction.java
package com.example.ashwanislaptop.expensemanager;
public class Transaction {
private int id;
private String price,date,time,description,category,payment_mode;
public Transaction() {
}
public Transaction(int id, String price, String date, String time, String description, String category, String payment_mode) {
this.id = id;
this.price = price;
this.date = date;
this.time = time;
this.description = description;
this.category = category;
this.payment_mode = payment_mode;
}
public Transaction(String price, String date, String time, String description, String category, String payment_mode) {
this.price = price;
this.date = date;
this.time = time;
this.description = description;
this.category = category;
this.payment_mode = payment_mode;
}
public Transaction(String price, String date, String category) {
this.category = category;
this.date = date;
this.price = price;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getPayment_mode() {
return payment_mode;
}
public void setPayment_mode(String payment_mode) {
this.payment_mode = payment_mode;
}
}
[This is my AllTransaction Class]
AllTansactionFragment.java
package com.example.ashwanislaptop.expensemanager;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Created by Welcome on 06-Aug-16.
*/
public class AllTransactionFragment extends Fragment {
private static final String TAG="AllTransactionFragment";
private ListView listView;
private DatabaseHelper ta=null;
//private ArrayAdapter<String> aa=null;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View vu=inflater.inflate(R.layout.alltransactionlistview,container,false);
listView=(ListView)vu.findViewById(R.id.lvtransaction);
ta=new DatabaseHelper(getActivity());
Log.i(TAG, "onCreateView:"+ta);
ArrayList<Transaction> list=ta.getAllTransactiondatewise();
Collections.sort(list, new Comparator<Transaction>() {
#Override
public int compare(Transaction t1, Transaction t2) {
SimpleDateFormat dateFormat=new SimpleDateFormat("dd-mm-yyyy");
if(t1.getDate()==null || t2.getDate()==null)
return 0;
return t1.getDate().compareTo(t2.getDate());
}
});
TransactionListAdapter aa=new TransactionListAdapter(getActivity(),list);
listView.setAdapter(aa);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Log.i(TAG, " onItemClick: ");
Toast.makeText(getActivity(),"Clicked on:"+i,Toast.LENGTH_SHORT).show();
Intent ii=new Intent(getActivity(),Transaction_Details.class);
ii.putExtra("STRING",i);
Log.i(TAG, "onItemClick: after");
startActivity(ii);
}
});
return vu;
}
}
Initialize your DatabaseHelper. It is null.

how get value of textview (with currentview ) with viewpager?

how get value of textview (with currentview ) in viewpager?
Problem
i gettext of textview but now current showing textview its gee=ttingtext of next view's textview
class Test
package "name";
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by name on 26-Mar-16.
*/
public class Test extends Activity {
private static final String DB_NAME = "";
private static final String TABLE_NAME = "";
private SQLiteDatabase database;
private List<String> testContactName = new ArrayList<>();
public MyAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
ViewPager mViewPager = (ViewPager) findViewById(R.id.testvp);
mAdapter = new MyAdapter();
mViewPager.setAdapter(mAdapter);
mViewPager.setCurrentItem(0);
mViewPager.setOffscreenPageLimit(50);
getAllContacts();
}
public void getAllContacts() {
DatabaseHelper dbOpenHelper = new DatabaseHelper(this, DB_NAME);
database = dbOpenHelper.openDataBase();
String query = "select * from " + TABLE_NAME;
Cursor cursor = database.rawQuery(query, null);
if (cursor != null) {
cursor.moveToFirst();
for (int c = 0; c < cursor.getCount(); c++) {
String name = cursor.getString(cursor.getColumnIndex("content"));
cursor.moveToNext();
/* String count= String.valueOf(cursor.getCount());
Toast.makeText(getApplicationContext(), count , Toast.LENGTH_LONG).show();*/
testContactName.add(name);
// testContactName.notifyAll();
Log.i("Name: " + "" + "---", name);
}mAdapter.notifyDataSetChanged();
}
cursor.close();
}
private class MyAdapter extends PagerAdapter {
public MyAdapter() {
super();
}
#Override
public int getCount() {
return testContactName.size();
}
#Override
public boolean isViewFromObject(View collection, Object object) {
return object == collection;
}
#Override
public Object instantiateItem(ViewGroup collection, int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.test1, null);
TextView pagenumber;
pagenumber = (TextView) view.findViewById(R.id.tv_test1);
try {
pagenumber.setText(testContactName.get(position));
**method i called like**
imgcopy.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
setClipboard(mViewPager.getFocusedChild(), pagenumber.getText().toString());
}
});
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
( collection).addView(view);
return view;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
( collection).removeView((View) view);
mAdapter.notifyDataSetChanged();
}
}
}
method i use to copytoclipborad
private void setClipboard(View context,String text) {
if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText(text);
Toast.makeText(getApplicationContext(),text,Toast.LENGTH_LONG).show();
} else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData.newPlainText("Copied Text", text);
clipboard.setPrimaryClip(clip);
Toast.makeText(getApplicationContext(),"Copied To ClipBoard",Toast.LENGTH_LONG).show();
}
}
test.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v4.view.ViewPager
android:id="#+id/testvp"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
</RelativeLayout>
test1.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/tv_test1"
android:layout_gravity="top|center"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>

Categories

Resources