Not getting the number after decimal point in android - 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;
}
}

Related

Get Values from Adapter to main activity

I was trying to get the values which i have entered in edit text using recycler view. On click of submit i want to save the text given in the editetxt to the table.
using Json stored the data to the table - Success
upto array adapter i got the data
now how to move the data from adapter to the main activity to save the data into table on single submit button. [enter image description here][1]
Activity
public class fertlizerRequest extends AppCompatActivity {
Button submit_btn,view_btn;
RecyclerView material_lv;
ArrayList<ProductData> arrayList;
ProductsAdapter myAdapterP;
private RecyclerView.LayoutManager mLayoutManager;
DBHelperClass dbHelperClass = new DBHelperClass(this);
Integer[] enteredNumber = new Integer[1000];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fertlizer_request);
datacasting();
view_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PlantLocationAssy plantLocationAssy = new PlantLocationAssy();
plantLocationAssy.execute();
}
});
submit_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(fertlizerRequest.this, "Edited Item are ", Toast.LENGTH_SHORT).show();
}
});
}
void datacasting(){
material_lv = (RecyclerView) findViewById(R.id.materialreq_lv);
submit_btn = (Button) findViewById(R.id.sbt_btn);
view_btn = (Button) findViewById(R.id.vie_btn);
mLayoutManager = new LinearLayoutManager(this);
material_lv.setLayoutManager(mLayoutManager);
}
void fetchProductData(){
arrayList = dbHelperClass.getProductsDataFromDB();
myAdapterP = new ProductsAdapter(fertlizerRequest.this, arrayList, new ProductsAdapter.onEditTextChanged() {
#Override
public void onTextChanged(int position, String charSeq) {
enteredNumber[position] = Integer.valueOf(charSeq);
System.out.println("==================================== " + position);
Toast.makeText(fertlizerRequest.this, "Entered value is " + myAdapterP.getItemId(position), Toast.LENGTH_SHORT).show();
}
});
material_lv.setAdapter(myAdapterP);
myAdapterP.notifyDataSetChanged();
System.out.println("==================================== " + myAdapterP.getItemCount() );
}
private class PlantLocationAssy extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
fetchProductData();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
}
}
Adapter
package com.example.fertlizertrackerapp.Adapter;
import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.fertlizertrackerapp.Model.ProductData;
import com.example.fertlizertrackerapp.R;
import java.io.Serializable;
import java.util.ArrayList;
public class ProductsAdapter extends RecyclerView.Adapter<ProductsAdapter.Holder> {
private Context context;
private ArrayList<ProductData> arrayList;
private onEditTextChanged onEditTextChanged;
public ProductsAdapter(Context context, ArrayList<ProductData> arrayList, onEditTextChanged onEditTextChanged) {
this.context = context;
this.arrayList = arrayList;
this.onEditTextChanged = onEditTextChanged;
}
#NonNull
#Override
public Holder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.cust_lv_fertilizer_request, parent, false);
return new Holder(view);
}
#Override
public void onBindViewHolder(#NonNull final Holder holder, final int position) {
final ProductData productData = arrayList.get(position);
// get for view
String productId = productData.getProductId();
final String material = productData.getMaterial();
String materialCode = productData.getMaterialCode();
//set view
holder.productId.setText(productId);
holder.material.setText(material);
holder.materialCode.setText(materialCode);
holder.quantity.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
onEditTextChanged.onTextChanged(position,s.toString());
String qty = holder.quantity.getText().toString();
Toast.makeText(context, "Value Changed is " + material + " : " + qty, Toast.LENGTH_SHORT).show();
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
#Override
public int getItemCount() {
return arrayList.size();
}
class Holder extends RecyclerView.ViewHolder{
TextView productId, material,materialCode;
EditText quantity;
public Holder(#NonNull View itemView) {
super(itemView);
productId = itemView.findViewById(R.id.productId_tv);
material = itemView.findViewById(R.id.materialName_tv);
materialCode = itemView.findViewById(R.id.materialCode_tv);
quantity = (itemView).findViewById(R.id.materialQuantity_edt);
}
}
#Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
public interface onEditTextChanged{
void onTextChanged(int position, String charSeq);
}
}
Model
package com.example.fertlizertrackerapp.Model;
public class ProductData {
String ProductId, Material,MaterialCode;
int quantity = 0;
public ProductData(String productId, String material,String materialCode) {
this.ProductId = productId;
this.Material = material;
this.MaterialCode = materialCode;
}
public String getProductId() {
return ProductId;
}
public void setProductId(String productId) {
ProductId = productId;
}
public String getMaterial() {
return Material;
}
public void setMaterial(String material) {
Material = material;
}
public String getMaterialCode() {
return MaterialCode;
}
public void setMaterialCode(String materialCode) {
MaterialCode = materialCode;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
DBHelperClass
package com.example.fertlizertrackerapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.example.fertlizertrackerapp.Model.PlantData;
import com.example.fertlizertrackerapp.Model.ProductData;
import com.example.fertlizertrackerapp.Model.ProductRateData;
import java.util.ArrayList;
public class DBHelperClass extends SQLiteOpenHelper {
public static final int DBVersion = 1;
public static final String DB_Godown = "FertlizerApp.db";
public static final String DB_ProductListTABLE = "ProductDetails";
public static final String DB_ProductId = "ProductId";
public static final String DB_productStatus = "productStatus";
public static final String DB_Material = "Material";
public static final String DB_MaterialCode = "MaterialCode";
public static final String DB_MaterialStatus = "Status";
public static final String DB_MaterialCreatedBy = "CreatedBy";
public static final String DB_MaterialCreatedOn = "CreatedOn";
public static final String DB_MaterialUpdatedBy = "UpdatedBy";
public static final String DB_MaterialUpdatedOn = "UpdatedOn";
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(" CREATE TABLE " + DB_ProductListTABLE + "(" + DB_ProductId + " TEXT, "
+ DB_productStatus + " TEXT, "
+ DB_Material + " TEXT, "
+ DB_MaterialCode + " TEXT NOT NULL PRIMARY KEY, "
+ DB_MaterialStatus + " TEXT, "
+ DB_MaterialCreatedBy + " TEXT, "
+ DB_MaterialCreatedOn + " TEXT, "
+ DB_MaterialUpdatedBy + " TEXT, "
+ DB_MaterialUpdatedOn + " TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DB_ProductListTABLE);
}
public Boolean insertProductDetails(String v_ProductId, String v_productStatus, String v_Material, String v_MaterialCode, String v_MaterialStatus, String v_MaterialCreatedBy, String v_MaterialCreatedOn, String v_MaterialUpdatedBy, String v_MaterialUpdatedOn) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValue = new ContentValues();
contentValue.put("ProductId", v_ProductId);
contentValue.put("productStatus", v_productStatus);
contentValue.put("Material", v_Material);
contentValue.put("MaterialCode", v_MaterialCode);
contentValue.put("Status", v_MaterialStatus);
contentValue.put("CreatedBy", v_MaterialCreatedBy);
contentValue.put("CreatedOn", v_MaterialCreatedOn);
contentValue.put("UpdatedBy", v_MaterialUpdatedBy);
contentValue.put("UpdatedOn", v_MaterialUpdatedOn);
long result = db.insert(DB_ProductListTABLE, null, contentValue);
if (result == -1)
return false;
else
return true;
}
public DBHelperClass(Context context) {
super(context, DB_Godown, null, DBVersion);
}
public ArrayList<ProductData> getProductsDataFromDB(){
ArrayList<ProductData> arrayList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from " + DB_ProductListTABLE, null);
while (cursor.moveToNext()) {
String productId = cursor.getString(0);
String material = cursor.getString(2);
String materialCode = cursor.getString(3);
ProductData productData = new ProductData(productId,material,materialCode);
arrayList.add(productData);
System.out.println("00000000000000000000 Product 00000000000000000000000000000 " + material);
}
return arrayList;
}
}
[1]: https://i.stack.imgur.com/ikNRR.jpg

Display image from sqlite in listview?

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.

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.

(Android) What have I done wrong in my code while trying to populate a spinner with database info

I am make data show that up in a spinner that consists of food objects (name, calories) that gets created in my main, and then make these objects (just the name for now) show up in a spinner that is on the activity. This activity will actually become a part of a larger program, and eventually I want to be able to allow the user the ability to "count" the total amount of calories that they have eaten by added up all the foods selected. For now, I just want to be able to make the foods appear so I can move further along. However, whenever I go to run it, my app just crashes with no error message stated the problem. If anyone knows what I need to do, please help. My code below:
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.List;
public class MainActivity extends ActionBarActivity implements
OnItemSelectedListener {
MyDBHandler dbHandler = new MyDBHandler(this, null, null, 1);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Foods food1 = new Foods("Apple", "80");
Foods food2 = new Foods("Bagel", "200");
Foods food3 = new Foods("Biscuit", "65" );
Foods food4 = new Foods("Banana", "105");
Foods food5 = new Foods("Beef Roast", "205");
Foods food6 = new Foods("Corn", "60");
Foods food7 = new Foods("Cereal", "120");
Foods food8 = new Foods("Chicken", "240");
Foods food9 = new Foods("Eggs", "105");
Foods food10 = new Foods("Cabbage", "30");
Foods food11 = new Foods("Oatmeal", "160");
Foods food12 = new Foods("Pancake", "60");
Foods food13 = new Foods("Pears", "100");
Foods food14 = new Foods("Pizza", "290");
Foods food15 = new Foods("Ice Cream", "270");
Foods food16 = new Foods("Pork Chop", "335");
Foods food17 = new Foods("Ham", "250");
Foods food18 = new Foods("Ribs", "270");
Foods food19 = new Foods("Popcorn", "55");
Foods food20 = new Foods("Baked Potato", "220");
Foods food21 = new Foods("Rice", "225");
Foods food22 = new Foods("Salad", "85");
Foods food23 = new Foods("Spaghetti", "360");
Foods food24 = new Foods("Bread", "65");
Foods food25 = new Foods("Fish", "175");
dbHandler.addFood(food1);
dbHandler.addFood(food2);
dbHandler.addFood(food3);
dbHandler.addFood(food4);
dbHandler.addFood(food5);
dbHandler.addFood(food6);
dbHandler.addFood(food7);
dbHandler.addFood(food8);
dbHandler.addFood(food9);
dbHandler.addFood(food10);
dbHandler.addFood(food11);
dbHandler.addFood(food12);
dbHandler.addFood(food13);
dbHandler.addFood(food14);
dbHandler.addFood(food15);
dbHandler.addFood(food16);
dbHandler.addFood(food17);
dbHandler.addFood(food18);
dbHandler.addFood(food19);
dbHandler.addFood(food20);
dbHandler.addFood(food21);
dbHandler.addFood(food22);
dbHandler.addFood(food23);
dbHandler.addFood(food24);
dbHandler.addFood(food25);
spinner.setOnItemSelectedListener(this);
loadSpinnerData();
}
private void loadSpinnerData()
{
List<String> foodnames = dbHandler.getFoodNames();
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, foodnames);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String food = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "You selected: " + food,
Toast.LENGTH_LONG).show();
}
}
public class Foods {
private int _id;
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
private String name;
private String calories;
public Foods(){
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCalories() {
return calories;
}
public void setCalories(String calories) {
this.calories = calories;
}
public Foods(String foodname, String foodcalories){
this.name = foodname;
this.calories = foodcalories;
}
}
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.Cursor;
import android.content.Context;
import android.content.ContentValues;
import java.util.ArrayList;
import java.util.List;
public class MyDBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "BroncoWellness.db";
public static final String TABLE_FOODS = "food";
public static final String COLUMN_FOOD_ID = "_id";
public static final String COLUMN_FOOD_NAME = "foodname";
public static final String COLUMN_FOOD_CALORIES = "foodcalories";
#Override
public void onCreate(SQLiteDatabase db) {
String Foodquery = "CREATE TABLE " + TABLE_FOODS + "(" +
COLUMN_FOOD_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_FOOD_NAME + " TEXT " +
COLUMN_FOOD_CALORIES + " TEXT " +
");";
db.execSQL(Foodquery);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FOODS);
onCreate(db);
}
public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context,DATABASE_NAME ,factory, DATABASE_VERSION);}
public void addFood(Foods food){
ContentValues values = new ContentValues();
values.put(COLUMN_FOOD_NAME, food.getName());
values.put(COLUMN_FOOD_CALORIES, food.getCalories());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_FOODS,null,values);
db.close();
}
public List<String> getFoodNames(){
List<String> foodnames = new ArrayList<String>();
String selectQuery = "SELECT * FROM " + TABLE_FOODS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
foodnames.add(cursor.getString(1));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return foodnames;
}
}
In your code, you are initializing the spinner outside the onCreate() method. It should be like this-
Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.spinner);
//your code
}
This will solve your issue.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// **Spinner element here**
spinner = (Spinner) findViewById(R.id.spinner);

