Get Values from Adapter to main activity - android

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

Related

How to retrieve data from firebase database which is having nested array and objects structure?

I tried data extraction code from many places but everywhere i get how to retrieve data in a simple list. As the structure of my JSON is complex and i can't change it now, so please help me in retrieving data from firebase database. Please help as i am not able to understand Firebase code. Following is my code and JSON database:
CategoryModel.xml
package com.example.firedb;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
/**
* Created by Android on 5/31/2017.
*/
public class CategoryModel {
private ArrayList<CategoryList> categoryList;
public CategoryModel() {
}
public CategoryModel(ArrayList<CategoryList> categoryList) {
this.categoryList = categoryList;
}
public ArrayList<CategoryList> getCategoryList() {
return categoryList;
}
public void setCategoryList(ArrayList<CategoryList> categoryList) {
this.categoryList = categoryList;
}
// CategoryList
public static class CategoryList {
public int Category_id;
public String Category_name;
public ArrayList<String>Emails;
public ArrayList<String>Epabx;
public ArrayList<String>Category_Fax;
public ArrayList<Persons> persons;
public CategoryList() {
}
//constructor of CategoryList
public CategoryList(int category_id, String category_name,
ArrayList<String> emails, ArrayList<String> epabx, ArrayList<String> category_Fax,
ArrayList<Persons> persons) {
Category_id = category_id;
Category_name = category_name;
Emails = emails;
Epabx = epabx;
Category_Fax = category_Fax;
this.persons = persons;
}
// getters and setters of CategoryList
public int getCategory_id() {
return Category_id;
}
public void setCategory_id(int category_id) {
Category_id = category_id;
}
public String getCategory_name() {
return Category_name;
}
public void setCategory_name(String category_name) {
Category_name = category_name;
}
public ArrayList<String> getEmails() {
return Emails;
}
public void setEmails(ArrayList<String> emails) {
Emails = emails;
}
public ArrayList<String> getEpabx() {
return Epabx;
}
public void setEpabx(ArrayList<String> epabx) {
Epabx = epabx;
}
public ArrayList<String> getCategory_Fax() {
return Category_Fax;
}
public void setCategory_Fax(ArrayList<String> category_Fax) {
Category_Fax = category_Fax;
}
public ArrayList<Persons> getPersons() {
return persons;
}
public void setPersons(ArrayList<Persons> persons) {
this.persons = persons;
}
}
//Persons
public static class Persons {
private int Person_ID;
private String Name;
private String Designation;
private ArrayList<String> Office_Phone;
private ArrayList<String> Residence_Phone;
private String VOIP;
private String Address;
private ArrayList<String>Fax;
private String Ext;
private ArrayList<String>Extra_info;
private String Category_name;
public Persons() {
}
// Constructor of Persons
public Persons(int person_ID, String name, String designation, ArrayList<String> office_Phone,
ArrayList<String> residence_Phone, String VOIP, String address, ArrayList<String> fax, String ext,
ArrayList<String>extra_info, String category_name) {
Person_ID = person_ID;
Name = name;
Designation = designation;
Office_Phone = office_Phone;
Residence_Phone = residence_Phone;
this.VOIP = VOIP;
Address = address;
Fax = fax;
Ext = ext;
Extra_info=extra_info;
Category_name=category_name;
}
// Getter and Setters of Persons
public int getPerson_ID() {
return Person_ID;
}
public void setPerson_ID(int person_ID) {
Person_ID = person_ID;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getDesignation() {
return Designation;
}
public void setDesignation(String designation) {
Designation = designation;
}
public ArrayList<String> getOffice_Phone() {
return Office_Phone;
}
public void setOffice_Phone(ArrayList<String> office_Phone) {
Office_Phone = office_Phone;
}
public ArrayList<String> getResidence_Phone() {
return Residence_Phone;
}
public void setResidence_Phone(ArrayList<String> residence_Phone) {
Residence_Phone = residence_Phone;
}
public String getVOIP() {
return VOIP;
}
public void setVOIP(String VOIP) {
this.VOIP = VOIP;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public ArrayList<String> getFax() {
return Fax;
}
public void setFax(ArrayList<String> fax) {
Fax = fax;
}
public String getExt() {
return Ext;
}
public void setExt(String ext) {
Ext = ext;
}
public ArrayList<String> getExtra_info() {
return Extra_info;
}
public void setExtra_info(ArrayList<String> extra_info) {
Extra_info = extra_info;
}
public String getCategory_name() {
return Category_name;
}
public void setCategory_name(String category_name) {
Category_name = category_name;
}
}
}
CardviewActivity: Earlier i used an asset file but now i want to get data from firebase whose code is ambiguous online
package com.example.firedb;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.LoginFilter;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import static android.R.attr.button;
public class CardViewActivity extends AppCompatActivity {
Toolbar mActionBarToolbar;
private RecyclerView mainRecyclerView;
private RecyclerView.Adapter mainAdapter;
private RecyclerView.LayoutManager mainLayoutManager;
private static String LOG_TAG = "CardViewActivity";
EditText inputSearchMain;
private ArrayList<CategoryModel.CategoryList> categoryLists;
TextView toolbar_title_main;
ImageView back_cardviewActivity;
// DatabaseHandler db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_card_view);
// db = new DatabaseHandler (CardViewActivity.this);
mActionBarToolbar = (Toolbar) findViewById(R.id.tool_bar);
toolbar_title_main=(TextView)findViewById(R.id.toolbar_title);
// mActionBarToolbar.setTitle("Hry. Govt. Telephone Directory");
// mActionBarToolbar.setLogo(R.drawable.logotoolbar);
// mActionBarToolbar.setTitleMargin(5,2,2,2);
setSupportActionBar(mActionBarToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar_title_main.setText("Hry. Govt. Telephone Directory");
back_cardviewActivity=(ImageView)findViewById(R.id.back);
back_cardviewActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
categoryLists=new ArrayList<CategoryModel.CategoryList>();
categoryLists.addAll(getmcategoryset());
mainRecyclerView=(RecyclerView)findViewById(R.id.recyclerView_Main);
mainRecyclerView.setHasFixedSize(true);
mainLayoutManager=new LinearLayoutManager(this);
mainRecyclerView.setLayoutManager(mainLayoutManager);
// Log.d( "onCreate: ", "List Size: "+categoryLists.size());
mainAdapter=new RecyclerViewAdapterMain(getmcategoryset());
mainRecyclerView.setAdapter(mainAdapter);
inputSearchMain = (EditText) findViewById(R.id.inputSearchMain);
addTextListener();
}
public void addTextListener(){
inputSearchMain.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence query, int start, int before, int count) {
query = query.toString().toLowerCase();
final ArrayList<CategoryModel.CategoryList> filteredList = new ArrayList<CategoryModel.CategoryList>();
for (int i = 0; i < categoryLists.size(); i++) {
final String text = categoryLists.get(i).getCategory_name().toLowerCase();
if (text.contains(query)) {
filteredList.add(categoryLists.get(i));
}
}
mainRecyclerView.setLayoutManager(new LinearLayoutManager(CardViewActivity.this));
mainAdapter = new RecyclerViewAdapterMain(filteredList);
mainRecyclerView.setAdapter(mainAdapter);
mainAdapter.notifyDataSetChanged(); // data set changed
}
});
}
private ArrayList<CategoryModel.CategoryList> getmcategoryset() {
// JSONObject obj = new JSONObject(readJSONFromAsset());
try {
ArrayList<CategoryModel.CategoryList>categoryList = new ArrayList<CategoryModel.CategoryList>();
JSONObject jsonObject = new JSONObject(readJSONFromAsset());
JSONArray categoryArray = jsonObject.getJSONArray("Category");
Log.d("getmcategoryset", "category count: "+categoryArray.length());
for (int i = 0; i < categoryArray.length(); i++)
{
JSONObject job = categoryArray.getJSONObject(i);
int categoryId = job.getInt("Category_id");
String categoryName = job.getString("Category_name");
//this is for email array
ArrayList<String> emails = new ArrayList<>();
JSONArray emailArray = job.getJSONArray("Emails");
for (int j = 0; j< emailArray.length(); j++){
// JSONObject jobE = emailArray.getString(j);
emails.add(emailArray.getString(j));
}
//This i for Epabx array
ArrayList<String> epabx = new ArrayList<>();
JSONArray epabxArray = job.getJSONArray("Epabx");
for (int j = 0; j < epabxArray.length(); j++){
// JSONObject jobE = epabxArray.getString(j);
epabx.add(epabxArray.getString(j));
}
//This i for Category_Fax array
ArrayList<String> category_Fax = new ArrayList<>();
JSONArray category_FaxJson = job.getJSONArray("Category_Fax");
for (int j = 0; j < category_FaxJson.length(); j++){
// JSONObject jobE = category_FaxJson.getString(j);
category_Fax.add(category_FaxJson.getString(j));
}
//This i for Persons array
ArrayList<CategoryModel.Persons> personsList = new ArrayList<>();
JSONArray personsArray = job.getJSONArray("Persons");
for (int j = 0; j < personsArray.length(); j++){
JSONObject jobIn = personsArray.getJSONObject(j);
int Person_ID = jobIn.getInt("Person_ID");
String Name = jobIn.getString("Name");
String Designation = jobIn.getString("Designation");
//this is for Office_Phone array
ArrayList<String>Office_Phone = new ArrayList<>();
JSONArray office_Phone = jobIn.getJSONArray("Office_Phone");
for (int k=0; k < office_Phone.length(); k++)
{
Office_Phone.add(office_Phone.getString(k));
}
//this is for Residence_Phone array
ArrayList<String>Residence_Phone = new ArrayList<>();
JSONArray residence_Phone = jobIn.getJSONArray("Residence_Phone");
for (int k=0; k < residence_Phone.length(); k++)
{
Residence_Phone.add(residence_Phone.getString(k));
}
String VOIP = jobIn.getString("VOIP");
String Address = jobIn.getString("Address");
//this is for Fax array
ArrayList<String>Fax = new ArrayList<>();
JSONArray fax = jobIn.getJSONArray("Fax");
for (int k=0; k < fax.length(); k++)
{
Fax.add(fax.getString(k));
}
String Ext = jobIn.getString("Ext");
//this is for Extra_info array
ArrayList<String>Extra_info = new ArrayList<>();
JSONArray extra_info = jobIn.getJSONArray("Extra_info");
for (int k=0; k < extra_info.length(); k++)
{
Extra_info.add(extra_info.getString(k));
}
personsList.add(new CategoryModel.Persons(Person_ID, Name, Designation, Office_Phone, Residence_Phone,
VOIP, Address, Fax, Ext,Extra_info,categoryName));
// db.addPerson(new CategoryModel.Persons(Person_ID, Name, Designation, Office_Phone, Residence_Phone,
// VOIP, Address, Fax, Ext,Extra_info));
}
//here your Category[] value store in categoryArrayList
categoryList.add(new CategoryModel.CategoryList(categoryId, categoryName, emails, epabx, category_Fax, personsList));
// db.addCategory(new CategoryModel.CategoryList(categoryId, categoryName, emails, epabx, category_Fax, personsList));
Log.i("categoryList size = ", ""+categoryArray.length());
Log.i("cat_name=",""+categoryName);
}
if (categoryList != null)
{
Log.i("categoryList size = ", ""+categoryArray.length());
}
return categoryList;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onResume() {
super.onResume();
// ((RecyclerViewAdapterMain) mainAdapter).setOnItemClickListener(new RecyclerViewAdapterMain()
// .CategoryClickListener() {
// public void onItemClick(int position, View v) {
// Log.i(LOG_TAG, " Clicked on Item " + position);
// }
// });
}
}
RecyclerViewAdapter:
package com.example.firedb;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
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.Arrays;
public class RecyclerViewAdapterMain extends RecyclerView.Adapter<RecyclerViewAdapterMain.CategoryObjectHolder> {
private static String LOG_TAG = "categoryRecyclrVwAdptr";
private ArrayList<CategoryModel.CategoryList> mcategoryset;
private static CategoryClickListener categoryClickListener;
public static class CategoryObjectHolder extends RecyclerView.ViewHolder {
TextView category_name;
/*TextView category_emails;
TextView category_epabx;
TextView category_fax;*/
public CategoryObjectHolder(View itemView){
super(itemView);
category_name=(TextView)itemView.findViewById(R.id.category_name);
/*category_emails=(TextView)itemView.findViewById(R.id.category_emails);
category_epabx=(TextView)itemView.findViewById(R.id.category_epabx);
category_fax=(TextView)itemView.findViewById(R.id.category_fax);*/
Log.i(LOG_TAG, "Adding Listener");
}
// #Override
// public void onClick(View v) {
// categoryClickListener.onItemClick(getAdapterPosition(), v);
// }
}
// public void setOnItemClickListener(CategoryClickListener categoryClickListener) {
// this.categoryClickListener = categoryClickListener;
// }
public RecyclerViewAdapterMain(ArrayList<CategoryModel.CategoryList> myDataset) {
mcategoryset = myDataset;
}
public CategoryObjectHolder onCreateViewHolder(ViewGroup parent,int viewType){
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view_row_main_activity,parent,false);
CategoryObjectHolder categoryObjectHolder=new CategoryObjectHolder(view);
return categoryObjectHolder;
}
#Override
public void onBindViewHolder(CategoryObjectHolder holder, final int position) {
/*final StringBuilder stringBuilder_emails = new StringBuilder();
for (String email : mcategoryset.get(position).getEmails()) {
if (!stringBuilder_emails.toString().isEmpty()) {
stringBuilder_emails.append(", ");
}
stringBuilder_emails.append(email);
}
final StringBuilder stringBuilder_Epabx = new StringBuilder();
for (String epabx : mcategoryset.get(position).getEpabx()) {
if (!stringBuilder_Epabx.toString().isEmpty()) {
stringBuilder_Epabx.append(", ");
}
stringBuilder_Epabx.append(epabx);
}
final StringBuilder stringBuilder_Category_Fax = new StringBuilder();
for (String category_Fax : mcategoryset.get(position).getCategory_Fax()) {
if (!stringBuilder_Category_Fax.toString().isEmpty()) {
stringBuilder_Category_Fax.append(", ");
}
stringBuilder_Category_Fax.append(category_Fax);
}*/
holder.category_name.setText(mcategoryset.get(position).getCategory_name());
/*holder.category_emails.setText(stringBuilder_emails.toString());
holder.category_epabx.setText(stringBuilder_Epabx.toString());
holder.category_fax.setText(stringBuilder_Category_Fax.toString());*/
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent (v.getContext(), PeopleListActivity.class);
i.putParcelableArrayListExtra("Persons",mcategoryset.get(position).getPersons());
i.putStringArrayListExtra("emails",mcategoryset.get(position).getEmails());
//i.putExtras(b);
v.getContext().startActivity(i);
}
});
}
public void addItem(CategoryModel.CategoryList dataObj, int index) {
mcategoryset.add(index, dataObj);
notifyItemInserted(index);
}
public void deleteItem(int index) {
mcategoryset.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount() {
return mcategoryset.size();
}
public interface CategoryClickListener {
public void onItemClick(int position, View v);
}
}
The only way to get data from Firebase Database it's using a ValueEventListener.
Firebase work with asynchronous calls, so you can't call the function, get the data and use it. You have to set a ValueEventListener in a specific database reference.
For your actual problem, you have to create an array, set the Firebase Reference, add the ValueEventListener and inside add each occurrence of CategoryList in the array. Finally , still inside of the ValueEventListener, you can create your CategoryModel, with the CategoryList's array as parameter, and update your UI, to see the data in CategoryModel:
CategoryModel categoryModel;
ArrayList<CategoryList> array = new ArrayList<>();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference categoryRef = database.getReference("Category");
categoryRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
CategoryList categoryList = childSnapshot.getValue(CategoryList.class);
array.add(categoryList);
}
categoryModel = new CategoryModel(array);
// Method to show the data in category model,
// usually populating an ListView or something
updateUI()
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
For have this working, your CategoryList class has to implement all the setters of his members so "datasnapshot.getValue()" works.
Another approach can be, create a Constructor in CategoryList that recibe a DataSnapshot in this way:
public CategoryList(DataSnapshot snapshot){
Category_id = snapshot.child("Category_id").getValue(int.class);
Category_name = snapshot.child("Category_name").getValue(String.class);
GenericTypeIndicator<List<String>> stringList = new GenericTypeIndicator<List<String>>() {};
Emails = snapshot.child("Emails").getValue(stringList);
Epabx= snapshot.child("Epabx").getValue(stringList);
Category_Fax= snapshot.child("Category_Fax").getValue(stringList);
GenericTypeIndicator<List<Persons>> personsList = new GenericTypeIndicator<List<Persons>>() {};
persons = snapshot.child("Persons").getValue(personsList);
}
If you create the constructor, you have to replace this line:
CategoryList categoryList = childSnapshot.getValue(CategoryList.class);
with this:
CategoryList categoryList = new CategoryList(childSnapshot);
You can see that I use GenericTypeIndicator to work with collections of data, this is a helper class provide for Firebase to work with Lists, Maps, Sets or another Collection.
Just a recommendation! This is not a good data structure, you should denormalize your data.Then you can observe your data by ChildEventListener or ValueEventListener.
For example:
-Category
--CategoryId
---CategoryList
---Persons
----user1: true
----user2: true, etc.
-Users
--user1Id
---user1details
--user2Id
---user2details, etc.
Here is some useful links about denormalizing your data
Link1,
Link2

