How to update data in a Custom Dialog - android

The user at the moment clicks on a row which contains data and a Dialog with text fields is displayed.
I want the user to update the strings by using this Dialog.
How can I do this?
I have an update method already in my Database Class, but I'm not sure how to implement the update in the Dialog
Database Class
package ie.example.artur.projectrepeat;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
/**
* Created by family on 06/07/2016.
*/
public class DatabaseClass extends SQLiteOpenHelper {
public static final String DATABASE_Name = "Product.db2";
public static final String Table_Name = "product_table2";
public static final String COL_1 = "ID";
public static final String COL_2 = "Name";
public static final String COL_3 = "Quantity";
public static final String COL_4 = "Category";
public static final String COL_5 = "Importance";
Context myContext;
public DatabaseClass(Context context) {
super(context, DATABASE_Name, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + Table_Name + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,Quantity TEXT,Category INTEGER,Importance TEXT);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("Drop Table If Exists" + Table_Name);
onCreate(db);
}
public boolean insertData(String name, String quantity, String category,String importance) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, name);
contentValues.put(COL_3, quantity);
contentValues.put(COL_4, category);
contentValues.put(COL_5, importance);
long result = db.insert(Table_Name, null, contentValues);
if (result == -1)
return false;
else
return true;
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from " + Table_Name, null);
return res;
}
public boolean updateData(String id,String name,String quantity,String category,String importance ) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1, id);
contentValues.put(COL_2, name);
contentValues.put(COL_3, quantity);
contentValues.put(COL_4, category);
contentValues.put(COL_5, importance);
db.update(Table_Name,contentValues,"id =?",new String[]{id});
return true;
}
/* public Cursor getCursor(){
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setR
}
*/
public Integer DeleteData (String id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(Table_Name,"ID = ?",new String[]{id});
}
public static void DeleteInformation(String item_name, SQLiteDatabase sqLiteDatabase){
String selection = COL_1+" LIKE ?";
String [] selection_args = {item_name};
sqLiteDatabase.delete(Table_Name,selection,selection_args);
}
public Cursor getInformation(SQLiteDatabase sqLiteDatabase)
{
Cursor cursor;
String [] Projections = {COL_1,COL_2,COL_4};
cursor = sqLiteDatabase.query(Table_Name,Projections,null,null,null,null,null);
return cursor;
}
public Cursor getItem(String item_name ,SQLiteDatabase sqLiteDatabase){
String [] Projections = {COL_1,COL_2,COL_3,COL_4,COL_5};
String selection = COL_1+" LIKE ?";
String [] selection_args = {item_name};
Cursor cursor = sqLiteDatabase.query(Table_Name,Projections,selection,selection_args,null,null,null);
return cursor;
}
}
EditActivity
package ie.example.artur.projectrepeat;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class Edit_Activity extends AppCompatActivity implements AdapterView.OnItemClickListener {
ListView listView;
SQLiteDatabase sqLiteDatabase;
DatabaseClass database;
Cursor cursor;
ListDataAdapter listDataAdapter;
Dialog d;
EditText editText_name,editText_Quantity,editText_Category,editTextId,editText_Number;
Button updateBtn;
EditText nameEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data_list_layout);
listView = (ListView) findViewById(R.id.list_view);
listDataAdapter = new ListDataAdapter(getApplicationContext(), R.layout.row_layout);
listView.setAdapter(listDataAdapter);
listView.setOnItemClickListener(this);
database = new DatabaseClass(getApplicationContext());
editText_name = (EditText) findViewById(R.id.editText_name);
editText_Quantity = (EditText) findViewById(R.id.editText_Quantity);
editText_Category = (EditText) findViewById(R.id.editText_Category);
editText_Number = (EditText)findViewById(R.id.editText_Number);
editTextId = (EditText) findViewById(R.id.editText_id);
sqLiteDatabase = database.getReadableDatabase();
Cursor cursor=database.getInformation(sqLiteDatabase);
if (cursor.moveToFirst()) {
do {
String id, product_name, category;
id = cursor.getString(0);
product_name = cursor.getString(1);
category = cursor.getString(2);
DataProvider dataProvider = new DataProvider(id, product_name, category);
listDataAdapter.add(dataProvider);
} while (cursor.moveToNext()
);
}
}
public void loginMethod() {
// Create an instance of the dialog fragment and show it
MyDialog dialog = new MyDialog();
dialog.show(getFragmentManager(),"my_dialog");
}
/*
private void showDialog(){
Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.input);
dialog.setTitle("Here Goes the Title");
Button updateBtn = (Button) d.findViewById(R.id.updateBtn);
dialog.show();
}
*/
#Override
public void onItemClick(AdapterView<?> parent, View view, int position , long id) {
TextView tv = (TextView) view.findViewById(R.id.product_id);
sqLiteDatabase = database.getReadableDatabase();
loginMethod();
/*
listView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// custom dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.input);
dialog.setTitle("Title...");
final EditText nameEditText = (EditText) d.findViewById(R.id.product_name);
Button updateBtn = (Button) d.findViewById(R.id.updateBtn);
/* if (position == -1) {
updateBtn.setEnabled(false);
} else
updateBtn.setEnabled(true);
updateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
dialog.show();
}
});
*/
/*private void displayInputDialog(final int pos) {
d = new Dialog(this);
d.setTitle("List View");
d.setContentView(R.layout.input);
final EditText nameEditText = (EditText) d.findViewById(R.id.product_name);
Button updateBtn = (Button) d.findViewById(R.id.updateBtn);
if (pos == -1) {
updateBtn.setEnabled(false);
} else
updateBtn.setEnabled(true);
updateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});*
}*/
}
}
MyDialog Class
package ie.example.artur.projectrepeat;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.graphics.drawable.LayerDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
/**
* Created by family on 12/08/2016.
*/
public class MyDialog extends DialogFragment{
LayoutInflater inflater;
View v;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
inflater = getActivity().getLayoutInflater();
v= inflater.inflate(R.layout.input,null);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(v).setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
return builder.create();
}
}

