Can't access ArrayAdapter from AlertDialog - java

TL;DR
I don't understand how to change my ArrayList dataset from a dialog so that it updates my listview. My current solution crashes because the ListView doesn't update. Need to know where my code is going wrong.
The Problem
I have one activity that has a ListView of items with an ArrayAdapter that connects it to my data (ArrayList). When a user clicks on an item in that list I load an AlertDialog that allows the user to delete that item. Debugging shows that the item does get removed from the data, the dialog closes as expected but the ListView doesn't update and subsequent clicks cause the app to crash.
The problem seems to be tied to the itemsList.notifyDataSetChanged();. I've tried hitting the adapter instead but then the Adapter itself can't be resolved.
I know this is due to an error on my part but I can't find where I'm going wrong.
The Code
ScannerActivity.java
import android.content.Intent;
import android.graphics.pdf.PdfDocument;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class ScannerActivity extends AppCompatActivity {
Button delete, deleteAll, manual, export, newPull;
EditText input_main;
static int pulls = 001;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scanner);
//Load some items for testing
final PullSheet pullSheet = new PullSheet();
pullSheet.createSheet(nameText, roleText, storeText, runitText);
pullSheet.addItem("12543", 5);
pullSheet.addItem("3526", 1);
pullSheet.addItem("00045", 3);
pullSheet.addItem("95462", 18);
pullSheet.addItem("1181", 53);
pullSheet.addItem("6543", 1);
final ArrayAdapter<PullItem> itemAdapter =
new ArrayAdapter<PullItem>(this, 0, pullSheet.SheetItems) {
#Override
public View getView(int position,
View convertView,
ViewGroup parent){
PullItem currentItem = getItem(position);//
if(convertView == null) {
convertView = getLayoutInflater()
.inflate(R.layout.item, null, false);
}
TextView itemSku =
(TextView)convertView.findViewById(R.id.item_sku);
TextView itemQty =
(TextView)convertView.findViewById(R.id.item_qty);
itemSku.setText(currentItem.sku);
itemQty.setText(String.valueOf(currentItem.qty));
return convertView;
}
};
final ListView itemsList = (ListView) findViewById(R.id.itemsList);
itemsList.setAdapter(itemAdapter);
itemsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(final AdapterView<?> itemAdapter,
View view, int position, long rowId) {
final PullItem item = pullSheet.SheetItems.get(position);
final PullSheet sheet = pullSheet;
//load dialog
final AlertDialog.Builder mBuilder = new AlertDialog.Builder(ScannerActivity.this);
final View mView = getLayoutInflater().inflate(R.layout.dialog_interact, null);
//Declare dialog ui elements
Button mYes = (Button) mView.findViewById(R.id.btnYes);
Button mNo = (Button) mView.findViewById(R.id.btnNo);
TextView skuData = (TextView) mView.findViewById(R.id.skuData);
TextView qtyData = (TextView) mView.findViewById(R.id.qtyData);
skuData.setText(item.sku);
qtyData.setText(item.qty.toString());
mBuilder.setView(mView);
final AlertDialog dialog = mBuilder.create();
dialog.show();
mYes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deletePullItem(sheet, item);
itemsList.notifyDataSetChanged();// This isn't working, "Cannot resolve method notifyDataSetChanged()"
dialog.dismiss();
}
});
mNo.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
});
}
public void deletePullItem(PullSheet sheet, PullItem item)
{
sheet.removeItem(item);
}
}
PullSheet.java
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.UUID;
public class PullSheet extends Application{
protected String pullerName;
protected String role;
protected String store;
protected String sheetId;
protected String runItId;
protected Long startTime = System.currentTimeMillis();
protected ArrayList<PullItem> SheetItems = new ArrayList<PullItem>();
public void createSheet(String _pullerName, String _role, String _store, String _runItId){
setPullerName(_pullerName);
setRole(_role);
setStore(_store);
setRunItId(_runItId);
setSheetId();
}
protected void addItem(String sku, Integer qty){
SheetItems.add(new PullItem(sku, qty));
}
protected void removeItem(PullItem item){
this.SheetItems.remove(item);
}
//Getters and setters
public String getPullerName(){ return pullerName; }
public String getRole(){
return role;
}
public String getStore(){
return store;
}
public String getRunItId(){
return runItId;
}
public String getSheetId(){
return sheetId;
}
public Long getStartTime(){
return startTime;
}
private void setPullerName(String _pullerName){ pullerName = _pullerName; }
private void setRole(String _role){ pullerName = _role; }
private void setStore(String _store){ store = _store; }
private void setRunItId(String _runItId){ runItId = _runItId; }
private void setSheetId(){
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
String dateString = formatter.format(new Date(startTime));
UUID uuid = UUID.randomUUID();
String randUUID = uuid.toString();
sheetId = dateString + "-" + this.pullerName + "-" + randUUID + "-" + runItId;
}
}
PullItem.java
public class PullItem {
protected String sku;
protected Integer qty;
public PullItem(String sku, Integer qty) {
setSku(sku);
this.qty = 1;
}
String getSku(){ return sku; }
Integer getQty(){ return qty; }
void setSku(String _sku){ sku = _sku; }
void setQty(Integer _qty){ qty = _qty; }
void incrementQty(){ qty += 1; }
}
The Solution
I need to be told where I'm going wrong. I know it has to do with the ArrayAdapter and the ListView, but Everything I've tried just moves the "Can't resolve" to another part of the expression.
Thanks in advance for any help

notifyDatasetChanged() is an Adapter method, so you can't use it with ListView
But this should work:
Make your Adapter a member variable (instantiate it the way you did) so you can access it everywhere in the Activity:
private ArrayAdapter<PullItem> itemAdapter;
Simply call deletePullItem() if the user clicks the OK-Button:
mYes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deletePullItem(sheet, item);
dialog.dismiss();
}
});
And call notifyDatasetChanged() when really deleting the item:
public void deletePullItem(PullSheet sheet, PullItem item)
{
sheet.removeItem(item);
itemAdapter.notifyDatasetChanged();
}

Try this:
mYes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deletePullItem(sheet, item);
itemsList.getAdapter().notifyDataSetChanged();
dialog.dismiss();
}
});

