Cannot access activity's property from the dialog - android

I have an activity from which I call the dialog. On positive dialog's event I'm trying to add a custom item form the "showAddPhraseDialog" method to the List (phrasesToSave) which is property of the activity's class.
But the list size do not increases.
Activity class:
public class AddActivity extends AppCompatActivity {
private RecyclerView rv_select_person;
private ChildHorizontalAdapter personAdapter;
private RecyclerView rv_conversation;
private UnsavedConversationAdapter conversationAdapter;
private List<UnsavedPhrase> phrasesToSave;
private List<Child> personsList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
phrasesToSave = new ArrayList<UnsavedPhrase>();
// conversation widgets
rv_conversation = (RecyclerView) findViewById(R.id.rv_conversation);
conversationAdapter = new UnsavedConversationAdapter(phrasesToSave);
LinearLayoutManager llm = new LinearLayoutManager(AddActivity.this);
rv_conversation.setLayoutManager(llm);
rv_conversation.setAdapter(conversationAdapter);
...
}
private void showAddPhraseDialog(final Child phrase_author)
{
boolean wrapInScrollView = true;
new MaterialDialog.Builder(AddActivity.this)
.title(R.string.label_what_was_said)
.customView(R.layout.dialog_add_phrase, wrapInScrollView)
.positiveText(R.string.button_add)
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
EditText tePhrase = (EditText)dialog.findViewById(R.id.te_phrase);
String phrase_text = tePhrase.getText().toString();
if (!StringUtils.isNullAndEmpty(phrase_text)) {
UnsavedPhrase new_phrase = new UnsavedPhrase(phrase_text, phrase_author);
phrasesToSave.add(new_phrase);
}
}
})
.show();
}
}

Try to debug and check that after the phrasesToSave.add(new_phrase); the list has one new element in it. If it has a new element, but you don't see the element in your UI, you should notify the RecyclerView that it's data set has changed. Try calling notifyDataSetChanged(). Docs for it.
Your code looks fine. If there isn't a new element in phrasesToSave after the add, then try to clean your project. Build -> Clean Project

Sorry for late reply You forgot to notify the adapter
if(conversationAdapter != null)
{
conversationAdapter.notifyDataSetChanged();
}

Related

Adding a Item to Listview

Im trying to simply add a Item to a Listview and display it. But if I add it it just shows me the path of that string istead of the tring itself. I'm sure it's a simple mistake but I cant find it.
public class zutatenHinzufuegen extends AppCompatActivity {
private ArrayList<String> zutatenliste;
private ListView zutatenView;
private ArrayAdapter<String> zutatenadapter;
private TextInputLayout zutatInput;
private TextInputLayout anzahlInput;
private int anzahlint;
private String einheitInput;
private Button hinzufuegen_button;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.zutaten_hinzufuegen_linear);
getSupportActionBar().setTitle(R.string.menu_zutaten);
// Spinner
final Spinner einheiten_spinner = (Spinner) findViewById(R.id.spinner_einheiten2);
ArrayAdapter<String> einheiten_adapter = new ArrayAdapter<String>(zutatenHinzufuegen.this,
android.R.layout.simple_list_item_1,getResources().getStringArray(R.array.einheiten));
einheiten_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
einheiten_spinner.setAdapter(einheiten_adapter);
// List
zutatInput =(TextInputLayout) findViewById(R.id.textInputZutat2);
einheitInput =(String) einheiten_spinner.getSelectedItem().toString();
anzahlInput = (TextInputLayout) findViewById(R.id.textInputAnzahl2);
try {
anzahlint = Integer.parseInt(anzahlInput.toString());
}catch (NumberFormatException nfe){}
hinzufuegen_button = findViewById(R.id.zutat_hinzufuegen_button2);
zutatenView =(ListView) findViewById(R.id.zutatenliste2);
zutatenliste= new ArrayList<>();
zutatenadapter = new ArrayAdapter<String>(this,R.layout.zutatenliste_items,R.id.textitemliste,zutatenliste);
// zutatenadapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_item, zutatenliste);
zutatenView.setAdapter(zutatenadapter);
hinzufuegen_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// hinzufuegen(v , einheiten_spinner);
ZutatClass newzutat = new ZutatClass(zutatInput.toString(),anzahlint,einheitInput);
zutatenliste.add((String) newzutat.zutat_sting);
zutatenadapter.notifyDataSetChanged();
}
});
}
}
This is what I see when i press the button a few times
I'm new to Android Studio and java so I hope it's not to much of a mess.
Thanks in advance.
First of all, you need to add Edittext inside the TextInputLayout and then get a text like this ZutatClass newzutat = new ZutatClass(zutatInput.getEditText().getText().toString(),anzahlint,einheitInput); on your on click method
I guess the issue is that you are trying to convert a TextInputLayout to string instead of getting the text from it and convert it to string , try the code below
hinzufuegen_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// hinzufuegen(v , einheiten_spinner);
ZutatClass newzutat = new ZutatClass(zutatInput.getEditText().getText().toString(),anzahlintgetEditText().g etText().toString()
,einheitInput);
zutatenliste.add((String) newzutat.zutat_sting);
zutatenadapter.notifyDataSetChanged();
}
});
zutatInput.toString() --> zutatInput.getEditText().getText()
anzahlint.toString() --> anzahlint.getEditText().getText().toString()