Here is a neat way to handle custom dialog class!
You can make MyDialog class to contain Builder class so that it handles buttonOnClick methods and text data.
my_dialog_layout.xml should contains 4 editTexts(name, category, quantity, importance) and 3 buttons(update, cancel, ok), as it is shown in your second picture. I won't post the xml code since it's not the critical part.
So in OnItemClickListener of the listView in EditActivity, you can
build the dialog
set default text on edit texts
set onClickListener for buttons
MyDialog class
public class MyDialog extends DialogFragment {
public static final String SimpleName = MyDialog.class.getSimpleName();
private EditText name,category, quantity, importance;
private Button update, positive, negative;
private Builder builder;
private static MyDialog instance = new MyDialog();
public static MyDialog getInstance(){
return instance;
}
#Override
public void onCreate(Bundle savedInstanceState) {
this.setCancelable(true);
if (savedInstanceState != null) {
if (builder != null) {
builder = savedInstanceState.getParcelable(Builder.class.getSimpleName());
}
}
setRetainInstance(true);
super.onCreate(savedInstanceState);
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
// make the dialog's default background transparent so that you can customize the window
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
return dialog;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.my_dialog_layout, container, false);
}
#Override
public void onViewCreated(View view, #Nullable final Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initViews(view);
if (builder != null) {
if (builder.getTextName() != null) {
name.setText(builder.getTextName());
}
if (builder.getTextCategory() != null) {
category.setText(builder.getTextCategory());
}
if (builder.getTextQuantity() != null) {
quantity.setText(builder.getTextQuantity());
}
if (builder.getTextImportance() != null) {
importance.setText(builder.getTextImportance());
}
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
builder.getOnUpdateClicked().OnClick(view, getDialog());
}
});
positive.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
builder.getOnPositiveClicked().OnClick(view, getDialog());
}
});
negative.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
builder.getOnNegativeClicked().OnClick(view, getDialog());
}
});
}
}
private void initViews(View view) {
name = (EditText) view.findViewById(R.id.editText_name);
category = (EditText) view.findViewById(R.id. editText_category);
quantity = (EditText) view.findViewById(R.id. editText_quantity);
importance = (EditText) view.findViewById(R.id.editText_importance);
update = (Button) view.findViewById(R.id.update);
positive = (Button) view.findViewById(R.id.positive);
negative = (Button) view.findViewById(R.id.negative);
}
private Dialog show(Activity activity, Builder builder) {
this.builder = builder;
if (!isAdded()){
show(((AppCompatActivity) activity).getSupportFragmentManager(), SimpleName);
}
return getDialog();
}
public static class Builder implements Parcelable {
private OnPositiveClicked onPositiveClicked;
private OnNegativeClicked onNegativeClicked;
private OnUpdateClicked onUpdateClicked;
private textName;
private textCategory;
private textQuantity;
private textImportance;
private Context context;
protected Builder(Parcel in) {
textName = in.readString();
textCategory = in.readString();
textQuantity = in.readString();
textImportance = in.readString();
}
public static final Creator<Builder> CREATOR = new Creator<Builder>() {
#Override
public Builder createFromParcel(Parcel in) {
return new Builder(in);
}
#Override
public Builder[] newArray(int size) {
return new Builder[size];
}
};
public Context getContext() {
return context;
}
public Builder setActivity(Context context) {
this.context = context;
return this;
}
public Builder(Context context) {
this.context = context;
}
public Builder setTextName(String textName) {
this.textName = textName;
return this;
}
public String getTextName() {
return textName;
}
public Builder setTextCategory(String textCategory) {
this.textCategory = textCategory;
return this;
}
public String getTextCategory() {
return textCategory;
}
public Builder setTextQuantity(String textQuantity) {
this.textQuantity = textQuantity;
return this;
}
public String getTextQuantity() {
return textQuantity;
}
public Builder setTextImportance(String textImportance) {
this.textImportance = textImportance;
return this;
}
public String getTextImportance() {
return textImportance;
}
public OnPositiveClicked getOnPositiveClicked() {
return onPositiveClicked;
}
public Builder setOnPositiveClicked(OnPositiveClicked onPositiveClicked) {
this.onPositiveClicked = onPositiveClicked;
return this;
}
public OnNegativeClicked getOnNegativeClicked() {
return onNegativeClicked;
}
public Builder setOnNegativeClicked(OnNegativeClicked onNegativeClicked) {
this.onNegativeClicked = onNegativeClicked;
return this;
}
public OnUpdateClicked getOnUpdateClicked() {
return onUpdateClicked;
}
public Builder setOnUpdateClicked(OnUpdateClicked onUpdateClicked) {
this.onUpdateClicked = onUpdateClicked;
return this;
}
public Builder build() {
return this;
}
public Dialog show() {
return getInstance().show(((Activity) context), this);
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(textName);
parcel.writeString(textCategory);
parcel.writeString(textQuantity);
parcel.writeString(textImportance);
}
}
public interface OnPositiveClicked {
void OnClick(View view, Dialog dialog);
}
public interface OnNegativeClicked {
void OnClick(View view, Dialog dialog);
}
}
EditActivity
build and show MyDialog in a listview OnItemClickListner.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
MyDialog.Builder dialog=null;
// TODO get the strings from database at the position i
String name =
String category =
String quantity =
String importance =
dialog.setTextName(name)
.setTextCategory(category)
.setTextQuantity(quantity)
.setTextImportance(importance)
.setOnPositiveClicked(new MyDialog.OnPositiveClicked() {
#Override
public void OnClick(View view, Dialog dialog) {
}
})
.setOnNegativeClicked(new MyDialog.OnNegativeClicked() {
#Override
public void OnClick(View view, Dialog dialog) {
}
})
.setOnUpdateClicked(new MyDialog.OnUpdateClicked() {
#Override
public void OnClick(View view, Dialog dialog) {
// TODO update database here
}
})
.build();
dialog.show();
}
});
Hope it helps. Let me know if there is a mistake or a better way.

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

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):