Related

Android Studio - Passing variable with intent add extra, ends up with null

after fixing the null pointer exception of a previous question, (Not sure if posting a different question for the same code is okay, do let me know if it is not) I've come across a new problem. When I try passing the date variable from this first activity to another, it is always empty. I've also tried just setting a public getter or the variable and it is also empty. However, using a toast to check within the class shows that the variable does indeed contain the date. I am trying to pass the date class to be added into a database by the other classes in the application package. Any help would be much appreciated.
CalendarActivity.java
package com.example.zaphk.studenthelperapplication3.calendar;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.CalendarView;
import android.widget.Toast;
import com.example.zaphk.studenthelperapplication3.R;
public class CalendarActivity extends AppCompatActivity {
public static final String EXTRA_TEXT = "com.example.zaphk.studenthelperapplication3";
private static final String TAG = "CalendarActivity";
private CalendarView mCalendarView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calendar_layout);
mCalendarView = (CalendarView) findViewById(R.id.calendarView);
mCalendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
#Override
public void onSelectedDayChange(CalendarView CalendarView, int year, int month, int dayOfMonth) {
String date = year + "/" + month + "/"+ dayOfMonth ;
Log.d(TAG, "onSelectedDayChange: yyyy/mm/dd:" + date);
Intent intent = new Intent(CalendarActivity.this,CalendarEvent.class);
intent.putExtra(Intent.EXTRA_TEXT,date);
startActivity(intent);
Toast.makeText(CalendarActivity.this,date,Toast.LENGTH_SHORT).show();
}
});
}
}
The class I am trying to receive it from : CalendarEvent.java
package com.example.zaphk.studenthelperapplication3.calendar;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import com.example.zaphk.studenthelperapplication3.calendar.database.Calendar;
import com.example.zaphk.studenthelperapplication3.calendar.database.CalendarAdapter;
import com.example.zaphk.studenthelperapplication3.calendar.database.Calendar_DbHelper;
import com.example.zaphk.studenthelperapplication3.utils.MyDividerItemDecoration;
import com.example.zaphk.studenthelperapplication3.utils.RecyclerTouchListener;
import com.example.zaphk.studenthelperapplication3.R;
public class CalendarEvent extends AppCompatActivity {
private CalendarAdapter mAdapter;
private List<Calendar> notesList = new ArrayList<>();
private CoordinatorLayout coordinatorLayout;
private RecyclerView recyclerView;
private TextView noNotesView;
Intent intent = getIntent();
public String date;
private Calendar_DbHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
intent = getIntent();
date = intent.getStringExtra(CalendarActivity.EXTRA_TEXT);
setContentView(R.layout.activity_notes);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
coordinatorLayout = findViewById(R.id.coordinator_layout);
recyclerView = findViewById(R.id.recycler_view);
noNotesView = findViewById(R.id.empty_notes_view);
db = new Calendar_DbHelper(this);
notesList.addAll(db.getAllNotes());
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showNoteDialog(false, null, -1);
}
});
mAdapter = new CalendarAdapter(this, notesList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.addItemDecoration(new MyDividerItemDecoration(this, LinearLayoutManager.VERTICAL, 16));
recyclerView.setAdapter(mAdapter);
toggleEmptyNotes();
/**
* On long press on RecyclerView item, open alert dialog
* with options to choose
* Edit and Delete
* */
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(this,
recyclerView, new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, final int position) {
}
#Override
public void onLongClick(View view, int position) {
showActionsDialog(position);
}
}));
}
/**
* Inserting new note in db
* and refreshing the list
*/
private void createNote(String note) {
// inserting note in db and getting
// newly inserted note id
long id = db.insertNote(note);
// get the newly inserted note from db
Calendar n = db.getNote(id);
if (n != null) {
// adding new note to array list at 0 position
notesList.add(0, n);
// refreshing the list
mAdapter.notifyDataSetChanged();
toggleEmptyNotes();
}
}
/**
* Updating note in db and updating
* item in the list by its position
*/
private void updateNote(String note, int position) {
Calendar n = notesList.get(position);
// updating note text
n.setNote(note);
// updating note in db
db.updateNote(n);
// refreshing the list
notesList.set(position, n);
mAdapter.notifyItemChanged(position);
toggleEmptyNotes();
}
/**
* Deleting note from SQLite and removing the
* item from the list by its position
*/
private void deleteNote(int position) {
// deleting the note from db
db.deleteNote(notesList.get(position));
// removing the note from the list
notesList.remove(position);
mAdapter.notifyItemRemoved(position);
toggleEmptyNotes();
}
/**
* Opens dialog with Edit - Delete options
* Edit - 0
* Delete - 0
*/
private void showActionsDialog(final int position) {
CharSequence colors[] = new CharSequence[]{"Edit", "Delete"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose option");
builder.setItems(colors, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
showNoteDialog(true, notesList.get(position), position);
} else {
deleteNote(position);
}
}
});
builder.show();
}
/**
* Shows alert dialog with EditText options to enter / edit
* a note.
* when shouldUpdate=true, it automatically displays old note and changes the
* button text to UPDATE
*/
private void showNoteDialog(final boolean shouldUpdate, final Calendar note, final int position) {
LayoutInflater layoutInflaterAndroid = LayoutInflater.from(getApplicationContext());
View view = layoutInflaterAndroid.inflate(R.layout.note_dialog, null);
AlertDialog.Builder alertDialogBuilderUserInput = new AlertDialog.Builder(CalendarEvent.this);
alertDialogBuilderUserInput.setView(view);
final EditText inputNote = view.findViewById(R.id.note);
TextView dialogTitle = view.findViewById(R.id.dialog_title);
dialogTitle.setText(!shouldUpdate ? getString(R.string.lbl_new_note_title) : getString(R.string.lbl_edit_note_title));
if (shouldUpdate && note != null) {
inputNote.setText(note.getNote());
}
alertDialogBuilderUserInput
.setCancelable(false)
.setPositiveButton(shouldUpdate ? "update" : "save", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogBox, int id) {
}
})
.setNegativeButton("cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogBox, int id) {
dialogBox.cancel();
}
});
final AlertDialog alertDialog = alertDialogBuilderUserInput.create();
alertDialog.show();
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Show toast message when no text is entered
if (TextUtils.isEmpty(inputNote.getText().toString())) {
Toast.makeText(CalendarEvent.this, "Enter note!", Toast.LENGTH_SHORT).show();
return;
} else {
alertDialog.dismiss();
}
// check if user updating note
if (shouldUpdate && note != null) {
// update note by it's id
updateNote(inputNote.getText().toString(), position);
} else {
// create new note
createNote(inputNote.getText().toString());
}
}
});
}
/**
* Toggling list and empty notes view
*/
private void toggleEmptyNotes() {
// you can check notesList.size() > 0
if (db.getNotesCount() > 0) {
noNotesView.setVisibility(View.GONE);
} else {
noNotesView.setVisibility(View.VISIBLE);
}
}
public String getDate(){
return date;
}
}
You are using wrong key while passing data between activity.
Replace below line,
intent.putExtra(Intent.EXTRA_TEXT,date);
With this one,
intent.putExtra(CalendarActivity.EXTRA_TEXT,date);
You use the key of Intent.EXTRA_TEXT.
intent.putExtra(Intent.EXTRA_TEXT,date)
But you use the other key to receive. It's not the same key.
intent.getStringExtra(CalendarActivity.EXTRA_TEXT);
As per I know (Not pretty sure)
Intent.EXTRA_TEXT
is used for implicit intents.
For explicit (i.e.Activity to Activity)
Do as below
Intent intent = new Intent(CalendarActivity.this,CalendarEvent.class);
intent.putExtra("DATE",date);
startActivity(intent);
To receive
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_notes);
intent = getIntent();
String date = intent.getStringExtra("DATE");
}
Where "DATE" is String KEY.
I would say that CalendarActivity.EXTRA_TEXT is probably empty because you have not imported that class in to CalendarEvent.java
import com.example.zaphk.studenthelperapplication3.calendar.CalendarActivity; in CalendarEvent.java
and as other people have said the put and get on the Intent need to be the the same String value.