How to return a custom object from ListView using a custom Adapter

especially older programmers. I need some help because I am using a ListView and a Custom Adapter in a commercial application that requires a order menu and in this menu some Edit Texts field.
I am searching for some way to return a custom object with the values that the user placed in the fields, I tried with listView.getItemAtPosition(X) but this return a generic object of Object class and I don't know how to turn this Object into my custom class.
Above goes my custom adapter:
package com.mobile.pedido.pedidomobile.model.adapter;
import android.content.Context;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.mobile.pedido.pedidomobile.*;
import com.mobile.pedido.pedidomobile.dao.local.ItemPedidoTempDAO;
import com.mobile.pedido.pedidomobile.model.ItemPedidoModelo;
import java.util.List;
/**
* Created by MATEUS on 11/02/2017.
*/
public class ProdutoListamgePrecoAdapter extends BaseAdapter {
private Context context;
private List<ItemPedidoModelo> lista;
int cod_pedido;
TextView tv_sequencia, tv_nome_item;
EditText et_quantidade, et_valor;
Button btn_excluir;
public ProdutoListamgePrecoAdapter(Context context, List<ItemPedidoModelo> lista, int cod_pedido) {
this.context = context;
this.lista = lista;
this.cod_pedido = cod_pedido;
}
#Override
public int getCount() {
return lista.size();
}
#Override
public Object getItem(int position) {
return lista.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ItemPedidoModelo itemPedidoModelo = lista.get(position);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.pedidoitempedido_itemprecoadapter, null);
tv_sequencia = (TextView) layout.findViewById(R.id.pedidoitempedido_itemprecoadapter_sequencia);
tv_nome_item = (TextView) layout.findViewById(R.id.pedidoitempedido_listagemadapter_nome);
et_quantidade = (EditText) layout.findViewById(R.id.pedidoitempedido_itemprecoadapter_quantidade);
et_valor = (EditText) layout.findViewById(R.id.pedidoitempedido_itemprecoadapter_preco);
btn_excluir = (Button) layout.findViewById(R.id.pedidoitempedido_itemprecoadapter_excluir);
tv_sequencia.setText(Integer.toString(itemPedidoModelo.getSequencia()));
tv_nome_item.setText(itemPedidoModelo.getNome_item());
et_quantidade.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) {
}
#Override
public void afterTextChanged(Editable s) {
try {
lista.get(position).setQuantidade(et_quantidade.getText().toString());
} catch (Exception e) {
e.printStackTrace();
}
}
});
et_valor.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) {
}
#Override
public void afterTextChanged(Editable s) {
try {
lista.get(position).setPreco(s.toString());
Toast.makeText(context, s, Toast.LENGTH_SHORT).show();
} catch (NumberFormatException e) {
Toast.makeText(context, s, Toast.LENGTH_SHORT).show();
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
}
});
btn_excluir.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (itemPedidoModelo.isAtivo()) {
ItemPedidoTempDAO iptdao = new ItemPedidoTempDAO();
iptdao.excluirItemPedidoTemp(context, cod_pedido, itemPedidoModelo.getSequencia());
btn_excluir.setText("EXCLUIDO");
btn_excluir.setEnabled(false);
btn_excluir.setTextColor(Color.RED);
tv_sequencia.setTextColor(Color.RED);
tv_nome_item.setTextColor(Color.RED);
et_quantidade.setEnabled(false);
et_valor.setEnabled(false);
itemPedidoModelo.setAtivo(false);
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
return layout;
}
}
This is my custom object:
package com.mobile.pedido.pedidomobile.model;
import java.math.BigDecimal;
public class ItemPedidoModelo {
private String cod_prod;
private String cod_pedido;
private String nome_item;
private BigDecimal quantidade;
private BigDecimal preco;
private BigDecimal total_item;
private int sequencia;
private boolean ativo = true;
public BigDecimal getTotal_item() {
return total_item;
}
public void setTotal_item(BigDecimal total_item) {
this.total_item = total_item;
}
public int getSequencia() {
return sequencia;
}
public void setSequencia(int sequencia) {
this.sequencia = sequencia;
}
public void setQuantidade(BigDecimal quantidade) {
this.quantidade = quantidade;
}
public void setPreco(BigDecimal preco) {
this.preco = preco;
}
public ItemPedidoModelo(){};
public ItemPedidoModelo(String cod_prod, String cod_pedido, String nome_item, BigDecimal quantidade, BigDecimal preco, int sequencia) {
super();
this.cod_prod = cod_prod;
this.cod_pedido = cod_pedido;
this.nome_item = nome_item;
this.quantidade = quantidade;
this.preco = preco;
this.sequencia = sequencia;
}
public String getNome_item() {
return nome_item;
}
public void setNome_item(String nome_item) {
this.nome_item = nome_item;
}
public String getCod_pedido() {
return cod_pedido;
}
public void setCod_pedido(String cod_pedido) {
this.cod_pedido = cod_pedido;
}
public String getCod_prod() {
return cod_prod;
}
public void setCod_prod(String cod_prod) {
this.cod_prod = cod_prod;
}
public BigDecimal getQuantidade() {
return quantidade;
}
public void setQuantidade(String quantidade) {
this.quantidade = new BigDecimal(quantidade);
}
public BigDecimal getPreco() {
return preco;
}
public void setPreco(String valor) {
this.preco= new BigDecimal(valor);
}
public boolean isAtivo() {
return ativo;
}
public void setAtivo(boolean ativo) {
this.ativo = ativo;
}
#Override
public String toString() {
return "PedidoItemModelo \ncod_prod=" + cod_prod + "\n cod_pedido=" + cod_pedido + "\n nome_item=" + nome_item
+ "\n quantidade=" + quantidade + "\n preco=" + preco + "\n sequencia=" + sequencia + "]" +"\n\n\n";
}
}
I get it using the following code to acess a child of listView:
View listItem = listView.getChildAt(0);
TextView sequencia = (TextView) listItem.findViewById(R.id.pedidoitempedido_listagemadapter_nome);
I used the method "getChildAt" of listview and after this,I used findViewById with the TextView that i need to get the text value