How to check duplicate data using Realm in Android

In my App I have stored some mockdata to show at the starting of the app. Now I have another option to add data into Realm database. But in my app, all the duplicate data is stored within the database. For Example I have three data in setRealmData() method. within this method I created same data with similar information. This data is checked perfectly. But whenever I tried to add a new data with simialer name it also stored within the app, which I do not want actually. How can I duplicate check in with preload data to new data in Realm.
My Activity Class is
public class MyColleaguesPage extends AppCompatActivity implements MyColleaguesAdapter.ColleagueListListener{
private RecyclerView recyclerView;
private MyColleaguesAdapter adapter;
private Realm colleagueRealm;
private RealmResults<MyColleagueModel> dataResult;
private static final String DIALOG_TAG = "EmployeeDialog";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mycolleagues_layout);
// Showing and Enabling clicks on the Home/Up button
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
colleagueRealm = Realm.getDefaultInstance();
recyclerView = (RecyclerView) findViewById(R.id.colleagues_recycler);
setUpRecycler();
if (!Prefs.with(this).getPreLoad()) {
setRealmData();
}
showAllPersons();
}
private void showAllPersons() {
dataResult = colleagueRealm.where(MyColleagueModel.class).findAll();
setAdapter(dataResult);
adapter.notifyDataSetChanged();
}
private void setAdapter(RealmResults<MyColleagueModel> results) {
adapter = new MyColleaguesAdapter(this, colleagueRealm.where(MyColleagueModel.class).findAllSortedAsync("id"),this);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
private void setUpRecycler() {
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
recyclerView.setHasFixedSize(true);
// use a linear layout manager since the cards are vertically scrollable
final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
}
private void setRealmData(){
List<MyColleagueModel> colleague = new ArrayList<>();
MyColleagueModel model = new MyColleagueModel();
model.setId(1);
model.setName("Name1");
model.setCompany("Comapny1");
model.setTitle("Title1");
colleague.add(model);
model = new MyColleagueModel();
model.setId(2);
model.setName("Name2");
model.setCompany("Comapny2");
model.setTitle("Title1");
colleague.add(model);
model = new MyColleagueModel();
model.setId(2);
model.setName("Name2");
model.setCompany("Comapny2");
model.setTitle("Title1");
colleague.add(model);
model = new MyColleagueModel();
model.setId(3);
model.setName("Name3");
model.setCompany("Comapny3");
model.setTitle("Title3");
colleague.add(model);
for (MyColleagueModel realmModel : colleague) {
// Persist the colleague data
colleagueRealm.beginTransaction();
colleagueRealm.copyToRealmOrUpdate(realmModel);
colleagueRealm.commitTransaction();
}
Prefs.with(this).setPreLoad(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.recycler_menu, menu);
final MenuItem item = menu.findItem(R.id.search);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == android.R.id.home) {
finish();
}
//onOptionsItemSelected(MenuItem item) add will open dialog box, which allows user to fill required data
if (id == R.id.addColleague) {
showAlertDialog();
return true;
}
return super.onOptionsItemSelected(item);
}
private void showAlertDialog() {
EditColleagueFragment dialog = new EditColleagueFragment();
//dialog.setPositiveButtonClickListener(this);
dialog.show(getSupportFragmentManager(), DIALOG_TAG);
//adapter.notifyDataSetChanged();
}
#Override
protected void onDestroy() {
if (colleagueRealm!= null)
colleagueRealm.close();
super.onDestroy();
}
}
My EditDialog Fragment Class is
public class EditColleagueFragment extends DialogFragment {
private EditText id;
private EditText name;
private EditText role;
private EditText company;
private EditText mobile;
private EditText email;
private EditText department;
private View view;
private LayoutInflater inflater;
private Realm mRealm;
/*public interface onSaveClickListener {
void onSaved();
}
private onSaveClickListener mSaveClickListener;
public void setPositiveButtonClickListener(onSaveClickListener listener){
mSaveClickListener=listener;
}*/
public EditColleagueFragment() {
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
inflater = getActivity().getLayoutInflater();
view = inflater.inflate(R.layout.edit_my_colleague, null);
id = (EditText) view.findViewById(R.id.id);
name = (EditText) view.findViewById(R.id.name);
role = (EditText) view.findViewById(R.id.role);
company = (EditText) view.findViewById(R.id.company);
mobile = (EditText) view.findViewById(R.id.mobile);
email = (EditText) view.findViewById(R.id.email);
department= (EditText) view.findViewById(R.id.department);
AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
dialog.setTitle("Add Colleague");
dialog.setView(view);
dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
savePerson();
}
});
return dialog.create();
}
private void savePerson() {
mRealm = Realm.getDefaultInstance();
mRealm.beginTransaction();
MyColleagueModel model=new MyColleagueModel();
model.setId(id.getId());
model.setName(name.getText().toString());
model.setTitle(role.getText().toString());
model.setCompany(company.getText().toString());
model.setMobile(mobile.getText().toString());
model.setEmail(email.getText().toString());
model.setDepartment(department.getText().toString());
mRealm.copyToRealmOrUpdate(model);
mRealm.commitTransaction();
mRealm.close();
}
}
The way to avoid duplication of data using the Realm Mobile Platform is to use primary keys.
Normally, all insertions and updates are preserved when synchronizing data between clients, but often multiple clients want to insert data that is logically identical. To ensure that those insertions are collapsed into single objects, you can use a primary key column on the model by which the objects can be identified on both clients. If two clients each insert an object with the same primary key value, the objects will be considered logically the same, and you will end up with just the one object after synchronization.
You haven't shared your model, but it looks like there is an "ID" field — that could serve as the primary key. :-)
Note that if you are only making local changes (no synchronization), primary key conflicts will result in an error being thrown, and you manually have to handle the case of preexisting objects.
If using primary keys is inconvenient for your use case, you always have the option to wait for download to complete and then manually clean up the database — just make sure that clients are able to make the same decisions about which object to discard, so as to avoid throwing away more than necessary.
try use code below
public <E extends RealmModel> boolean isDataExist(Class<E> eClass, int id) {
E data = colleagueRealm.where(eClass).equalTo("id", id).findFirst();
return data != null;
}
private void initData(){
if(isDataExist(MyColleagueModel.class, id.getText().toString())){
// data exist
}else{
// insert new
}

notify RecyclerView adapter from fragment

i have a RecyclerView with Dialog Fragment , and i get data from user in via the Dialog and stored it in the database then , i display it in recyclerview , and all this is working , my problem is , when i add the data i must restart the app to display it into recycler , how i can notify the adapter data is change ?
the add button in the Dialog Fragment
add = (Button) rootView.findViewById(R.id.addbutton);
add.setOnClickListener(this);
private void insert() {
Title = addTitle.getText().toString();
Des= addDesc.getText().toString();
db.insertIntoDB(Title, Des);}
#Override
public void onClick(View v) {
if (addTitle.getText().toString().trim().equals("")) {
addTitle.setError(" Title is required!");
} else if (addDesc.getText().toString().trim().equals("")) {
addDesc.setError(" Postion is required!");
}
Toast.makeText(getContext(),"your data is saved", Toast.LENGTH_SHORT).show();
insert();
}
and this is the getdata method in the helper class
public List<ToDoModule> getDataFromDB(){
List<ToDoModule> modelList = new ArrayList<ToDoModule>();
String query = "select * from "+ TODO_TABLE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query,null);
if (cursor.moveToFirst()){
do {
ToDoModule model = new ToDoModule();
model.setActionTitle(cursor.getString(1));
model.setActionDesc(cursor.getString(2));
modelList.add(model);
}while (cursor.moveToNext());
}
return modelList;
}
and this is the main activity
public class MainActivity extends AppCompatActivity {
public List<ToDoModule> dbList;
RecyclerView mRecyclerView;
DatabaseHelpher helpher;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().hide();
helpher = new DatabaseHelpher(this);
dbList= new ArrayList<ToDoModule>();
dbList = helpher.getDataFromDB();
mRecyclerView = (RecyclerView)findViewById(R.id.AppRecyclerView);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new RecyclerAdapter(this,dbList);
this.dbList =helpher.getDataFromDB();
mAdapter.notifyDataSetChanged();
mRecyclerView.setAdapter(mAdapter);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setImageResource(R.drawable.ic_action_name);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentManager fm = getSupportFragmentManager();
addAction add = new addAction();
add.show(fm,"fragment_edit_name");
}});}
#Override
protected void onResume() {
super.onResume();
}
}
DialogFragments, like all fragments, are directly tied to the lifecycle of the Activity that uses them. Therefore the onResume() callback is not called by the activity after a user dismisses the dialogFragment.
For simplicity and easy maintainability, I would create an interface,
public interface DialogFragUpdateListener {
public void OnDBUpdate();
}
which your activity will implement,
public class MainActivity extends AppCompatActivity implements DialogFragUpdateListener{
that receives a callback whenever the user finishes the action you are having them do in the DialogFragment. I would add this in your onClick() method after the insert() is called:
(DialogFragUpdateListener)getActivity()).OnDBUpdate()
Then in your activity, this callback method can them query the updated data from the database and update the adapter/recyclerview again:
public void OnDBUpdate() {
// Requery data from database here
getDataFromDB();
}
Check this out for reference:
https://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity

RecyclerView not refreshing after rotating the device with an open DialogFragment

I have a RecyclerView inside a AppCompatActivity. Item insertions and changes are shown and animated correctly after rotating the device.
The problem happens when you:
Tap on an item in the RecyclerView.
A DialogFragment opens prompting if you want to the delete the item.
Rotate the device.
Confirm the deletion in the dialog.
Check the array list. The item has been deleted.
The RecyclerView still shows the item.
Tried using notifyDataSetChanged instead of notifyItemRemoved but didn't work either because the item is still being shown in the RecyclerView.
This is happening with any version of Android.
Simplified code of how the process is being handled:
public class MyAppCompatActivity extends AppCompatActivity {
int positionOfDeletedItem;
MyObjectRecyclerViewAdapter adapter;
ArrayList<MyObject> someTestData;
MyItemDeletionHandler deletionHandlerRemover;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_activity_layout);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
positionOfDeletedItem = 1;
deletionHandlerRemover = new MyItemDeletionHandler(this);
someTestData = new ArrayList<MyObject>(3);
someTestData.add(new MyObject("A"));
someTestData.add(new MyObject("B"));
someTestData.add(new MyObject("C"));
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyObjectRecyclerViewAdapter(new MyAdapterOnClickEvent.OnItemClick() {
#Override
public void onClick(int posicion, int idViaje, View view) {
String tag = "Some tag value";
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment prev = getSupportFragmentManager().findFragmentByTag(tag);
if(prev != null)
ft.remove(prev);
ft.addToBackStack(null);
DialogFragment newFragment = MyDeletionConfirmationDialog.newInstance(deletionHandlerRemover);
newFragment.show(ft, tag);
}
}, someTestData);
recyclerView.setAdapter(adapter);
}
private final static class MyItemDeletionHandler extends Handler {
private final WeakReference<MyAppCompatActivity> theActivity;
private MyItemDeletionHandler(MyAppCompatActivity act) {
theActivity = new WeakReference<MyAppCompatActivity>(act);
}
#Override
public void handleMessage(Message msg) {
MyAppCompatActivity activity = theActivity.get();
if(activity != null) {
if(msg.what == 1) {
activity.deleteTheItem();
}
}
}
}
public void deleteTheItem() {
someTestData.remove(positionOfDeletedItem);
adapter.notifyItemRemoved(positionOfDeletedItem);
}
}
public class MyDeletionConfirmationDialog extends DialogFragment {
private Message handlerMessage;
public static MyDeletionConfirmationDialog newInstance(Handler callbackHandler) {
MyDeletionConfirmationDialog myDialog = new MyDeletionConfirmationDialog();
Bundle args = new Bundle();
args.putParcelable("handlerMessage", callbackHandler.obtainMessage(1, true));
myDialog.setArguments(args);
return myDialog;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handlerMessage = getArguments().getParcelable("handlerMessage");
}
#Override
#NonNull
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
alertDialogBuilder.setMessage("Some message");
alertDialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
final Message toSend = Message.obtain(handlerMessage);
toSend.sendToTarget();
}
});
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog dialog = alertDialogBuilder.create();
dialog.setCanceledOnTouchOutside(true);
return dialog;
}
}
How can I get the RecyclerView to work correctly?
Edit 1:
I have other RecyclerViews in which this works correctly. The only difference is those are inside Fragments instead of AppCompatActivity. I am suspecting that this has something to do with the events onDetachedFromWindow and onAttachedToWindow of the RecyclerView.
Edit 2:
If the dialog is closed (step 4) and opened again it works as expected.
Edit 3:
If the RecyclerView is extracted as a Fragment the problem disappears and works as intended. It is impossible to have the use case described above working correctly in conjunction with AppCompatActivity instead of a Fragment.
I was facing a similar problem with RecyclerView.
When I swiped left to delete an item and then rotate the screen, the item was removed from my dataset but the screen wasn't refreshing like it normaly does when we do the same action without rotating. It seems the adaptar.notifyItemRemoved() wasn't refreshing the screen at all.
I'm using the Nemanja Kovacevic source code as starting point, but I did some changes on it (like adding item click, edit with a dialog, database support, etc).
So I read this post which gave me a hint about what could be going wrong.
It seems the adapter.notify was still pointing to the previous adapter referece before rotation. Every time we rotate a new adapter is created at the Activity:OnCreate
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,
AddAlertDialog.OnAlertSavedListener,
AlertListAdapter.OnItemDeletedListener {
static ListAdapter mListAdapter;
RecyclerView mRecyclerView;
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
mRecyclerView = (RecyclerView) findViewById(R.id.mainListView);
mDB = new DatabaseTable(this);
// Reading all alerts
ArrayList<Alert> alerts = mDB.getAllAlerts();
if (mListAdapter == null)
mListAdapter = new ListAdapter(this, alerts);
}
}
Maybe it is not ideal (creating static objects is not a good idea), but it solved the problem.
I hope it may help you too.