recycler view does not refresh and show data

in my recycler view , when data get added , recycelr view does not show it until user close the activity and open it another time.
I think it has something to do with notifydataetchanger.
please help me with this
the only thing that worked by now was to creating an Intent .
but it makes app to loob very bad
my adaptor
package com.example.myapplication;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class Rec_adaptor_aza extends RecyclerView.Adapter<Rec_adaptor_aza.ViewHolder> {
Context context;
public Rec_adaptor_aza(Context context, List<Model_aza> list_aza) {
this.context = context;
this.list_aza = list_aza;
}
List<Model_aza> list_aza;
#NonNull
#Override
public Rec_adaptor_aza.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(context).inflate(R.layout.rec_row_aza,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull Rec_adaptor_aza.ViewHolder holder, int position) {
Model_aza modelAza =list_aza.get(position);
holder.txt_name.setText(modelAza.getName_aza());
holder.txt_semat.setText(modelAza.getSemat_aza());
holder.txt_saat_voood.setText(modelAza.getSaaat_vorood_aza());
holder.txt_saat_khoroo.setText(modelAza.getSaat_khorooj_aza());
}
#Override
public int getItemCount() {
return list_aza.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView txt_name,txt_semat,txt_saat_voood,txt_saat_khoroo;
public ViewHolder(#NonNull View itemView) {
super(itemView);
txt_name=itemView.findViewById(R.id.txt__person__name);
txt_semat=itemView.findViewById(R.id.txt__person__semat);
txt_saat_voood=itemView.findViewById(R.id.txt__person__enter);
txt_saat_khoroo=itemView.findViewById(R.id.txt__person__out);
}
}
}
my model class
package com.example.myapplication;
public class Model_aza {
private String name_aza;
private String semat_aza;
private String saaat_vorood_aza;
public String getName_aza() {
return name_aza;
}
public void setName_aza(String name_aza) {
this.name_aza = name_aza;
}
public String getSemat_aza() {
return semat_aza;
}
public void setSemat_aza(String semat_aza) {
this.semat_aza = semat_aza;
}
public String getSaaat_vorood_aza() {
return saaat_vorood_aza;
}
public void setSaaat_vorood_aza(String saaat_vorood_aza) {
this.saaat_vorood_aza = saaat_vorood_aza;
}
public String getSaat_khorooj_aza() {
return saat_khorooj_aza;
}
public void setSaat_khorooj_aza(String saat_khorooj_aza) {
this.saat_khorooj_aza = saat_khorooj_aza;
}
private String saat_khorooj_aza;
}
My activity
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class Activity_Gozaresh_giri extends AppCompatActivity {
private static final String TAG = "gozaresh_activity";
List<Model_aza> list_aza;
Rec_adaptor_aza rec_adaptor_aza;
public static Context context;
SQLiteDatabase sqLiteDatabase;
ImageButton btn__add__field, btn__add__field1;
final DataBase_aza dataBase_aza = new DataBase_aza(this);
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gozaresh_giri);
btn__add__field1 = findViewById(R.id.btn__add__field1);
btn__add__field = findViewById(R.id.btn__add__field);
int id=getIntent().getIntExtra("id",0);
list_aza = new ArrayList<>();
Log.d(TAG, "onCreate: onclicked");
btn__add__field.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText edtname = findViewById(R.id.edt__person__name);
EditText edt_semat_aza = findViewById(R.id.edt__person__semat);
EditText edt_vorood_aza = findViewById(R.id.edt__person__enter);
EditText edt_khorooj_aza = findViewById(R.id.edt__person__out);
String name_aza = edtname.getText().toString();
String semat_aza = edt_semat_aza.getText().toString();
String saat_vorood_aza = edt_vorood_aza.getText().toString();
String saat_khorooj_aza = edt_khorooj_aza.getText().toString();
long result = dataBase_aza.insert_info(name_aza, semat_aza, saat_vorood_aza, saat_khorooj_aza,id);
Toast.makeText(Activity_Gozaresh_giri.this, result + "", Toast.LENGTH_SHORT).show();
}
});
Cursor cursor1 = dataBase_aza.cursor(id);
for (cursor1.moveToFirst(); !cursor1.isAfterLast(); cursor1.moveToNext()) {
Model_aza modelAza = new Model_aza();
modelAza.setName_aza(cursor1.getString(1));
modelAza.setSemat_aza(cursor1.getString(2));
modelAza.setSaaat_vorood_aza(cursor1.getString(3));
modelAza.setSaat_khorooj_aza(cursor1.getString(4));
list_aza.add(modelAza);
}
RecyclerView recyclerView_aza = findViewById(R.id.rec_aza);
recyclerView_aza.setAdapter(new Rec_adaptor_aza(this, list_aza));
recyclerView_aza.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
}
}
my data base
package com.example.myapplication;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
public class DataBase_aza extends SQLiteOpenHelper {
public DataBase_aza(#Nullable Context context) {
super(context, "datbase_aza", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL("create table if not exists database_aza (_id integer primary key autoincrement,_name varcher(55) not null,_semat varcher(55) not null, _vorood varcher(6) not null, _khorooj varchar(22) not null, id__item__gozaresh integer(55))");
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public long insert_info(String name, String semat, String vorood, String khorooj, int id) {
ContentValues cv = new ContentValues();
cv.put("_name", name);
cv.put("_semat", semat);
cv.put("_vorood", vorood);
cv.put("_khorooj", khorooj);
cv.put("id__item__gozaresh", id);
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
return sqLiteDatabase.insert("database_aza", null, cv);
}
public Cursor cursor(int id) {
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
return sqLiteDatabase.rawQuery("SELECT * FROM database_aza where id__item__gozaresh="+id, null);
}
}
I want recycler view to show data as soon as user clicks on add button
after adding entry just notify data set changed to adapter like below
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gozaresh_giri);
btn__add__field1 = findViewById(R.id.btn__add__field1);
btn__add__field = findViewById(R.id.btn__add__field);
int id=getIntent().getIntExtra("id",0);
list_aza = new ArrayList<>();
Log.d(TAG, "onCreate: onclicked");
rec_adaptor_aza = new Rec_adaptor_aza(this, list_aza);
RecyclerView recyclerView_aza = findViewById(R.id.rec_aza);
recyclerView_aza.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
recyclerView_aza.setAdapter(rec_adaptor_aza);
Cursor cursor1 = dataBase_aza.cursor(id);
for (cursor1.moveToFirst(); !cursor1.isAfterLast(); cursor1.moveToNext()) {
Model_aza modelAza = new Model_aza();
modelAza.setName_aza(cursor1.getString(1));
modelAza.setSemat_aza(cursor1.getString(2));
modelAza.setSaaat_vorood_aza(cursor1.getString(3));
modelAza.setSaat_khorooj_aza(cursor1.getString(4));
list_aza.add(modelAza);
}
rec_adaptor_aza.notifyDataSetChanged();
btn__add__field.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText edtname = findViewById(R.id.edt__person__name);
EditText edt_semat_aza = findViewById(R.id.edt__person__semat);
EditText edt_vorood_aza = findViewById(R.id.edt__person__enter);
EditText edt_khorooj_aza = findViewById(R.id.edt__person__out);
String name_aza = edtname.getText().toString();
String semat_aza = edt_semat_aza.getText().toString();
String saat_vorood_aza = edt_vorood_aza.getText().toString();
String saat_khorooj_aza = edt_khorooj_aza.getText().toString();
long result = dataBase_aza.insert_info(name_aza, semat_aza, saat_vorood_aza, saat_khorooj_aza,id);
rec_adaptor_aza.notifyDataSetChanged(); // change here
Toast.makeText(Activity_Gozaresh_giri.this, result + "", Toast.LENGTH_SHORT).show();
}
});
}
Use it like below:-
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gozaresh_giri);
btn__add__field1 = findViewById(R.id.btn__add__field1);
btn__add__field = findViewById(R.id.btn__add__field);
int id=getIntent().getIntExtra("id",0);
list_aza = new ArrayList<>();
Rec_adaptor_aza adapter = new Rec_adaptor_aza(this, list_aza); // Add
RecyclerView recyclerView_aza = findViewById(R.id.rec_aza);
recyclerView_aza.setAdapter(adapter);
recyclerView_aza.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
btn__add__field.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText edtname = findViewById(R.id.edt__person__name);
EditText edt_semat_aza = findViewById(R.id.edt__person__semat);
EditText edt_vorood_aza = findViewById(R.id.edt__person__enter);
EditText edt_khorooj_aza = findViewById(R.id.edt__person__out);
String name_aza = edtname.getText().toString();
String semat_aza = edt_semat_aza.getText().toString();
String saat_vorood_aza = edt_vorood_aza.getText().toString();
String saat_khorooj_aza = edt_khorooj_aza.getText().toString();
long result = dataBase_aza.insert_info(name_aza, semat_aza, saat_vorood_aza, saat_khorooj_aza,id);
Model_aza modelAza = new Model_aza(); // Add
modelAza.setName_aza(name_aza);// Add
modelAza.setSemat_aza(semat_aza);// Add
modelAza.setSaaat_vorood_aza(saat_vorood_aza);// Add
modelAza.setSaat_khorooj_aza(saat_khorooj_aza);// Add
list_aza.add(modelAza);// Add
adapter.notifyDataSetChanged();// Add
Toast.makeText(Activity_Gozaresh_giri.this, result + "", Toast.LENGTH_SHORT).show();
}
});
Cursor cursor1 = dataBase_aza.cursor(id);
for (cursor1.moveToFirst(); !cursor1.isAfterLast(); cursor1.moveToNext()) {
Model_aza modelAza = new Model_aza();
modelAza.setName_aza(cursor1.getString(1));
modelAza.setSemat_aza(cursor1.getString(2));
modelAza.setSaaat_vorood_aza(cursor1.getString(3));
modelAza.setSaat_khorooj_aza(cursor1.getString(4));
list_aza.add(modelAza);
}
adapter.notifyDataSetChanged();// Add
}
Just add the below code, in your clickListner, you need to add the same object in your list, and after adding you need to notify the adapter about the inserted item, by using notifyDataSetChanged().
btn__add__field.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText edtname = findViewById(R.id.edt__person__name);
EditText edt_semat_aza = findViewById(R.id.edt__person__semat);
EditText edt_vorood_aza = findViewById(R.id.edt__person__enter);
EditText edt_khorooj_aza = findViewById(R.id.edt__person__out);
String name_aza = edtname.getText().toString();
String semat_aza = edt_semat_aza.getText().toString();
String saat_vorood_aza = edt_vorood_aza.getText().toString();
String saat_khorooj_aza = edt_khorooj_aza.getText().toString();
long result = dataBase_aza.insert_info(name_aza, semat_aza, saat_vorood_aza, saat_khorooj_aza,id);
Toast.makeText(Activity_Gozaresh_giri.this, result + "", Toast.LENGTH_SHORT).show();
/*
* Adding entered data in list*/
Model_aza mm=new Model_aza();
mm.setName_aza(name_aza);
mm.setSemat_aza(semat_aza);
mm.setSaaat_vorood_aza(saat_vorood_aza);
mm.setSaat_khorooj_aza(saat_khorooj_aza);
list_aza.add(mm);
rec_adaptor_aza.notifyDataSetChanged();
}
});
Set layoutmanager before set the adapter to recylerview in your activity, like below
RecyclerView recyclerView_aza = findViewById(R.id.rec_aza);
// set layout manager before set adapter
recyclerView_aza.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
recyclerView_aza.setAdapter(new Rec_adaptor_aza(this, list_aza));