Multiple Table Android SQLite with Loader Callbacks

I'm trying to create a patient registration app in android but I'm currently stuck on how to achieved a multiple table to relate with and add to loader callback method.
The First table is for patient fullname.
And the Second table is for patient information foreign key to the id of the patient_fullname table.
Can someone here explain or help me on how to achieved this output?
Appreciate for any help.
PatienDBOpenHelper.java
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class PatientDBOpenHelper extends SQLiteOpenHelper{
//Constants for db name and version
private static final String LOGTAG = "DENTALAPP";
private static final String DATABASE_NAME = "dental.db";
private static final int DATABASE_VERSION = 1;
//Constants for identifying table and columns
public static final String TABLE_PATIENT = "patient";
public static final String PATIENT_ID = "_id";
public static final String PATIENT_NAME = "nameInfo";
public static final String PATIENT_GENDER = "genderInfo";
public static final String PATIENT_CREATED = "patientCreated";
/*I will put my desired table structure here
_id
patientId
address
occupation
etc....
*/
public static final String[] ALL_COLUMNS = {PATIENT_ID, PATIENT_NAME, PATIENT_GENDER,PATIENT_CREATED};
//SQL to create table
private static final String TABLE_CREATE_PATIENT =
"CREATE TABLE " + TABLE_PATIENT + " (" +
PATIENT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
PATIENT_NAME + " TEXT, " +
PATIENT_GENDER + " TEXT, " +
PATIENT_CREATED + " TEXT default CURRENT_TIMESTAMP" +
")";
/*
Will also add query statement here for another table.
*/
public PatientDBOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
/*
Add the creation of other table.
*/
sqLiteDatabase.execSQL(TABLE_CREATE_PATIENT);
Log.i(LOGTAG,"Table Created!");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
/*
Add the query of my additional drop table.
*/
sqLiteDatabase.execSQL("DROP TABLE IF EXIST " + TABLE_PATIENT);
onCreate(sqLiteDatabase);
}
}
PatientDataSource.java
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.bloxofcode.multipletabs.model.Patient;
public class PatientDataSource {
private static final String LOGTAG = "DENTALAPP";
SQLiteOpenHelper dbhelper;
SQLiteDatabase database;
public PatientDataSource(Context context){
dbhelper = new PatientDBOpenHelper(context);
}
public void open(){
Log.i(LOGTAG,"Database open");
database = dbhelper.getWritableDatabase();
}
public void close(){
Log.i(LOGTAG,"Database close");
dbhelper.close();
}
public Patient create(Patient patient){
ContentValues values = new ContentValues();
values.put(PatientDBOpenHelper.PATIENT_NAME,patient.getPatientFullName());
values.put(PatientDBOpenHelper.PATIENT_GENDER,patient.getPatientGender());
long id = database.insert(PatientDBOpenHelper.TABLE_PATIENT,null,values);
patient.setId(id);
return patient;
}
}
Tab1.java
public class Tab1 extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>{
private ImageButton imgButton;
private CustomDialog customDialog;
private TextView tvNoRecord;
private ImageView imgNoRecord;
private CursorAdapter cursorAdapter;
PatientDataSource patientDataSource;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
patientDataSource = new PatientDataSource(getActivity());
patientDataSource.open();
final View v =inflater.inflate(R.layout.tab_1,container,false);
imgButton = (ImageButton) v.findViewById(R.id.imageButton);
imgNoRecord = (ImageView) v.findViewById(R.id.imgNoRecord);
tvNoRecord = (TextView) v.findViewById(R.id.tvNoRecord);
//Creating ImageButton
imgButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
customDialog = new CustomDialog(getActivity());
customDialog.setDialogResult(new OnMyDialogResult() {
#Override
public void finish(String resultName, String resultGender) {
if (!resultName.isEmpty()){
Log.d("TestingUnit","asdadasdsa");
Patient patient = new Patient();
patient.setPatientFullName(resultName);
patient.setPatientGender(resultGender);
patientDataSource.create(patient);
restartLoader();
}
listPatient(v);
}
});
customDialog.show();
}
});
listPatient(v);
return v;
}
private void listPatient(View v){
cursorAdapter = new PatientCursorAdapter(getActivity(),null,0 );
ListView list = (ListView) v.findViewById(android.R.id.list);
list.setAdapter(cursorAdapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String info = ((TextView) view.findViewById(R.id.tvName)).getText().toString();
Intent i = new Intent(getContext(), UserInfoActivity.class);
i.putExtra("PersonName", info);
startActivity(i);
}
});
getLoaderManager().initLoader(0,null,this);
}
private void restartLoader(){
getLoaderManager().restartLoader(0,null,this);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(getActivity(), PatientProvider.CONTENT_URI,null,null,null,null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if(data.getCount() > 0){
imgNoRecord.setVisibility(View.INVISIBLE);
tvNoRecord.setVisibility(View.INVISIBLE);
}else{
imgNoRecord.setVisibility(View.VISIBLE);
tvNoRecord.setVisibility(View.VISIBLE);
}
cursorAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
cursorAdapter.swapCursor(null);
}
#Override
public void onResume() {
super.onResume();
patientDataSource.open();
}
#Override
public void onPause() {
super.onPause();
patientDataSource.close();
}
}
This is where i will get the 1st table(patient full name):
This is where the 2nd table will show its data(patient info):

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;
}
}

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