How to update data via custom dialog [duplicate]

The user at the moment clicks on a row which contains data and a Dialog with text fields is displayed.
I want the user to update the strings by using this Dialog.
How can I do this?
I have an update method already in my Database Class, but I'm not sure how to implement the update in the Dialog
Database Class
package ie.example.artur.projectrepeat;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
/**
* Created by family on 06/07/2016.
*/
public class DatabaseClass extends SQLiteOpenHelper {
public static final String DATABASE_Name = "Product.db2";
public static final String Table_Name = "product_table2";
public static final String COL_1 = "ID";
public static final String COL_2 = "Name";
public static final String COL_3 = "Quantity";
public static final String COL_4 = "Category";
public static final String COL_5 = "Importance";
Context myContext;
public DatabaseClass(Context context) {
super(context, DATABASE_Name, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + Table_Name + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,Quantity TEXT,Category INTEGER,Importance TEXT);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("Drop Table If Exists" + Table_Name);
onCreate(db);
}
public boolean insertData(String name, String quantity, String category,String importance) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, name);
contentValues.put(COL_3, quantity);
contentValues.put(COL_4, category);
contentValues.put(COL_5, importance);
long result = db.insert(Table_Name, null, contentValues);
if (result == -1)
return false;
else
return true;
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from " + Table_Name, null);
return res;
}
public boolean updateData(String id,String name,String quantity,String category,String importance ) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1, id);
contentValues.put(COL_2, name);
contentValues.put(COL_3, quantity);
contentValues.put(COL_4, category);
contentValues.put(COL_5, importance);
db.update(Table_Name,contentValues,"id =?",new String[]{id});
return true;
}
/* public Cursor getCursor(){
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setR
}
*/
public Integer DeleteData (String id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(Table_Name,"ID = ?",new String[]{id});
}
public static void DeleteInformation(String item_name, SQLiteDatabase sqLiteDatabase){
String selection = COL_1+" LIKE ?";
String [] selection_args = {item_name};
sqLiteDatabase.delete(Table_Name,selection,selection_args);
}
public Cursor getInformation(SQLiteDatabase sqLiteDatabase)
{
Cursor cursor;
String [] Projections = {COL_1,COL_2,COL_4};
cursor = sqLiteDatabase.query(Table_Name,Projections,null,null,null,null,null);
return cursor;
}
public Cursor getItem(String item_name ,SQLiteDatabase sqLiteDatabase){
String [] Projections = {COL_1,COL_2,COL_3,COL_4,COL_5};
String selection = COL_1+" LIKE ?";
String [] selection_args = {item_name};
Cursor cursor = sqLiteDatabase.query(Table_Name,Projections,selection,selection_args,null,null,null);
return cursor;
}
}
EditActivity
package ie.example.artur.projectrepeat;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class Edit_Activity extends AppCompatActivity implements AdapterView.OnItemClickListener {
ListView listView;
SQLiteDatabase sqLiteDatabase;
DatabaseClass database;
Cursor cursor;
ListDataAdapter listDataAdapter;
Dialog d;
EditText editText_name,editText_Quantity,editText_Category,editTextId,editText_Number;
Button updateBtn;
EditText nameEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data_list_layout);
listView = (ListView) findViewById(R.id.list_view);
listDataAdapter = new ListDataAdapter(getApplicationContext(), R.layout.row_layout);
listView.setAdapter(listDataAdapter);
listView.setOnItemClickListener(this);
database = new DatabaseClass(getApplicationContext());
editText_name = (EditText) findViewById(R.id.editText_name);
editText_Quantity = (EditText) findViewById(R.id.editText_Quantity);
editText_Category = (EditText) findViewById(R.id.editText_Category);
editText_Number = (EditText)findViewById(R.id.editText_Number);
editTextId = (EditText) findViewById(R.id.editText_id);
sqLiteDatabase = database.getReadableDatabase();
Cursor cursor=database.getInformation(sqLiteDatabase);
if (cursor.moveToFirst()) {
do {
String id, product_name, category;
id = cursor.getString(0);
product_name = cursor.getString(1);
category = cursor.getString(2);
DataProvider dataProvider = new DataProvider(id, product_name, category);
listDataAdapter.add(dataProvider);
} while (cursor.moveToNext()
);
}
}
public void loginMethod() {
// Create an instance of the dialog fragment and show it
MyDialog dialog = new MyDialog();
dialog.show(getFragmentManager(),"my_dialog");
}
/*
private void showDialog(){
Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.input);
dialog.setTitle("Here Goes the Title");
Button updateBtn = (Button) d.findViewById(R.id.updateBtn);
dialog.show();
}
*/
#Override
public void onItemClick(AdapterView<?> parent, View view, int position , long id) {
TextView tv = (TextView) view.findViewById(R.id.product_id);
sqLiteDatabase = database.getReadableDatabase();
loginMethod();
/*
listView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// custom dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.input);
dialog.setTitle("Title...");
final EditText nameEditText = (EditText) d.findViewById(R.id.product_name);
Button updateBtn = (Button) d.findViewById(R.id.updateBtn);
/* if (position == -1) {
updateBtn.setEnabled(false);
} else
updateBtn.setEnabled(true);
updateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
dialog.show();
}
});
*/
/*private void displayInputDialog(final int pos) {
d = new Dialog(this);
d.setTitle("List View");
d.setContentView(R.layout.input);
final EditText nameEditText = (EditText) d.findViewById(R.id.product_name);
Button updateBtn = (Button) d.findViewById(R.id.updateBtn);
if (pos == -1) {
updateBtn.setEnabled(false);
} else
updateBtn.setEnabled(true);
updateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});*
}*/
}
}
MyDialog Class
package ie.example.artur.projectrepeat;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.graphics.drawable.LayerDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
/**
* Created by family on 12/08/2016.
*/
public class MyDialog extends DialogFragment{
LayoutInflater inflater;
View v;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
inflater = getActivity().getLayoutInflater();
v= inflater.inflate(R.layout.input,null);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(v).setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
return builder.create();
}
}
Here is a neat way to handle custom dialog class!
You can make MyDialog class to contain Builder class so that it handles buttonOnClick methods and text data.
my_dialog_layout.xml should contains 4 editTexts(name, category, quantity, importance) and 3 buttons(update, cancel, ok), as it is shown in your second picture. I won't post the xml code since it's not the critical part.
So in OnItemClickListener of the listView in EditActivity, you can
build the dialog
set default text on edit texts
set onClickListener for buttons
MyDialog class
public class MyDialog extends DialogFragment {
public static final String SimpleName = MyDialog.class.getSimpleName();
private EditText name,category, quantity, importance;
private Button update, positive, negative;
private Builder builder;
private static MyDialog instance = new MyDialog();
public static MyDialog getInstance(){
return instance;
}
#Override
public void onCreate(Bundle savedInstanceState) {
this.setCancelable(true);
if (savedInstanceState != null) {
if (builder != null) {
builder = savedInstanceState.getParcelable(Builder.class.getSimpleName());
}
}
setRetainInstance(true);
super.onCreate(savedInstanceState);
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
// make the dialog's default background transparent so that you can customize the window
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
return dialog;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.my_dialog_layout, container, false);
}
#Override
public void onViewCreated(View view, #Nullable final Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initViews(view);
if (builder != null) {
if (builder.getTextName() != null) {
name.setText(builder.getTextName());
}
if (builder.getTextCategory() != null) {
category.setText(builder.getTextCategory());
}
if (builder.getTextQuantity() != null) {
quantity.setText(builder.getTextQuantity());
}
if (builder.getTextImportance() != null) {
importance.setText(builder.getTextImportance());
}
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
builder.getOnUpdateClicked().OnClick(view, getDialog());
}
});
positive.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
builder.getOnPositiveClicked().OnClick(view, getDialog());
}
});
negative.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
builder.getOnNegativeClicked().OnClick(view, getDialog());
}
});
}
}
private void initViews(View view) {
name = (EditText) view.findViewById(R.id.editText_name);
category = (EditText) view.findViewById(R.id. editText_category);
quantity = (EditText) view.findViewById(R.id. editText_quantity);
importance = (EditText) view.findViewById(R.id.editText_importance);
update = (Button) view.findViewById(R.id.update);
positive = (Button) view.findViewById(R.id.positive);
negative = (Button) view.findViewById(R.id.negative);
}
private Dialog show(Activity activity, Builder builder) {
this.builder = builder;
if (!isAdded()){
show(((AppCompatActivity) activity).getSupportFragmentManager(), SimpleName);
}
return getDialog();
}
public static class Builder implements Parcelable {
private OnPositiveClicked onPositiveClicked;
private OnNegativeClicked onNegativeClicked;
private OnUpdateClicked onUpdateClicked;
private textName;
private textCategory;
private textQuantity;
private textImportance;
private Context context;
protected Builder(Parcel in) {
textName = in.readString();
textCategory = in.readString();
textQuantity = in.readString();
textImportance = in.readString();
}
public static final Creator<Builder> CREATOR = new Creator<Builder>() {
#Override
public Builder createFromParcel(Parcel in) {
return new Builder(in);
}
#Override
public Builder[] newArray(int size) {
return new Builder[size];
}
};
public Context getContext() {
return context;
}
public Builder setActivity(Context context) {
this.context = context;
return this;
}
public Builder(Context context) {
this.context = context;
}
public Builder setTextName(String textName) {
this.textName = textName;
return this;
}
public String getTextName() {
return textName;
}
public Builder setTextCategory(String textCategory) {
this.textCategory = textCategory;
return this;
}
public String getTextCategory() {
return textCategory;
}
public Builder setTextQuantity(String textQuantity) {
this.textQuantity = textQuantity;
return this;
}
public String getTextQuantity() {
return textQuantity;
}
public Builder setTextImportance(String textImportance) {
this.textImportance = textImportance;
return this;
}
public String getTextImportance() {
return textImportance;
}
public OnPositiveClicked getOnPositiveClicked() {
return onPositiveClicked;
}
public Builder setOnPositiveClicked(OnPositiveClicked onPositiveClicked) {
this.onPositiveClicked = onPositiveClicked;
return this;
}
public OnNegativeClicked getOnNegativeClicked() {
return onNegativeClicked;
}
public Builder setOnNegativeClicked(OnNegativeClicked onNegativeClicked) {
this.onNegativeClicked = onNegativeClicked;
return this;
}
public OnUpdateClicked getOnUpdateClicked() {
return onUpdateClicked;
}
public Builder setOnUpdateClicked(OnUpdateClicked onUpdateClicked) {
this.onUpdateClicked = onUpdateClicked;
return this;
}
public Builder build() {
return this;
}
public Dialog show() {
return getInstance().show(((Activity) context), this);
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(textName);
parcel.writeString(textCategory);
parcel.writeString(textQuantity);
parcel.writeString(textImportance);
}
}
public interface OnPositiveClicked {
void OnClick(View view, Dialog dialog);
}
public interface OnNegativeClicked {
void OnClick(View view, Dialog dialog);
}
}
EditActivity
build and show MyDialog in a listview OnItemClickListner.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
MyDialog.Builder dialog=null;
// TODO get the strings from database at the position i
String name =
String category =
String quantity =
String importance =
dialog.setTextName(name)
.setTextCategory(category)
.setTextQuantity(quantity)
.setTextImportance(importance)
.setOnPositiveClicked(new MyDialog.OnPositiveClicked() {
#Override
public void OnClick(View view, Dialog dialog) {
}
})
.setOnNegativeClicked(new MyDialog.OnNegativeClicked() {
#Override
public void OnClick(View view, Dialog dialog) {
}
})
.setOnUpdateClicked(new MyDialog.OnUpdateClicked() {
#Override
public void OnClick(View view, Dialog dialog) {
// TODO update database here
}
})
.build();
dialog.show();
}
});
Hope it helps. Let me know if there is a mistake or a better way.