LoadMoreListView Fragment implementation using sqlite database

I need to load a large dataset from a sqlite database. This will take too much of time to load the data. Therefore I used LoadMorelistView library to load with pagination.
I followed below link and successfully load the data from hard coded list.
pull to refresh and loadmore listview like facebook
But when I tried to load from sqlite database I got the following error.
// The constructor ArrayAdapter(Activity, int, ArrayList) is Undefined
I searched the google as well as stackoverflow. But unable to find a solution.
Please find the code snippet which I used to load the data,
Code for the list loading fragment. (FragmentThree.java)
package com.load.more.list.view;
import java.util.ArrayList;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import com.costum.android.widget.LoadMoreListView;
import com.costum.android.widget.LoadMoreListView.OnLoadMoreListener;
import com.load.more.list.model.Customer;
import com.load.more.list.data.CustomerDS;
import com.load.more.list.data.DatabaseHelper;
import android.app.Fragment;
import com.load.more.list.control.CustomerAdapter;
public class FragmentThree extends Fragment {
View view;
LoadMoreListView lyt;
ArrayAdapter<String> files;
ArrayList<Customer> mListItems;
CustomerDS customerDS;
private DatabaseHelper dbHelper;
private int visibleThreshold = 20;
private int currentPage = 0;
private int previousTotal = 0;
private int firstVisibleItem = 0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_three, container, false);
lyt = (LoadMoreListView) view.findViewById(R.id.lvRouteCustomers);
mListItems = customerDS.getAllCustomersFromTo(visibleThreshold,
firstVisibleItem);
// Following Error Thrown from here
// The constructor ArrayAdapter<String>(Activity, int,
// ArrayList<Customer>) is Undefined
files = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, mListItems);
lyt.setAdapter(files);
lyt.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
// TODO Auto-generated method stub
new LoadMoreDataTask().execute();
}
});
return view;
}
private class LoadMoreDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
if (isCancelled()) {
return null;
}
// Simulates a background task
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
// Following Error Thrown from here
// The constructor ArrayAdapter<String>(Activity, int,
// ArrayList<Customer>) is Undefined
files = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, mListItems);
lyt.setAdapter(files);
return null;
}
#Override
protected void onPostExecute(Void result) {
files.notifyDataSetChanged();
// Call onLoadMoreComplete when the LoadMore task, has finished
lyt.onLoadMoreComplete();
super.onPostExecute(result);
}
#Override
protected void onCancelled() {
// Notify the loading more operation has finished
lyt.onLoadMoreComplete();
}
}
}
Code for the database helper class. (DatabaseHelper)
package com.load.more.list.data;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
//database information
private static final String DATABASE_NAME = "fmcgDB.db";
private static final int DATABASE_VERSION = 1;
//TABLES
//Customer table
public static final String TABLE_CUSTOMER = "customer";
public static final String CUSTOMER_ID = "customer_id";
public static final String CUSTOMER_NO = "customer_no";
public static final String CUSTOMER_NAME = "customer_name";
public static final String CUSTOMER_CONTACT_PERSON = "customer_contact_person";
public static final String CUSTOMER_TELEPHONE_NO = "customer_telephone_no";
public static final String CUSTOMER_ADDRESS = "customer_address";
public static final String CUSTOMER_LONGITUDE = "customer_longitude";
public static final String CUSTOMER_LATITUDE = "customer_latitude";
public static final String CUSTOMER_TLP = "customer_tlp";
public static final String CUSTOMER_REP_ID = "customer_rep_id";
public static final String CUSTOMER_CATEGORY_ID = "cc_id";
public static final String CUSTOMER_OUTLET_TYPE_ID = "ot_id";
public static final String CUSTOMER_PERIPHERY_TYPE_ID = "pt_id";
public static final String CUSTOMER_VOLUME_ID = "volume_id";
public static final String CUSTOMER_MARKET_ID = "market_id";
private static final String CREATE_CUSTOMER_TABLE = "CREATE TABLE " + TABLE_CUSTOMER + " ("
+ CUSTOMER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ CUSTOMER_NO + " TEXT, "
+ CUSTOMER_NAME + " TEXT, "
+ CUSTOMER_CONTACT_PERSON + " TEXT, "
+ CUSTOMER_TELEPHONE_NO + " TEXT, "
+ CUSTOMER_ADDRESS + " TEXT, "
+ CUSTOMER_LONGITUDE + " REAL, "
+ CUSTOMER_LATITUDE + " REAL, "
+ CUSTOMER_TLP + " INTEGER, "
+ CUSTOMER_REP_ID + " INTEGER, "
+ CUSTOMER_CATEGORY_ID + " INTEGER, "
+ CUSTOMER_OUTLET_TYPE_ID + " INTEGER, "
+ CUSTOMER_PERIPHERY_TYPE_ID + " INTEGER, "
+ CUSTOMER_VOLUME_ID + " INTEGER, "
+ CUSTOMER_MARKET_ID + " INTEGER "
+");";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase arg0) { // this order must be followed when creating tables
arg0.execSQL(CREATE_CUSTOMER_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
arg0.execSQL("DROP TABLE IF EXISTS " + CREATE_CUSTOMER_TABLE);
onCreate(arg0);
}
}
Code for the sqlite data loading. (CustomerDS.java)
package com.load.more.list.data;
import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import com.load.more.list.model.Customer;
public class CustomerDS {
private SQLiteDatabase fmcgDB;
private DatabaseHelper dbHelper;
Context context;
public CustomerDS(Context context) {
this.context = context;
dbHelper = new DatabaseHelper(context);
}
public void open() throws SQLException {
fmcgDB = dbHelper.getWritableDatabase();
}
public ArrayList<Customer> getAllCustomersFromTo(int limit, int offset) {
if (fmcgDB == null) {
open();
} else if (!fmcgDB.isOpen()) {
open();
}
ArrayList<Customer> customersList = new ArrayList<Customer>();
// Newly Added
String selectQuery = "SELECT * FROM " + dbHelper.TABLE_CUSTOMER
+ " LIMIT " + limit + " OFFSET " + offset +"";
Cursor cursor = null;
try{
cursor = fmcgDB.rawQuery(selectQuery, null);
/*cursor = fmcgDB.query(dbHelper.TABLE_CUSTOMER, null, null, null,
null, null, null);
*/
while (cursor.moveToNext()) {
Customer customer = new Customer();
customer.setCustomer_id(cursor.getInt(cursor.getColumnIndex(dbHelper.CUSTOMER_ID)));
customer.setCustomer_no(cursor.getString((cursor.getColumnIndex(dbHelper.CUSTOMER_NO))));
customer.setCustomer_name(cursor.getString((cursor.getColumnIndex(dbHelper.CUSTOMER_NAME))));
customer.setCustomer_contact_person(cursor.getString((cursor.getColumnIndex(dbHelper.CUSTOMER_CONTACT_PERSON))));
customer.setCustomer_telephone_no(cursor.getString((cursor.getColumnIndex(dbHelper.CUSTOMER_TELEPHONE_NO))));
customer.setCustomer_address(cursor.getString((cursor.getColumnIndex(dbHelper.CUSTOMER_ADDRESS))));
customer.setCustomer_longitude(cursor.getDouble((cursor.getColumnIndex(dbHelper.CUSTOMER_LONGITUDE))));
customer.setCustomer_latitude(cursor.getDouble((cursor.getColumnIndex(dbHelper.CUSTOMER_LATITUDE))));
int TLP = cursor.getInt((cursor.getColumnIndex(dbHelper.CUSTOMER_TLP)));
if(TLP == 0){
customer.setCustomer_TLP_member(true);
}else{
customer.setCustomer_TLP_member(false);
}
customersList.add(customer);
}
}
finally {
if (cursor!=null) {
cursor.close();
}
fmcgDB.close();
return customersList;
}
}
}
Code for the Adapter Class. (CustomerAdapter.java)
package com.load.more.list.control;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.load.more.list.model.Customer;
import com.load.more.list.view.R;
public class CustomerAdapter extends ArrayAdapter<Customer> {
Context context;
ArrayList<Customer> customerList;
public CustomerAdapter(Context context, ArrayList<Customer> customerList){
super(context, R.layout.item_customer, customerList);
this.context = context;
this.customerList = customerList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.item_customer, parent, false);
TextView tvName = (TextView) row.findViewById(R.id.tvRouteCustomerListName);
TextView tvMarket = (TextView) row.findViewById(R.id.tvRouteCustomerListMarket);
TextView tvVolume = (TextView) row.findViewById(R.id.tvRouteCustomerListVolume);
tvName.setText(customerList.get(position).getCustomer_name());
return row;
}
}
Code for the Customer Object. (Customer.java)
package com.load.more.list.model;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.util.Log;
public class Customer {
private static final String TAG_CUSTOMER = "customers";
private static final String TAG_CUSTOMER_ID = "customer_id";
private static final String TAG_CUSTOMER_NO = "CustomerCode";
private static final String TAG_CUSTOMER_NAME = "CustomerName";
private static final String TAG_CUSTOMER_ADDRESS = "Address1";
private static final String TAG_CUSTOMER_CONTACT_PERSON = "ContactPersonName";
private static final String TAG_CUSTOMER_TELEPHONE_NO = "PhoneNo";
private static final String TAG_CUSTOMER_LATITUDE = "CustomerLatitude";
private static final String TAG_CUSTOMER_LONGITUDE = "CustomerLongitude";
private static final String TAG_CUSTOMER_IS_TLP = "Istlp";
private static final String TAG_CUSTOMER_REP_ID = "";
private static final String TAG_CUSTOMER_PT_ID = "PheriheryId";
private static final String TAG_CUSTOMER_CATEGORY_ID = "CatrgoryId";
private static final String TAG_CUSTOMER_OUTLETTYPE_ID = "OutletTypeId";
private static final String TAG_CUSTOMER_VOLUME_ID = "VolumeId";
private static final String TAG_CUSTOMER_MARKET_ID = "MarketId";
private int customer_id;
private String customer_no;
private String customer_name;
private String customer_contact_person;
private String customer_telephone_no;
private String customer_address;
private double customer_longitude;
private double customer_latitude;
private boolean customer_TLP_member;
public int getCustomer_id() {
return customer_id;
}
public void setCustomer_id(int customer_id) {
this.customer_id = customer_id;
}
public String getCustomer_name() {
return customer_name;
}
public void setCustomer_name(String customer_name) {
this.customer_name = customer_name;
}
public String getCustomer_contact_person() {
return customer_contact_person;
}
public void setCustomer_contact_person(String customer_contact_person) {
this.customer_contact_person = customer_contact_person;
}
public String getCustomer_telephone_no() {
return customer_telephone_no;
}
public void setCustomer_telephone_no(String customer_telephone_no) {
this.customer_telephone_no = customer_telephone_no;
}
public String getCustomer_address() {
return customer_address;
}
public void setCustomer_address(String customer_address) {
this.customer_address = customer_address;
}
public double getCustomer_longitude() {
return customer_longitude;
}
public void setCustomer_longitude(double customer_longitude) {
this.customer_longitude = customer_longitude;
}
public double getCustomer_latitude() {
return customer_latitude;
}
public void setCustomer_latitude(double customer_latitude) {
this.customer_latitude = customer_latitude;
}
public boolean isCustomer_TLP_member() {
return customer_TLP_member;
}
public void setCustomer_TLP_member(boolean customer_TLP_member) {
this.customer_TLP_member = customer_TLP_member;
}
public String getCustomer_no() {
return customer_no;
}
public void setCustomer_no(String customer_no) {
this.customer_no = customer_no;
}
}
Can anyone know how to solve this problem? If yes, please help me to solve this problem.
Thanks in advance.
Finally I solved the issue,.
I have changed the type of mListItems to
ArrayList<String> mListItems;
and the return type of getAllCustomersFromTo() to String array.
It solved my issue.
Final source code of the updated classes are shown below.
Code for the list loading fragment. (FragmentThree.java)
package com.load.more.list.view;
import java.util.ArrayList;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import com.costum.android.widget.LoadMoreListView;
import com.costum.android.widget.LoadMoreListView.OnLoadMoreListener;
import com.load.more.list.model.Customer;
import com.load.more.list.data.CustomerDS;
import com.load.more.list.data.DatabaseHelper;
import android.app.Fragment;
import com.load.more.list.control.CustomerAdapter;
public class FragmentThree extends Fragment {
View view;
LoadMoreListView lyt;
ArrayAdapter<String> files;
ArrayList<String> mListItems;
CustomerDS customerDS;
private DatabaseHelper dbHelper;
private int visibleThreshold = 20;
private int currentPage = 0;
private int previousTotal = 0;
private int firstVisibleItem = 0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_three, container, false);
lyt = (LoadMoreListView) view.findViewById(R.id.lvRouteCustomers);
mListItems = customerDS.getAllCustomersFromTo(visibleThreshold,
firstVisibleItem);
files = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, mListItems);
lyt.setAdapter(files);
lyt.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
// TODO Auto-generated method stub
new LoadMoreDataTask().execute();
}
});
return view;
}
private class LoadMoreDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
if (isCancelled()) {
return null;
}
// Simulates a background task
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
files = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, mListItems);
lyt.setAdapter(files);
return null;
}
#Override
protected void onPostExecute(Void result) {
files.notifyDataSetChanged();
// Call onLoadMoreComplete when the LoadMore task, has finished
lyt.onLoadMoreComplete();
super.onPostExecute(result);
}
#Override
protected void onCancelled() {
// Notify the loading more operation has finished
lyt.onLoadMoreComplete();
}
}
}
Code for the sqlite data loading. (CustomerDS.java)
package com.load.more.list.data;
import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import com.load.more.list.model.Customer;
public class CustomerDS {
private SQLiteDatabase fmcgDB;
private DatabaseHelper dbHelper;
Context context;
public CustomerDS(Context context) {
this.context = context;
dbHelper = new DatabaseHelper(context);
}
public void open() throws SQLException {
fmcgDB = dbHelper.getWritableDatabase();
}
public ArrayList<String> getAllCustomersFromTo(int limit, int offset) {
if (fmcgDB == null) {
open();
} else if (!fmcgDB.isOpen()) {
open();
}
ArrayList<String> customersList = new ArrayList<String>();
String selectQuery = "SELECT * FROM " + dbHelper.TABLE_CUSTOMER
+ " LIMIT " + limit + " OFFSET " + offset +"";
Cursor cursor = null;
try{
cursor = fmcgDB.rawQuery(selectQuery, null);
while (cursor.moveToNext()) {
customersList.add(cursor.getString((cursor.getColumnIndex(dbHelper.CUSTOMER_NAME))));
}
}
finally {
if (cursor!=null) {
cursor.close();
}
fmcgDB.close();
return customersList;
}
}
}

Categories

Resources