How to save button state in shared preference?

I am new to android development and I have custom ListView which have favourite and removefavourite button now i want save this button state in SharedPreferences please tell me how i can save this button state in shared preference when user click on favourite button, the button change into favourite and when click on favourite the button change into removefavourite here is my code?
holder.addfavoruite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ischeckd=true;
holder.addfavoruite.setVisibility(View.GONE);
holder.removefavoruite.setVisibility(View.VISIBLE);
}
});
holder.removefavoruite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ischeckd=false;
holder.addfavoruite.setVisibility(View.VISIBLE);
holder.removefavoruite.setVisibility(View.GONE);
}
});
My custom ListView whole code
package bible.swordof.God;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.opengl.Visibility;
import android.preference.PreferenceManager;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.amulyakhare.textdrawable.TextDrawable;
import com.amulyakhare.textdrawable.util.ColorGenerator;
import com.hitomi.cmlibrary.CircleMenu;
import com.hitomi.cmlibrary.OnMenuSelectedListener;
import com.hitomi.cmlibrary.OnMenuStatusChangeListener;
import java.util.List;
import java.util.Locale;
import es.dmoral.toasty.Toasty;
import static android.content.Context.MODE_PRIVATE;
import static android.database.sqlite.SQLiteDatabase.CONFLICT_NONE;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.V;
import static android.support.constraint.Constraints.TAG;
import static android.support.v4.content.ContextCompat.createDeviceProtectedStorageContext;
import static android.support.v4.content.ContextCompat.startActivity;
public class FullverseAdopter extends ArrayAdapter<String> {
private ALLVERSE activity;
private List<String> versenumber;
private List<String>verseid;
private List<String> verselist;
private List<String> refernce;
TextToSpeech textToSpeech;
private DatabaseHelper mDBHelper;
private SQLiteDatabase mDb;
private boolean ischeckd;
String My_PREF="MY_PREF";
SharedPreferences sharedPreferences;
//check for availabe language
int result;
public FullverseAdopter(ALLVERSE context, int resource, List<String> versenumber, List<String> verselist, List<String> refernce, List<String>verseid) {
super(context, resource, versenumber);
this.activity = context;
this.versenumber = versenumber;
this.verselist = verselist;
this.refernce = refernce;
this.verseid=verseid;
}
#Override
public int getCount() {
return versenumber.size();
}
#Override
public String getItem(int position) {
return versenumber.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
// If holder not exist then locate all view from UI file.
if (convertView == null) {
// inflate UI from XML file
convertView = inflater.inflate(R.layout.versedisplayrow, parent, false);
// get all UI view
holder = new ViewHolder(convertView);
// set tag for holder
holder.versenumber = (TextView) convertView.findViewById(R.id.versenumber);
holder.verselist = (TextView) convertView.findViewById(R.id.verse);
holder.addfavoruite=(ImageView)convertView.findViewById(R.id.adbookmark);
holder.removefavoruite=(ImageView)convertView.findViewById(R.id.removebookmark);
try {
holder.addfavoruite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ischeckd=true;
holder.addfavoruite.setVisibility(View.GONE);
holder.removefavoruite.setVisibility(View.VISIBLE);
}
});
holder.removefavoruite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ischeckd=false;
holder.addfavoruite.setVisibility(View.VISIBLE);
holder.removefavoruite.setVisibility(View.GONE);
}
});
}catch (Exception e){
Toast.makeText(activity, ""+e, Toast.LENGTH_SHORT).show();
}
convertView.setTag(holder);
} else {
// if holder created, get tag from view
holder = (ViewHolder) convertView.getTag();
}
holder.versenumber.setText(versenumber.get(position));
holder.verselist.setText(verselist.get(position));
//share verse
holder.share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toasty.info(activity, "Sharing a verse.", Toast.LENGTH_SHORT, true).show();
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, refernce.get(position) + ":" + versenumber.get(position) + '\n' + verselist.get(position));
sendIntent.setType("text/plain");
activity.startActivity(sendIntent);
}
});
textToSpeech = new TextToSpeech(activity, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
result = textToSpeech.setLanguage(Locale.ENGLISH);
} else {
Toast.makeText(activity, "YOUR DEVICE NOT SUPPORTED", Toast.LENGTH_SHORT).show();
}
}
});
//My toggle button
//mDBHelper = new DatabaseHelper(activity);
//mDb = mDBHelper.getWritableDatabase();
//ContentValues contentValues=new ContentValues();
//contentValues.put("id",verseid.get(position));
//contentValues.put("bookname",refernce.get(position));
//contentValues.put("versenumber",versenumber.get(position));
//contentValues.put("verse",verselist.get(position));
//long check=mDb.insert("favourite",null,contentValues);
//Log.d("MY_TAG","DB IS NOW "+check);
//Toasty.success(activity, "Added in favouite"+check, Toast.LENGTH_SHORT, true).show();
holder.speakverse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(activity, "I AM CLICKED", Toast.LENGTH_SHORT).show();
if (result == TextToSpeech.LANG_NOT_SUPPORTED || result == TextToSpeech.LANG_MISSING_DATA) {
Toast.makeText(activity, "Language not supported or Missing", Toast.LENGTH_SHORT).show();
} else {
textToSpeech.speak(verselist.get(position), TextToSpeech.QUEUE_FLUSH, null);
}
}
});
/* holder.removebookmark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDBHelper = new DatabaseHelper(activity);
mDb = mDBHelper.getWritableDatabase();
// long delete= mDb.delete("favourite","id=?",new String[]{verseid.get(position)});
//Toasty.error(activity, "Remove in favouite"+delete, Toast.LENGTH_SHORT, true).show();
}
});*/
return convertView;
}
static class ViewHolder {
private TextView versenumber;
private TextView verselist;
private ImageView share;
private ImageView addfavoruite;
private ImageView removefavoruite;
private ImageView speakverse;
public ViewHolder(View v) {
versenumber = (TextView) v.findViewById(R.id.versenumber);
verselist = (TextView) v.findViewById(R.id.verse);
share = (ImageView) v.findViewById(R.id.share);
speakverse = (ImageView) v.findViewById(R.id.speakverse);
addfavoruite=(ImageView)v.findViewById(R.id.adbookmark);
removefavoruite=(ImageView)v.findViewById(R.id.removebookmark);
}
}
public boolean CheckIsDataAlreadyInDBorNot(String TableName, String dbfield, String fieldValue) {
mDBHelper = new DatabaseHelper(activity);
mDb = mDBHelper.getReadableDatabase();
String Query = "Select * from " + TableName + " where " + dbfield + " = " + fieldValue;
Cursor cursor = mDb.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursor.close();
Toast.makeText(activity, "false", Toast.LENGTH_SHORT).show();
return false;
}else {
Toast.makeText(activity, "TRUE", Toast.LENGTH_SHORT).show();
}
cursor.close();
return true;
}
}
you just need to create an AppPreference class :-
public class AppPrefrences {
private static SharedPreferences mPrefs;
private static SharedPreferences.Editor mPrefsEditor;
public static boolean isButtonCLicked(Context ctx) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
return mPrefs.getBoolean("button_clicked", true);
}
public static void setButtonCLicked(Context ctx, Boolean value) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
mPrefsEditor = mPrefs.edit();
mPrefsEditor.putBoolean("button_clicked", value);
mPrefsEditor.commit();
}
}
and set this method in your button click:-
holder.addfavoruite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ischeckd=true;
holder.addfavoruite.setVisibility(View.GONE);
holder.removefavoruite.setVisibility(View.VISIBLE);
AppPreference.setButtonCLicked(activity, ture);
}
});
and get your button state like this :-
boolean isButtonClicked = AppPreference.isButtonCLicked(activity);
I have a few suggestions. First, I'd recommend you use a ToggleButton for your favourite button. Second, I'd recommend you use a RecyclerView instead of a ListView (which is essentially deprecated). Third, I'd recommend you create a data class (ideally with AutoValue):
class Verse {
private final int number;
private final String list;
private final String ref;
private final String id;
private final boolean isFavourite;
//Constructor and getters...
}
And replace this:
List<String> versenumber, List<String> verselist, List<String> refernce, List<String>verseid
with this:
List<Verse> verses
With respect to persisting which verses are checked and which aren't, then I'd recommend you favour an SQLiteDatabase over SharedPreferences. However, if you use shared preferences, you'll need a way to link your verse to its checked state. I'm assuming your id value is unique, so you can use that:
class VersePreferences {
private static final String VERSE_KEY = "com.my.packagename.VERSE_KEY";
private final SharedPreferences prefs;
private VersePreferences(SharedPreferences prefs) {
this.prefs = prefs;
}
static VersePreferences from(Context context) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
return new VersePreferences(prefs);
}
void save(List<Verse> verses) {
final Set<String> set = new HashSet<>(verses.size());
for(Verse verse : verses) {
final String serialized = String.format("%s:%s", verse.id(), Boolean.toString(verse.isFavourite()));
}
prefs.edit().putStringSet(VERSE_KEY, set).apply();
}
Map<String, Boolean> load() {
final Set<String> set = prefs.getStringSet(VERSE_KEY, new HashSet<>());
final Map<String, Boolean> map = new HashMap<>();
for(String serialized : set) {
final String[] parts = serialized.split(":");
map.put(parts[0], Boolean.parseBoolean(parts[1]);
}
return map;
}
}
You can identify which verse is an isn't a favourite by comparing the String id value in the map against the Boolean value
Example usage...
//OnClick
VersePreferences.from(Context).save(verses); //save all verses
//To load
final Map<String, Boolean> checkedStates = VersePreferences.from(context).load();
for(int i = 0; i < verses.size(); i++) {
final Verse current = verses.get(i);
final boolean checkedState = checkedState.get(current.id());
final Verse checked = current.toBuilder().setChecked(checkedState).build(); //Example using builder pattern
verses.set(i, checked);
}