What is the most effective way for a Dialog to interact with an array adapter of a (parent) activity?

The way my dialog is set up currently, it is supposed to take the values from the EditTexts and save in into a database (a process simplified through Sugar ORM), then place the newly created SubjectInfo object into the RecyclerView. The way the notifyDataSetChanged(); is included gives me errors concerning the Thread (basically no thread is waiting upon the change in the data set). SO, I have two paths as I see it, but I'm still confused as to how each approach would work.
Option 1: Somehow revoke the onCreate() method in the SubjectManagerActivity so that the adapter responds to the new database. (How to revoke an onCreate method?)
Option 2: Create a custom Dialog Fragment Activity. Does this navigate back up to recreate the parent activity?
Please help explain how to make the notifyDataSetChanged(); respond, because once that line is removed, there are no errors, but I can't see the new Subject card until I restart the app.
Here is my code:
public class SubjectManagerActivity extends ActionBarActivity {
public static ArrayList<SubjectInfo> subjectList = new ArrayList<SubjectInfo>();
public static FloatingActionButton fabCreateSubject;
private AlertDialog.Builder build;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_subject_manager);
RecyclerView recList = (RecyclerView) findViewById(R.id.subject_card_list);
recList.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
recList.setLayoutManager(llm);
subjectList = getSubjectInfoArrayList();
SubjectAdapter sa = new SubjectAdapter(subjectList);
recList.setAdapter(sa);
fabCreateSubject = (FloatingActionButton) findViewById(R.id.fab_create_subject);
fabCreateSubject.setOnClickListener (new View.OnClickListener() {
#Override
public void onClick(View v) {
build = new AlertDialog.Builder(SubjectManagerActivity.this);
LayoutInflater inflater = getLayoutInflater();
View alertview = inflater.inflate(R.layout.create_subject_dialog, null);
// Pass null as the parent view because its going in the dialog layout
build.setView(alertview);
final EditText inputSubjectName = (EditText) alertview.findViewById(R.id.dialog_edit_subject_card_name);
final EditText inputSubjectGrade = (EditText) alertview.findViewById(R.id.dialog_edit_subject_card_grade);
build.setTitle("Add Subject")
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
String enteredSubjectName = inputSubjectName.getText().toString();
boolean enteredSubjectIsArchived = false;
if((!(inputSubjectName.getText().toString().equals("")))) {
SubjectInfo si = new SubjectInfo(enteredSubjectName, enteredSubjectIsArchived);
si.save();
}
dialog.cancel();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = build.create();
alert.show();
}
});
}
public ArrayList<SubjectInfo> getSubjectInfoArrayList(){
ArrayList<SubjectInfo> sial= new ArrayList<SubjectInfo>();
List<SubjectInfo> sil = SubjectInfo.listAll(SubjectInfo.class);
sial.addAll(sil);
notifyDataSetChanged;
return sial;
}
It turns out often the most effective way to deal with an issue is to trust in your code and research to make it work! For anyone else with a similar issue, I included this code:
si.save();
subjectList.add(si);
sa.notifyDataSetChanged();
The method notifyDataSetChanged(); had to be directed to an adapter, which is the container of the Thread. Though the adapter isn't being populated from the getSubjectInfoArrayList() method in real-time (when the dialog is prompted), the ArrayList is still acquiring the same value and when the app is reopened, it can populate the adapter from the database (and in turn, the same get( ) method).

Categories

Resources