recyclerView doesn't show the 'real' data for my list items

I have implemented a recyclerView and a SQLite database to save/retrieve data for the recylerview, but the data I get on the recyclerView is not the data that should show. The recyclerView worked as it should without the SQLite db.
When the plus sign is clicked, a dialog will popup with editext fields, where the user can type the information:
Here is the DialogFragment class where the user shall write their information:
public class DialogAdd extends DialogFragment {
private Button okButton;
private EditText name, quantity, location, normalPrice, offerPrice;
private List<ShopListItem> shopListItem;
private Context context;
DatabaseHelper dbHelper;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dbHelper = new DatabaseHelper(getContext());
shopListItem = new ArrayList<>();
context = getActivity();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.add_productdialog,container, false);
getDialog().setCanceledOnTouchOutside(false);
getDialog().setTitle("Add to shoplist");
name = (EditText) rootView.findViewById(R.id.dialog_productname);
quantity = (EditText) rootView.findViewById(R.id.dialog_qantity);
location = (EditText) rootView.findViewById(R.id.dialog_location);
normalPrice = (EditText) rootView.findViewById(R.id.dialog_normalPrice);
offerPrice = (EditText) rootView.findViewById(R.id.dialog_offerPrice);
okButton = (Button) rootView.findViewById(R.id.dialog_okButton);
okButton.getBackground().setColorFilter(Color.parseColor("#2fbd4b"), PorterDuff.Mode.MULTIPLY);
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (name.getText().toString().isEmpty()) {
Toast.makeText(context, "You must add a name", Toast.LENGTH_LONG).show();
} else {
dbHelper.insertData(name.toString() ,quantity.toString(),location.toString(),normalPrice.toString(),offerPrice.toString());
getDialog().dismiss();
}
}
});
return rootView;
}
This is the mainActivity class where I create the recylerview, adapters and Database:
public class MainActivity extends AppCompatActivity{
private ImageButton addbutton;
private DialogAdd dialogAdd;
public static RecyclerView recyclerView;
private List<ShopListItem> shopListItems;
private SQLiteDatabase db;
private Cursor cursor;
private DatabaseHelper databaseHelper;
private ShoplistAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shoppinglist_mainactivity);
databaseHelper = new DatabaseHelper(this);
addbutton = (ImageButton) findViewById(R.id.addbtn);
addbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialogAdd = new DialogAdd();
dialogAdd.show(getSupportFragmentManager(), "addDialog");
}
});
//RecyclerView
recyclerView = (RecyclerView)findViewById(R.id.rv_shoppinglist);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(App.getAppContex());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
initializeData();
adapter = new ShoplistAdapter(shopListItems);
recyclerView.setAdapter(adapter);
}
private void initializeData(){
shopListItems = new ArrayList<>();
Cursor resultset = databaseHelper.getAllData();
if (resultset.moveToFirst()){
while(!resultset.isAfterLast()){
shopListItems.add(new ShopListItem(resultset.getString(1), resultset.getString(2), resultset.getString(3), resultset.getString(4), resultset.getString(5)));
resultset.moveToNext();
}
}
resultset.close();
shopListItems.add(new ShopListItem("Potato", "2 KG", "MALL", "7 kr", ""));
}
This class is where the database is defined:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME ="dbshoplist.db";
public static final String TABLE_NAME ="product_table";
public static final String COL_ID = "ID";
public static final String COL_NAME ="NAME";
public static final String COL_QTY ="QUANTITY";
public static final String COL_LOCATION ="LOCATION";
public static final String COL_PRICE1 ="PRICE1";
public static final String COL_PRICE2 ="PRICE2";
/*
This constructor creates the database
*/
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
SQLiteDatabase db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,QUANTITY TEXT,LOCATION TEXT,PRICE1 TEXT,PRICE2 TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String name, String qty, String location, String price1, String price2){
SQLiteDatabase db = this.getWritableDatabase();
// content value is a row, and we fill it with the put();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_NAME, name);
contentValues.put(COL_QTY, qty);
contentValues.put(COL_LOCATION, location);
contentValues.put(COL_PRICE1, price1);
contentValues.put(COL_PRICE2, price2);
long result = db.insert(TABLE_NAME, null,contentValues);
if(result == -1) {
return false;
}else{
return true;
}
}
public Cursor getAllData(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursorResults = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
return cursorResults;
}
My recyclerView adapter class:
public class ShoplistAdapter extends RecyclerView.Adapter<ShoplistAdapter.ViewHolder>{
List<ShopListItem> shopListItems;
public ShoplistAdapter(List<ShopListItem> shopListItems) {
this.shopListItems = shopListItems;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View shoplist_itemView = inflater.inflate(R.layout.shop_list_item, parent, false);
ViewHolder viewHolder = new ViewHolder(shoplist_itemView);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.location.setText(shopListItems.get(position).location.toString());
holder.normalPrice.setText(shopListItems.get(position).normalprice.toString());
holder.offerPrice.setText(shopListItems.get(position).offerprice.toString());
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(shopListItems.get(position).quantity + " " + shopListItems.get(position).name);
holder.productname.setText(stringBuilder);
if(!shopListItems.get(position).offerprice.toString().isEmpty()){
holder.normalPrice.setPaintFlags(holder.normalPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
if(shopListItems.get(position).normalprice.isEmpty()){
holder.normalPrice.setVisibility(View.GONE);
}
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked == true){
holder.productname.setPaintFlags(holder.productname.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
holder.productname.setTextColor(Color.parseColor("#40000000"));
}else{
holder.productname.setPaintFlags(0 | Paint.ANTI_ALIAS_FLAG);
holder.productname.setTextColor(Color.BLACK);
}
}
});
}
#Override
public int getItemCount() {
return shopListItems.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder{
private CheckBox checkBox;
private TextView productname, quantity, location, normalPrice, offerPrice;
private ImageButton edit_icon, delete_icon;
public ViewHolder(View itemView) {
super(itemView);
productname = (TextView)itemView.findViewById(R.id.product_name);
location = (TextView)itemView.findViewById(R.id.product_location);
normalPrice = (TextView)itemView.findViewById(R.id.product_price);
offerPrice = (TextView)itemView.findViewById(R.id.product_offer_price);
edit_icon = (ImageButton)itemView.findViewById(R.id.editShopItem_Icon);
delete_icon = (ImageButton)itemView.findViewById(R.id.shopitem_delete_icon);
checkBox = (CheckBox) itemView.findViewById(R.id.bought_checkbox);
}
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
This is happening because you're calling the toString() method of fields of the ShopListItem object: shopListItems.get(position).location.toString().
Instead, create getter methods for the fields of your ShopListItem class, e.g.
public getLocation() {
return location;
}
and just call these to get the data.

Android CursorAdapter not refreshing on first load

EDIT I didn't add my XML
I am writing a dialog for tagging selections. The first view is applying tags they have in their db. The next screen is a dialog for adding new tags to their db. I am supplying suggestions for them to use for their tags. I want to filter the list when they begin typing in their tag. I am using two custom CursorAdapters for each screen but they share the same ListView. I am also using a CursorLoader to run my queries in the background both are extended from the support library.
When I open the new tag screen the first time, after the dialog comes up, the list doesn't refresh with the filtered cursor in Android 4.0.3 nor does the quick scroll work. If I switch to the tag view and then back to the new tag dialog it filters and scrolls like it should.. My query works and the code works in Android 2.3.3 every time. I can't figure out why this is not working. Here is my code for the CursorLoader and the Suggestion adapter.
package org.lds.ldssa;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import org.lds.ldssa.service.MLDatabase;
import org.lds.ldssa.service.aws.Annotation;
public class TagDialog extends AlertDialog implements LoaderManager.LoaderCallbacks<Cursor> {
private static final String TAG = "ldssa.tagdialog";
public static final int TAGLOADERID = 0;
// View Items
private EditText mEditText;
private ListView mListView;
private TextView mEmptyView;
private ProgressBar mProgressBar;
private ImageButton mNewTagButton;
private ImageButton mSortTagButton;
private TextView mTitle;
private Button mOkButton;
private Button mCancelButton;
private String mTagTitle;
private String mNewTagTitle;
private Annotation mAnnotation;
private ContentFragment mContentFragment;
private boolean isNewTagView;
private static final String KEY_NEWTAGVIEW = "new_tag_view";
private SimpleCursorAdapter mSuggestionAdapter;
private TagListAdapter mTagAdapter;
private MLDatabase mlDatabase;
protected TagDialog(Context context) {
super(context);
}
public void onCreate(Bundle savedInstanceState){
Context context = getContext();
Resources r = context.getResources();
final LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.dialog_tag, null);
// Main parts of the view
mEditText = (EditText) view.findViewById(R.id.tag_new_tag);
mListView = (ListView) view.findViewById(android.R.id.list);
mProgressBar = (ProgressBar) view.findViewById(R.id.tag_spin_progress_bar);
mEmptyView = (TextView) view.findViewById(android.R.id.empty);
mEmptyView.setVisibility(View.INVISIBLE);
// Titlebar
View titleBar = inflater.inflate(R.layout.dialog_tag_title, null);
mNewTagButton = (ImageButton) titleBar.findViewById(R.id.tag_new_icon);
mSortTagButton = (ImageButton) titleBar.findViewById(R.id.tag_sort_icon);
mTitle = (TextView) titleBar.findViewById(R.id.tag_title);
mTagTitle = r.getString(R.string.tag_dialog_title);
mNewTagTitle = r.getString(R.string.tag_new_dialog_title);
this.setCustomTitle(titleBar);
// Buttons
final String OK = r.getString(R.string.ok);
final String CANCEL = r.getString(R.string.cancel);
this.setButton(BUTTON_POSITIVE, OK, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) { /*Never Used*/}});
this.setButton(BUTTON_NEGATIVE, CANCEL, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) { /*Never Used*/}});
// Setup Button Listeners
setOnShowListener(new OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
Button ok = getButton(BUTTON_POSITIVE);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isNewTagView){
hideIMM();
setupTagDialog();
mEditText.setText("");
} else {
dismiss();
}
}
});
Button cancel = getButton(BUTTON_NEGATIVE);
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isNewTagView){
hideIMM();
setupTagDialog();
mEditText.setText("");
} else {
dismiss();
}
}
});
}
});
mNewTagButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setupNewTagDialog();
}
});
mSortTagButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
mEditText.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) {
LoaderManager lm = getLoaderManager();
if(lm != null){
Loader l = lm.getLoader(TAGLOADERID);
if(l != null){
l.forceLoad();
} else {
restartLoader();
}
} else {
restartLoader();
}
}
});
String[] UIBindFrom = {MLDatabase.CL_ID};
int[] UIBindTo = {android.R.id.text1};
mTagAdapter = new TagListAdapter(context, null);
mSuggestionAdapter = new SimpleCursorAdapter(context, android.R.layout.simple_list_item_1, null,
UIBindFrom, UIBindTo, 0);
//Handle Rotations
if(savedInstanceState == null){
//New
setupTagDialog();
} else {
//rotated
isNewTagView = savedInstanceState.getBoolean(KEY_NEWTAGVIEW, false);
if(isNewTagView){
restoreTagState(savedInstanceState);
} else {
restoreNewTagState(savedInstanceState);
}
}
LoaderManager lm = getLoaderManager();
if(lm != null){
lm.initLoader(TAGLOADERID, null, this);
}
this.setView(view);
super.onCreate(savedInstanceState);
}
public void onStart(){
restartLoader();
}
#Override
public Bundle onSaveInstanceState(){
Bundle bundle = super.onSaveInstanceState();
bundle.putBoolean(KEY_NEWTAGVIEW, isNewTagView);
return bundle;
}
#Override
public void onBackPressed(){
if(isNewTagView){
hideIMM();
setupTagDialog();
} else {
this.dismiss();
}
}
private void setupTagDialog() {
isNewTagView = false;
mTitle.setText(mTagTitle);
mNewTagButton.setVisibility(View.VISIBLE);
mSortTagButton.setVisibility(View.VISIBLE);
mEditText.setVisibility(View.GONE);
mListView.setVisibility(View.GONE);
mProgressBar.setVisibility(View.VISIBLE);
mListView.setAdapter(mTagAdapter);
restartLoader();
}
private void setupNewTagDialog() {
isNewTagView = true;
mTitle.setText(mNewTagTitle);
mNewTagButton.setVisibility(View.INVISIBLE);
mSortTagButton.setVisibility(View.INVISIBLE);
mEditText.setVisibility(View.VISIBLE);
mListView.setVisibility(View.GONE);
mProgressBar.setVisibility(View.VISIBLE);
mListView.setAdapter(mSuggestionAdapter);
restartLoader();
}
private void restoreTagState(Bundle bundle) {
setupTagDialog();
}
private void restoreNewTagState(Bundle bundle) {
setupNewTagDialog();
}
public void setAnnotation(Annotation a) {
mAnnotation = a;
}
public void setContentViewInterface(ContentFragment contentFragment) {
mContentFragment = contentFragment;
}
private MLDatabase getDatabase() {
if(mlDatabase == null){
GospelLibraryApplication app = (GospelLibraryApplication) getContext().getApplicationContext();
mlDatabase = app.getMlDatabase();
}
return mlDatabase;
}
public String getFilter() {
return mEditText.getText().toString().trim();
}
public Integer getAnnotationID(){
if(mAnnotation != null){
return mAnnotation.getDbKey();
}
return -1;
}
private LoaderManager getLoaderManager(){
if(mContentFragment == null){
Log.d(TAG, "ContentFragment is NULL!");
return null;
}
return mContentFragment.getContentActivity().getSupportLoaderManager();
}
private void restartLoader(){
LoaderManager lm = getLoaderManager();
if(lm != null){
lm.restartLoader(TAGLOADERID, null, this);
}
}
private void hideIMM(){
InputMethodManager imm = (InputMethodManager)getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
TagCursorLoader loader = new TagCursorLoader(getContext(), this);
return loader;
}
#Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor data) {
if(isNewTagView) {
mSuggestionAdapter.changeCursor(data);
} else {
mTagAdapter.changeCursor(data);
}
mListView.invalidateViews();
mProgressBar.setVisibility(View.GONE);
mListView.setVisibility(View.VISIBLE);
}
#Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
if(mSuggestionAdapter != null) {
mSuggestionAdapter.changeCursor(null);
}
}
public static class TagCursorLoader extends CursorLoader {
private final ForceLoadContentObserver mObserver = new ForceLoadContentObserver();
private TagDialog dialog;
private MLDatabase mlDatabase;
private Cursor mCursor;
private String mFilter;
private Integer mAnnotationID;
// Runs on worker thread
#Override
public Cursor loadInBackground(){
Cursor cursor = null;
if(dialog.isNewTagView){
mFilter = dialog.getFilter();
cursor = mlDatabase.getTagSuggestions(mFilter);
} else {
mAnnotationID = dialog.getAnnotationID();
}
if(cursor != null){
cursor.registerContentObserver(mObserver);
}
return cursor;
}
//Runs on UI thread
#Override
public void deliverResult(Cursor cursor){
//Handle if canceled in the middle.
if(isReset()){
if(cursor != null){
cursor.close();
}
return;
}
Cursor oldCursor = mCursor;
mCursor = cursor;
if(isStarted()) {
super.deliverResult(cursor);
}
if(oldCursor != null && !oldCursor.equals(cursor) && !oldCursor.isClosed()) {
oldCursor.close();
}
}
public TagCursorLoader(Context context, TagDialog dialog) {
super(context);
this.dialog = dialog;
mlDatabase = dialog.getDatabase();
}
#Override
public void onStartLoading(){
if(mCursor == null) {
forceLoad();
} else {
if(dialog.isNewTagView && mFilter.equals(dialog.getFilter())) {
deliverResult(mCursor);
} else {
forceLoad();
}
}
}
#Override
protected void onStopLoading() {
// Attempt to cancel the current load task if possible.
cancelLoad();
}
#Override
public void onCanceled(Cursor cursor) {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
#Override
protected void onReset() {
super.onReset();
// Ensure the loader is stopped
onStopLoading();
if (mCursor != null && !mCursor.isClosed()) {
mCursor.close();
}
mCursor = null;
}
}
}
package org.lds.ldssa;
import android.R;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.CursorAdapter;
import android.widget.TextView;
import org.lds.ldssa.service.MLDatabase;
public class TagSuggestionAdapter extends CursorAdapter {
public TagSuggestionAdapter(Context context, Cursor cursor, int flags){
super(context, cursor, flags);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.simple_list_item_1, parent, false);
bindView(v, context, cursor);
return v;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView tv = (TextView) view.findViewById(R.id.text1);
tv.setText(cursor.getString(cursor.getColumnIndex(MLDatabase.CL_ID)));
}
}
Thanks in Advance for any help.
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tag_layout"
android:orientation="vertical"
android:layout_height="wrap_content"
android:layout_width="#dimen/min_dialog_width"
android:padding="5dp"
android:animateLayoutChanges="true"
>
<!-- Here is the view to show if the list is emtpy -->
<TextView
android:id="#android:id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="50dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_centerInParent="true"
android:gravity="center"
android:text="#string/no_items"
android:visibility="invisible"
/>
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="invisible"
/>
<ProgressBar
android:id="#+id/tag_spin_progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:indeterminate="true"
/>
</RelativeLayout>
Try it without
android:animateLayoutChanges="true"
... in your XML layout.

Categories

Resources