How to structure data in firebase database as a List<String>?

I would like to know how to structure my data in Firebase database so it return a List<String> when queried. I'm implementing a image slider, I need Firebase to return a List containing images url that my model class which implement Parcelable can parse.
Here is my model class
public class Property implements Parcelable {
private int price;
private String address;
private int numberOfBed;
private int numberOfBath;
private int numberOfCar;
private List<String> propertyImage= new ArrayList<>();
private float lotDim;
public Property() { } //Needed for Firebase's auto data mapping
public Property(int price, String address, int numberOfBed, int numberOfBath,
int numberOfCar, List<String> propertyImage, float lotDim) {
this.price = price;
this.address = address;
this.numberOfBed = numberOfBed;
this.numberOfBath = numberOfBath;
this.numberOfCar = numberOfCar;
this.propertyImage = propertyImage;
this.lotDim = lotDim;
}
protected Property(Parcel in) {
price = in.readInt();
address = in.readString();
numberOfBed=in.readInt();
numberOfBath = in.readInt();
numberOfCar = in.readInt();
in.readStringList(propertyImage);
lotDim = in.readFloat();
}
public static final Creator<Property> CREATOR = new Creator<Property>() {
#Override
public Property createFromParcel(Parcel in) {
return new Property(in);
}
#Override
public Property[] newArray(int i) {
return new Property[i];
}
};
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getNumberOfBed() {
return numberOfBed;
}
public void setNumberOfBed(int numberOfBed) {
this.numberOfBed = numberOfBed;
}
public int getNumberOfBath() {
return numberOfBath;
}
public void setNumberOfBath(int numberOfBath) {
this.numberOfBath = numberOfBath;
}
public int getNumberOfCar() {
return numberOfCar;
}
public void setNumberOfCar(int numberOfCar) {
this.numberOfCar = numberOfCar;
}
public List<String> getPropertyImage() {
return propertyImage;
}
public void setPropertyImage(List<String> propertyImage) {
this.propertyImage = propertyImage;
}
public float getLotDim() {
return lotDim;
}
public void setLotDim(float lotDim) {
this.lotDim = lotDim;
}
#Override
public int describeContents(){
return 0;
}
#Override
public void writeToParcel( Parcel dest, int flags){
dest.writeInt(price);
dest.writeString(address);
dest.writeInt(numberOfBed);
dest.writeInt(numberOfBath);
dest.writeInt(numberOfCar);
dest.writeStringList(propertyImage);
dest.writeFloat(lotDim);
}
}
Here is my current Firebase structure. it return a String actually. I want it to return a List of propertyImage.
This is the fragment that will use the model class, That's where I need to implement the code. Notice at the bottom, I work out something, in the firebase database I appended all the urls in one string(well it's a dirty solution), and split the url turning that String into an array. :-)
So how to implement the new code provided by #Alex Mano. thanks guys
package com.realty.drake.kunuk;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.text.NumberFormat;
import java.util.Locale;
/**
* Created by drake on 4/11/18
*/
public class Tab1Buy extends Fragment {
private DatabaseReference propertyRef;
private RecyclerView mPropertyRecyclerView;
FirebaseRecyclerAdapter<Property, PropertyViewHolder> mPropertyAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.property_tab, container, false);
mPropertyRecyclerView = rootView.findViewById(R.id.property_recyclerView);
return rootView;
}
//TODO Check internet and display error msg if internet down
#Override
public void onViewCreated(final View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mPropertyRecyclerView.hasFixedSize();
mPropertyRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
final ProgressBar progressBar = view.findViewById(R.id.progressBar);
progressBar.setVisibility(View.VISIBLE);
propertyRef = FirebaseDatabase.getInstance()
.getReference()
.child("Buy");
propertyRef.keepSynced(true);
// keyQuery - the Firebase location containing the list of keys to be found in dataRef
//Query personQuery = personRef.orderByKey();
FirebaseRecyclerOptions<Property> options =
new FirebaseRecyclerOptions.Builder<Property>()
.setQuery(propertyRef, Property.class)
.build();
mPropertyAdapter = new FirebaseRecyclerAdapter<Property, PropertyViewHolder>(options) {
#Override
// Bind the Property object to the ViewHolder PropertyHolder
public void onBindViewHolder(#NonNull PropertyViewHolder holder,
final int position, #NonNull final Property model) {
holder.setPrice(model.getPrice());
holder.setAddress(model.getAddress());
holder.setNumberOfBed(model.getNumberOfBed());
holder.setNumberOfBath(model.getNumberOfBath());
holder.setNumberOfCar(model.getNumberOfCar());
holder.setPropertyImage(model.getPropertyImage());
//Intent send Parcelable to PropertyDetail
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getActivity().startActivity(new Intent(getActivity(), PropertyDetail.class)
.putExtra("Property", model));
}
});
}
#Override
public PropertyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// Create a new instance of the ViewHolder, in this case we are using a custom
// layout called R.layout.property_card for each item
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.property_card, parent, false);
return new PropertyViewHolder(view);
}
#Override
public void onDataChanged() {
// Called each time there is a new data snapshot. You may want to use this method
// to hide a loading spinner or check for the "no documents" state and update your UI.
// ...
progressBar.setVisibility(View.GONE);
}
//TODO Implement onError
#Override
public void onError(#NonNull DatabaseError e) {
// Called when there is an error getting data. You may want to update
// your UI to display an error message to the user.
// ...
progressBar.setVisibility(View.GONE);
Toast.makeText(getActivity(), "DatabaseError", Toast.LENGTH_SHORT).show();
}
};
mPropertyRecyclerView.setAdapter(mPropertyAdapter);
}
#Override
public void onStart() {
super.onStart();
mPropertyAdapter.startListening();
}
#Override
public void onStop() {
super.onStop();
mPropertyAdapter.stopListening();
}
public class PropertyViewHolder extends RecyclerView.ViewHolder {
View mView;
public PropertyViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setPrice(int price) {
String currencyPrice = NumberFormat //Format the price variable in currency form
.getCurrencyInstance(Locale.US)
.format(price);
TextView Price = mView.findViewById(R.id.post_price);
Price.setText(currencyPrice);
}
public void setAddress(String address){
TextView Address = mView.findViewById(R.id.post_address);
Address.setText(String.valueOf(address));
}
public void setNumberOfBed(int numberOfBed){
TextView NumberOfBed = mView.findViewById(R.id.post_bedroom);
NumberOfBed.setText(String.valueOf(numberOfBed));
}
public void setNumberOfBath(int numberOfBath){
TextView NumberOfBath = mView.findViewById(R.id.post_bathroom);
NumberOfBath.setText(String.valueOf(numberOfBath));
}
public void setNumberOfCar(int numberOfCar) {
TextView NumberOfCar = mView.findViewById(R.id.post_garage);
NumberOfCar.setText(String.valueOf(numberOfCar));
}
public void setPropertyImage(String propertyImage){
ImageView imageView = mView.findViewById(R.id.post_propertyImage);
//take one long string containing multiple url in and parse it
String propertyImageArray[] = propertyImage.split(",");
//TODO add loading icon for placeholder
// Download directly from StorageReference using Glide
// (See MyAppGlideModule for Loader registration)
GlideApp.with(getContext())
.load(propertyImageArray[0])
.fitCenter()
.into(imageView);
}
}
}
Assuming that the Buy node is a direct child of your Firebase root, to solve this, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference propertyImageRef = rootRef.child("Buy").child("1").child("propertyImage");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String url = ds.getValue(String.class);
Log.d("TAG", url);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
propertyImageRef.addListenerForSingleValueEvent(valueEventListener);
The output will be all those urls.

java.lang.IllegalStateException: Tried to serialize a command referencing a new, unsaved object(Parse.com)

I am pretty new to Android, and i am trying to build an app using the database API from Parse.com. For like one week, i have the following problem when accesing the database and retrieving the object from the database:
E/ParseCommandCache﹕ saveEventually thread had an error.
java.lang.IllegalStateException: Tried to serialize a command referencing a new, > unsaved object.
at com.parse.ParseCommand.resolveLocalIds(ParseCommand.java:407)
at com.parse.ParseCommand.onPreExecute(ParseCommand.java:306)
at com.parse.ParseRequest$7.then(ParseRequest.java:299)
at com.parse.ParseRequest$7.then(ParseRequest.java:296)
at com.parse.Task$11.run(Task.java:481)
at com.parse.Task$ImmediateExecutor.execute(Task.java:673)
at com.parse.Task.completeAfterTask(Task.java:477)
at com.parse.Task.continueWithTask(Task.java:353)
at com.parse.Task.continueWithTask(Task.java:364)
at com.parse.ParseRequest.executeAsync(ParseRequest.java:296)
at com.parse.ParseRequest.executeAsync(ParseRequest.java:286)
at com.parse.ParseCommandCache.maybeRunAllCommandsNow(ParseCommandCache.java:487)
at com.parse.ParseCommandCache.runLoop(ParseCommandCache.java:597)
at com.parse.ParseCommandCache.access$000(ParseCommandCache.java:26)
at com.parse.ParseCommandCache$2.run(ParseCommandCache.java:146)
Here is my code(I apologize if it is a bit messy, but i've been trying all sorts of things in the last week, and i didn't really have much time for refactoring or cleaning.):
package com.example.boacterapp.Pages;
import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.google.android.gms.maps.MapView;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseGeoPoint;
import com.parse.ParseObject;
import com.parse.ParseQuery;
public class RecentSightings extends Activity {
ListView listview;
List<ParseObject> ob;
ProgressDialog mProgressDialog;
Alert alert;
List<Alert> alerts;
public ParseGeoPoint coordinates;
private CustomAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.setContentView(R.layout.list_view_layout);
}
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(RecentSightings.this);
// Set progressdialog title
mProgressDialog.setTitle("Parse.com Simple ListView Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("AlertsClass");
try {
ob = query.find();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.alertListView);
getDataForListView();
adapter = new CustomAdapter(RecentSightings.this,alerts);
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
// Capture button clicks on ListView items
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Send single item click data to SingleItemView Class
Intent i = new Intent(RecentSightings.this,
AlertViewOnMap.class);
// Pass data "name" followed by the position
i.putExtra("coordinatesLatitude", alerts.get(position).getCoordinates().getLatitude());
i.putExtra("coordinatesLongitude", alerts.get(position).getCoordinates().getLongitude());
i.putExtra("description", alerts.get(position).getDescription().toString());
i.putExtra("busNumber", alerts.get(position).getBusNumber());
// Open SingleItemView.java Activity
startActivity(i);
}
});
}
}
public void getDataForListView(){
final List<Alert> alerts = new ArrayList<Alert>();
for (ParseObject alertParse : ob) {
Alert alert = new Alert();
alert.setBusNumber(alertParse.getInt("BusNumber"));
alert.setCoordinates(alertParse.getParseGeoPoint("Coordinates"));
alert.setCreatedAt(alertParse.getDate("createdAt"));
alert.setDescription(alertParse.getString("Description"));
alerts.add(alert);
}
}
}
class CustomAdapter extends BaseAdapter {
Context context;
//ArrayList<HashMap<String,String>> data;
List<Alert> ob;
public CustomAdapter(Context context, List<Alert> ob){
this.context = context;
this.ob = ob;
}
#Override
public int getCount() {
return ob.size();
}
#Override
public Object getItem(int pos) {
return ob.get(pos);
}
#Override
public long getItemId(int pos) {
return pos;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView==null){
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.list_item,null,false);
holder.channel = (TextView) convertView.findViewById(R.id.channelVariableLabel);
holder.viewOnMap = (TextView) convertView.findViewById(R.id.viewOnMapVariableLabel);
holder.description = (TextView) convertView.findViewById(R.id.descriptionVariableLabel);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.channel.setText(ob.get(position).getBusNumber());
holder.viewOnMap.setText("<Tap here to view alert on map>");
holder.description.setText(ob.get(position).getDescription().toString());
convertView.setTag(holder);
return convertView;
}
class ViewHolder {
TextView channel;
TextView viewOnMap;
TextView description;
}
}
class Alert {
private int busNumber;
private ParseGeoPoint coordinates;
private Date createdAt;
private String description;
public Alert () {
}
public void setCreatedAt(java.util.Date date) {
// TODO Auto-generated method stub
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public ParseGeoPoint getCoordinates() {
return coordinates;
}
public void setCoordinates(ParseGeoPoint coordinates) {
this.coordinates = coordinates;
}
public int getBusNumber() {
return busNumber;
}
public void setBusNumber(int busNumber) {
this.busNumber = busNumber;
}
}
So please, almighty lords of Programming/Java/Android/Parse.com Users, lend this mortal a hand in finding his problem!
Thank you! Respects.

Categories

Resources