I am trying to save data into a RealmListafter calling a dialog box. The dialog is supposed to take the name of the new object, a FixtureInfo, add it to the RealmList, and then move to the next activity. However after moving to the next activity and pressing the back button the ListView populated with that RealmList doesn't show the object just created. There is no error it just doesn't show up. Any ideas?
EDIT added in RealmBaseAdapter as beeeneder suggest I do and problem persists.
first activity
public class RoomDescription extends ActionBarActivity {
public AlertDialog.Builder dialogBuilder;
public RealmList<FixtureInfo> myFixtures = new RealmList<>();
public String RoomName;
public String FixtureName;
public RealmList<Rooms> myRooms = new RealmList<>();
private Realm realm;
public Rooms rooms;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_room_description);
//get room name
TextView textFixture = (TextView) findViewById(R.id.RoomName);
Bundle extras = getIntent().getExtras();
if (extras != null) {
RoomName = extras.getString("txtString");
textFixture.setText(RoomName);
}
//initiate realm instant to get CompanyInfo object, Room object, and populate myRoom and myFixtures
realm = Realm.getInstance(this);
rooms = realm.where(Rooms.class).equalTo("Name", RoomName).findFirst();
realm.beginTransaction();
CompanyInfo companyinfo = realm.where(CompanyInfo.class).findFirst();
myRooms = companyinfo.getRooms();
myFixtures = rooms.getFixtureInfos();
realm.commitTransaction();
populateListView();
}
#Override
protected void onResume() {
super.onResume();
LoadInfo();
}
#Override
protected void onPause() {
super.onPause();
SaveInfo();
}
#Override
protected void onDestroy() {
super.onDestroy();
realm.close();
}
private void setFixtureName()
{
//dialog to add fixture to room and set its name
dialogBuilder = new AlertDialog.Builder(this);
final EditText txtInput = new EditText(this);
dialogBuilder.setTitle("New Fixture");
dialogBuilder.setMessage("What is the fixture name?");
dialogBuilder.setView(txtInput);
dialogBuilder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//initiate realm instant
Realm realm = Realm.getInstance(getApplicationContext());
realm.beginTransaction();
//get fixture name and create FixtureInfo object
FixtureName = txtInput.getText().toString();
FixtureInfo fixtureInfo = realm.createObject(FixtureInfo.class);
fixtureInfo.setName(FixtureName);
fixtureInfo.setRoomName(RoomName);
myFixtures.add(fixtureInfo);
realm.commitTransaction();
//save changes
SaveInfo();
//start new activity
Intent i = new Intent(RoomDescription.this, FixtureDescription.class);
i.putExtra("textString", FixtureName);
i.putExtra("txtString", RoomName);
populateListView();
Toast.makeText(getApplicationContext(), "Fixture has been added.", Toast.LENGTH_SHORT).show();
startActivity(i);
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
SaveInfo();
}
});
AlertDialog dialogFixtureName = dialogBuilder.create();
dialogFixtureName.show();
}
private void setRoomName()
{
//same as setRoomName in RoomList.java
dialogBuilder = new AlertDialog.Builder(this);
final EditText txtInput = new EditText(this);
dialogBuilder.setTitle("New Room");
dialogBuilder.setMessage("What is the room name?");
dialogBuilder.setView(txtInput);
dialogBuilder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Realm realm = Realm.getInstance(getApplicationContext());
realm.beginTransaction();
String txtString = txtInput.getText().toString();
Rooms rooms = realm.createObject(Rooms.class);
rooms.setName(txtString);
myRooms.add(rooms);
realm.commitTransaction();
SaveInfo();
realm.close();
Intent i = new Intent(RoomDescription.this, RoomDescription.class);
i.putExtra("txtString", txtString);
Toast.makeText(getApplicationContext(), "Room has been added.", Toast.LENGTH_SHORT).show();
populateListView();
startActivity(i);
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
SaveInfo();
}
});
AlertDialog dialogFixtureName = dialogBuilder.create();
dialogFixtureName.show();
}
private void removeFixture()
{
//remove fixture from room
dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setTitle("Select Fixture to Remove");
dialogBuilder.setSingleChoiceItems(myFixtures.toArray(new String[myFixtures.size()]), -1, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//initiate realm instant
Realm realm = Realm.getInstance(getApplicationContext());
//remove fixture info from room
realm.beginTransaction();
myFixtures = rooms.getFixtureInfos();
myFixtures.remove(which);
//save change
SaveInfo();
populateListView();
Toast.makeText(getApplicationContext(), "Fixture has been removed.", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
AlertDialog dialogFixtureName = dialogBuilder.create();
dialogFixtureName.show();
}
private void populateListView()
{
//on click for the list of FixtureInfo connected to the room
ListView list = (ListView) findViewById(R.id.FixtureList);
RealmResults<FixtureInfo> results = realm.where(FixtureInfo.class).equalTo("RoomName", RoomName).findAll();
FixtureListAdapter adapter = new FixtureListAdapter(this, results, true);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
default:
Intent i = new Intent(RoomDescription.this, FixtureDescription.class);
TextView textItem = (TextView) view;
String FixtureName = textItem.getText().toString();
i.putExtra("textString", FixtureName);
i.putExtra("txtString", RoomName);
startActivity(i);
break;
}
}
});
}
public void SaveInfo()
{
//save info or update info
realm.beginTransaction();
rooms.setName(RoomName);
rooms.setFixtureInfos(myFixtures);
realm.copyToRealmOrUpdate(rooms);
realm.commitTransaction();
}
public void LoadInfo()
{
//load info from specific room
realm.beginTransaction();
myFixtures = rooms.getFixtureInfos();
realm.commitTransaction();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_room_description, menu);
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();
switch (item.getItemId())
{
case R.id.newFixture:
setFixtureName();
break;
case R.id.removeFixture:
removeFixture();
break;
case R.id.add:
setRoomName();
break;
case R.id.home:
startActivity(new Intent(getApplicationContext(), MainPage.class));
break;
case R.id.summary:
startActivity(new Intent(getApplicationContext(), Summary.class));
break;
}
return super.onOptionsItemSelected(item);
}
}
RealmBaseAdapter class
public class FixtureListAdapter extends RealmBaseAdapter<FixtureInfo> implements ListAdapter {
private static class ViewHolder{
TextView FixtureName;
}
public FixtureListAdapter(Context context, RealmResults<FixtureInfo> realmResults, boolean automaticUpdate) {
super(context, realmResults, automaticUpdate);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = inflater.inflate(android.R.layout.simple_list_item_1,
parent, false);
viewHolder = new ViewHolder();
viewHolder.FixtureName = (TextView) convertView.findViewById(android.R.id.text1);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
FixtureInfo fixtureInfo = realmResults.get(position);
viewHolder.FixtureName.setText(fixtureInfo.getName());
return convertView;
}
}
FixtureInfo class
public class FixtureInfo extends RealmObject{
#PrimaryKey
private String RoomName;
#Ignore
private String Name;
private String Description;
private String Wattage;
private String Run_Time;
private String Bulbs_Out;
private String Notes;
private int Count;
public String getRoomName() {
return RoomName;
}
public void setRoomName(String roomName) {
RoomName = roomName;
}
public void setCount(int count) {
Count = count;
}
public int getCount() {
return Count;
}
public void setName(String name) {
Name = name;
}
public void setDescription(String description) {
Description = description;
}
public void setWattage(String wattage) {
Wattage = wattage;
}
public void setRun_Time(String run_Time) {
Run_Time = run_Time;
}
public void setBulbs_Out(String bulbs_Out) {
Bulbs_Out = bulbs_Out;
}
public void setNotes(String notes) {
Notes = notes;
}
public String getName() {
return Name;
}
public String getDescription() {
return Description;
}
public String getWattage() {
return Wattage;
}
public String getRun_Time() {
return Run_Time;
}
public String getBulbs_Out() {
return Bulbs_Out;
}
public String getNotes() {
return Notes;
}
}
I suggest you set a break pointer in onClick to check fixtureInfo you tried to add there. since the RoomName is the primary key, so if you are trying to change a FixtrueInfo with a different RoomName there, i don't expect you will see any changes in the ListView since the RealmResults is based on the original name.
And couple of other problems:
transaction is only needed for writing, no need for reading.
If the object is created by Realm.createObject, no need to call copyToRealmOrUpdate anymore
I suggest you to spend a couple of more minutes on our examples http://github.com/realm/realm-java/tree/master/examples . And also, the mechanism behind the realm-java is that we using Proxy object to overload getters/setters. It is not difficult. You can find FixtureInfoRealmProxy.java in your build directory. It would be interesting and helpful to understand the whole thing, maybe you can have a quick look at that as well :)
Related
I have 2 recycler views that have cards.They basically look the same have the same number of cards and everthing. The first one is for like viewing and other stuff and the second one is only for deleting cards. OnlongClicking a card in the first recycler view triggers the opening of the second recycler view. I wanted to add transitions in between them like what keep notes has done when a card is long clicked. Both the recycler view use the same adapter. I have set what the adapter should do based on passing context to the adapter. enter image description here this is my 1st layout having the 1st recycler view.enter image description here this is the 2nd layout having the second recycler view.I want like a seamless transition for the tool bar again just like what Google keeps has done.A simple solution would be preferred as I am very new to this stuff.
Here is the java code for the adapter.
public class Task_recycle_view_adapter extends RecyclerView.Adapter<Task_recycle_view_adapter.ViewHolder>{
private List<struct_task> task_list= new ArrayList<>();
private ArrayList<String> isSelected=new ArrayList<String>();
protected Context context1;
protected Context context2;
private String labelName;
private String taskName;
private ConstraintLayout label_menu_avatar;
public Task_recycle_view_adapter(Context context1,Context context2)
{
this.context1=context1;
this.context2=context2;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {//parent is the parent of the recycle view it is taken as an arg to use it to attach the every view to the parent view
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_task,parent,false);//to inflate a layout
ViewHolder holder= new ViewHolder(view);
return holder;
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.taskname.setText(task_list.get(position).getTask_name());
holder.taskid.setText(String.valueOf(task_list.get(position).getTask_id()));
if(context2==null && context1!=null) {
String taskName=task_list.get(position).getTask_name();
Long taskid=task_list.get(position).getTask_id();
String duedate=task_list.get(position).getDue_date();
holder.parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DataBaseHelper dataBaseHelper = new DataBaseHelper(context1);
ArrayList<SubTaskModel> subtask_list=(ArrayList<SubTaskModel>) dataBaseHelper.getAllSubTasksFor(labelName, Long.parseLong(holder.taskid.getText().toString()));
Intent intent1 =new Intent(context1,ViewTaskActivity.class);
intent1.putExtra("label_name",labelName);
intent1.putExtra("task_id",taskid);
intent1.putExtra("task_name",taskName);
intent1.putExtra("due_date",duedate);
intent1.putParcelableArrayListExtra("subtask_list", (ArrayList<? extends Parcelable>) subtask_list);
context1.startActivity(intent1);
}
});
holder.parent.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Intent intent2 = new Intent(context1, Delete_page_Activity.class);
intent2.putParcelableArrayListExtra("task_list", (ArrayList<? extends Parcelable>) task_list);
intent2.putExtra("label_name",labelName);
intent2.putExtra("selected_task",taskName);
Pair[] pairs = new Pair[1];
pairs[0]= new Pair<View,String>(label_menu_avatar,"transition1");
ActivityOptions options= ActivityOptions.makeSceneTransitionAnimation((Activity) context1,pairs);
context1.startActivity(intent2,options.toBundle());
return true;
}
});
}
if(context2!=null && context1==null)
{
if(taskName.equals(task_list.get(position).getTask_name()))
{
holder.active=1;
isSelected.add(holder.taskid.getText().toString());
holder.parent.findViewById(R.id.layout_for_every_task).setBackgroundResource(R.drawable.background_for_task_card);
}
holder.parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(holder.active==0) {
isSelected.add(holder.taskid.getText().toString());
v.findViewById(R.id.layout_for_every_task).setBackgroundResource(R.drawable.background_for_task_card);
holder.active=1;
}
else {
isSelected.remove(holder.taskid.getText().toString());
v.findViewById(R.id.layout_for_every_task).setBackgroundResource(R.drawable.background_for_task_card_transparent);
holder.active=0;
}
}
});
}
// subtasks 1 to 5
if(task_list.get(position).getSubtask1()!=null)
holder.subtask1.setText(task_list.get(position).getSubtask1());
else
holder.subtask1.setVisibility(View.GONE);
if(task_list.get(position).getSubtask2()!=null)
holder.subtask2.setText(task_list.get(position).getSubtask2());
else
holder.subtask2.setVisibility(View.GONE);
if(task_list.get(position).getSubtask3()!=null)
holder.subtask3.setText(task_list.get(position).getSubtask3());
else
holder.subtask3.setVisibility(View.GONE);
if(task_list.get(position).getSubtask4()!=null)
holder.subtask4.setText(task_list.get(position).getSubtask4());
else
holder.subtask4.setVisibility(View.GONE);
if(task_list.get(position).getSubtask5()!=null)
holder.subtask5.setText(task_list.get(position).getSubtask5());
else
holder.subtask5.setVisibility(View.GONE);
// due date
if(task_list.get(position).getDue_date()!=null)
holder.duedate.setText(task_list.get(position).getDue_date());
else
holder.duedate.setVisibility(View.GONE);
// progress
holder.progresscircle.setProgress(task_list.get(position).getProgress());
}
#Override
public int getItemCount() {
return task_list.size();
}
public void setTask_list(List<struct_task> task_list) {
this.task_list = task_list;//to refresh the data inside the recycler view
}
#Override
public int getItemViewType(int position) {
return position;
}
public String getLabelName() {
return labelName;
}
public void setLabelName(String labelName) {
this.labelName = labelName;
}
public ArrayList<String> getIsSelected() {
return isSelected;
}
public String getTaskName() {
return taskName;
}
public void setTaskName(String taskName) {
this.taskName = taskName;
}
public void setLabel_menu_avatar(ConstraintLayout label_menu_avatar) {
this.label_menu_avatar = label_menu_avatar;
}
public static class ViewHolder extends RecyclerView.ViewHolder{// holds the view for every item inside the recycle view
private TextView taskname,taskid,duedate,subtask1,subtask2,subtask3,subtask4,subtask5;
private CardView parent;
private ProgressBar progresscircle;
public void setActive(int active) {
this.active = active;
}
private int active;
public ViewHolder(#NonNull View itemView) {
super(itemView);
taskid=itemView.findViewById(R.id.task_id);
taskname = itemView.findViewById(R.id.task_name);
parent = itemView.findViewById(R.id.card_for_every_task);
duedate = itemView.findViewById(R.id.due_date);
progresscircle = itemView.findViewById(R.id.progress_circular);
subtask1 = itemView.findViewById(R.id.subtask_1);
subtask2 = itemView.findViewById(R.id.subtask_2);
subtask3 = itemView.findViewById(R.id.subtask_3);
subtask4 = itemView.findViewById(R.id.subtask_4);
subtask5 = itemView.findViewById(R.id.subtask_5);
active=0;
}
}
}
Here is the code for the 1st activity i.e the 1st image:
public class TaskPageActivity extends AppCompatActivity {
private RecyclerView task_rv;//task recycler view
private FloatingActionButton addTask;
private long tasksNum;
private String labelName;
private DataBaseHelper dataBaseHelper = new DataBaseHelper(this);
private Task_recycle_view_adapter adapter= new Task_recycle_view_adapter(this,null);
private List<struct_task> tasks;
private EditText searchBar;
private ConstraintLayout search_btn;
private ConstraintLayout calendar_btn;
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task_title);
getWindow().getSharedElementExitTransition();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
search_btn= findViewById(R.id.search_btn);
calendar_btn=findViewById(R.id.calendar_btn);
search_btn.setClickable(true);
search_btn.setFocusable(true);
labelName = getIntent().getExtras().getString("832715");
TextView txtLabelName = findViewById(R.id.Label_name);
txtLabelName.setText(labelName);
task_rv = findViewById(R.id.Recycle_view_task);
addTask = findViewById(R.id.add_task);
searchBar= (SearchBar) findViewById(R.id.search_bar);
tasksNum = getTasksNum(labelName, dataBaseHelper, adapter); //displays all tasks and return number of tasks
ConstraintLayout.LayoutParams params= (ConstraintLayout.LayoutParams) searchBar.getLayoutParams();
addTask.setOnClickListener(view -> {
tasksNum = getTasksNum(labelName, dataBaseHelper, adapter);
Intent intent = new Intent(TaskPageActivity.this, AddTaskPageActivity.class);
intent.putExtra("labelName", labelName);
intent.putExtra("taskID", tasksNum);
startActivity(intent);
});
search_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(searchBar.getVisibility()==View.INVISIBLE) {
search_btn.setAlpha(.5f);
searchBar.setVisibility(View.VISIBLE);
searchBar.requestFocus();
imm.showSoftInput(searchBar,InputMethodManager.SHOW_IMPLICIT);
ConstraintLayout.LayoutParams params= (ConstraintLayout.LayoutParams) searchBar.getLayoutParams();
params.verticalBias = .55f;
searchBar.setLayoutParams(params);
searchBar.requestFocus();
}
else {
searchBar.setVisibility(View.INVISIBLE);
search_btn.setAlpha(1.0f);
}
}
});
searchBar.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus) {
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) searchBar.getLayoutParams();
if(params.verticalBias==.9f) {
searchBar.requestFocus();
params.verticalBias = .55f;
searchBar.setLayoutParams(params);
}
searchBar.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if((event.getAction()==KeyEvent.ACTION_DOWN) && (keyCode==KeyEvent.KEYCODE_ENTER) && params.verticalBias==.55f)
{
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) searchBar.getLayoutParams();
searchBar.requestFocus();
params.verticalBias = .9f;
searchBar.setLayoutParams(params);
searchBar.clearFocus();
imm.hideSoftInputFromWindow(searchBar.getWindowToken(),0);
}
return false;
}
});
}
}
});
searchBar.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) {
filter(s.toString());
}
});
AlertDialog alertDialog = new AlertDialog.Builder(TaskPageActivity.this).create();
calendar_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(calendar_btn.getAlpha()==1.0f) {
calendar_btn.setAlpha(.5f);
LayoutInflater inflater = getLayoutInflater();
View view1 = inflater.inflate(R.layout.dialog_calendar,null);
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
alertDialog.setView(view1);
CalendarView mCalendarView= view1.findViewById(R.id.calendar);
mCalendarView.setMinDate(Calendar.getInstance().getTimeInMillis());
alertDialog.show();
}
}
});
alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
if(calendar_btn.getAlpha()==.5f)
calendar_btn.setAlpha(1.0f);
}
});
}
private void filter(String string) {
ArrayList<struct_task> filteredList = new ArrayList<>();
for(struct_task item: tasks)
{
if(item.getTask_name().contains(string) || item.getTask_name().contains(string.toUpperCase()))
{
filteredList.add(item);
}
}
if(filteredList.size()!=0) {
adapter.setTask_list(filteredList);
task_rv.setAdapter(adapter);
}
}
#Override
public void onBackPressed() {
if(searchBar.getText().toString().length()!=0) {
showAllTasks(labelName, dataBaseHelper, adapter);
searchBar.setText(null);
searchBar.setVisibility(View.INVISIBLE);
search_btn.setAlpha(1.0f);
}
else if(searchBar.getText().toString().length()==0)
{
super.onBackPressed();
}
}
#Override
protected void onResume() {
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) searchBar.getLayoutParams();
showAllTasks(labelName, dataBaseHelper, adapter);
if(params.verticalBias==.54f) {
searchBar.requestFocus();
params.verticalBias = .9f;
searchBar.setLayoutParams(params);
searchBar.clearFocus();
}
if(searchBar.getText().toString().length()==0) {
showAllTasks(labelName, dataBaseHelper, adapter);
}
else {
filter(searchBar.getText().toString());
}
super.onResume();
}
private void showAllTasks(String labelName, DataBaseHelper dataBaseHelper, Task_recycle_view_adapter adapter) {
tasks = dataBaseHelper.getAllTasksFor(labelName);
adapter.setLabelName(labelName);
adapter.setTask_list(tasks);
task_rv.setAdapter(adapter);
task_rv.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL));
}
long getTasksNum(String labelName, DataBaseHelper dataBaseHelper, Task_recycle_view_adapter adapter) {
return dataBaseHelper.getLastTaskID(labelName)+1; //to determine ID of next task
}
#Override
protected void onUserLeaveHint() {
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) searchBar.getLayoutParams();
params.verticalBias=.9f;
searchBar.setLayoutParams(params);
searchBar.setText(null);
searchBar.clearFocus();
super.onUserLeaveHint();
}
}
And finally for the 2nd activity which is triggered by longclicking any card
public class Delete_page_Activity extends AppCompatActivity {
private Task_recycle_view_adapter recycle_view_adapter = new Task_recycle_view_adapter(null,this);
private ArrayList<String> delete_list=new ArrayList<>();
private DataBaseHelper dataBaseHelper = new DataBaseHelper(this);
private String labelName=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delete_page);
overridePendingTransition(0,0);
Toolbar toolbar=findViewById(R.id.toolbar_bar);
ImageView close_btn=findViewById(R.id.close_btn);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(null);
ArrayList<struct_task> task_list = getIntent().getParcelableArrayListExtra("task_list");
labelName=getIntent().getExtras().getString("label_name");
String task = getIntent().getExtras().getString("selected_task");
Log.e("test",labelName);
RecyclerView recyclerView = findViewById(R.id.delete_Recycler_View);
recycle_view_adapter.setTaskName(task);
recycle_view_adapter.setTask_list(task_list);
recyclerView.setAdapter(recycle_view_adapter);
recyclerView.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL));
close_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.toolbar_menu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId())
{
case R.id.tool_bar_item1:
delete_list = recycle_view_adapter.getIsSelected();
if(delete_list.size()==0)
{
Toast toast1= new Toast(this);
toast1.setDuration(Toast.LENGTH_SHORT);
LayoutInflater inflater= (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view= inflater.inflate(R.layout.activity_toast_msg1,null);
view.setBackgroundResource(R.drawable.background_for_calendar);
toast1.setView(view);
toast1.show();
}
else {
for (int task = 0; task < delete_list.size(); task++) {
dataBaseHelper.deleteOneTask(labelName, Long.parseLong(delete_list.get(task)));
}
finish();
}
break;
case R.id.tool_bar_item2:
Boolean flag=dataBaseHelper.deleteAllCompletedTasks(labelName);
if(flag)
finish();
else
{
Toast toast2= new Toast(this);
toast2.setDuration(Toast.LENGTH_SHORT);
LayoutInflater inflater= (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view= inflater.inflate(R.layout.activity_toast_msg2,null);
view.setBackgroundResource(R.drawable.background_for_calendar);
toast2.setView(view);
toast2.show();
}
break;
}
return true;
}
}
I have added the code related to the scene transititon which is in the adapter.
here is a gif of the problem when i add a scene transition
enter image description here
As u can see there are 2 pauses when going from 1st to 2nd activity 1st pause being longer 2nd one shorter. And also a pause when exiting the 2nd activity which seems to have the same duration as the 2nd pause.
EDIT 1: I used debugging statements and it turns out that when I add an item to the database it is successful. However, the updateUI() method is not called because what I am launching is a DialogFragment() so my ListActivity does not enter a paused state. But, if I exit the app and launch again the adapter gets updated. So now the question becomes how do I update the adapter after exiting the dialog fragment?
I'm building a simple list app and added SQLite database to store task object. I am successfully adding items to the database, but they do not show up immediately in the RecyclerView I am using to show all tasks. It is only when I completely exit from the app and reload that tasks items show up in the RecyclerView.
ListFragment.java this will create the RecyclerView
public class ListFragment extends Fragment {
private static final String DEBUG_LOG = "debug_message";
private static final String ADD_DIALOG = "add_dialog";
private static final int REQUEST_TITLE = 0;
private RecyclerView mRecyclerView;
private TaskAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_list, container, false);
mRecyclerView = view.findViewById(R.id.the_task_list);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(linearLayoutManager);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(mRecyclerView.getContext(), linearLayoutManager.getOrientation());
mRecyclerView.addItemDecoration(dividerItemDecoration);
updateUI();
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == Activity.RESULT_OK && requestCode == ListFragment.REQUEST_TITLE) {
UUID taskId = (UUID) data.getSerializableExtra(EditTaskFragment.EXTRA_TASK_ID);
String newTaskName = data.getStringExtra(EditTaskFragment.EXTRA_TASK_TITLE);
if(newTaskName != null) {
Task task = TaskLab.get(getActivity()).getTask(taskId);
task.setTitle(newTaskName);
TaskLab.get(getActivity()).updateTask(task);
}
updateUI();
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_list_item, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.add_new_task:
FragmentManager manager = getFragmentManager();
AddTaskFragment dialog = new AddTaskFragment();
dialog.show(manager, ADD_DIALOG);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onResume() {
super.onResume();
updateUI();
}
public void updateUI() {
// Retrieves ArrayList<Task>
List<Task> taskList = TaskLab.get(getActivity()).getTaskList();
if(mAdapter == null) {
mAdapter = new TaskAdapter(taskList);
mRecyclerView.setAdapter(mAdapter);
}else {
mAdapter.setCrimes(taskList);
mAdapter.notifyDataSetChanged();
}
}
private class TaskAdapter extends RecyclerView.Adapter<TaskHolder>{
private List<Task> mTaskList;
public TaskAdapter(List<Task> taskList) {
mTaskList = taskList;
}
#Override
public TaskHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(getActivity()).inflate(R.layout.task_list_layout, parent, false);
return new TaskHolder(view);
}
#Override
public void onBindViewHolder(TaskHolder holder, int position) {
final Task currentTask = mTaskList.get(position);
holder.bindData(currentTask);
final TextView taskTitle = holder.mTaskTitle;
holder.mSolved.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if(isChecked) {
taskTitle.setPaintFlags(taskTitle.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
currentTask.setSolved(true);
}else {
taskTitle.setPaintFlags(taskTitle.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
}
}
});
}
#Override
public int getItemCount() {
return mTaskList.size();
}
public void setCrimes(List<Task> taskList) {
mTaskList = taskList;
}
}
private class TaskHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private Task mTask;
private TextView mTaskTitle;
private CheckBox mSolved;
private static final String EDIT_DIALOG = "edit_dialog";
public TaskHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
mTaskTitle = itemView.findViewById(R.id.task_title);
mSolved = itemView.findViewById(R.id.task_solved);
}
public void bindData(Task task) {
mTask = task;
mTaskTitle.setText(mTask.getTitle());
mSolved.setChecked(mTask.isSolved());
}
#Override
public void onClick(View view) {
if(!mSolved.isChecked()) {
FragmentManager manager = getFragmentManager();
EditTaskFragment dialog = EditTaskFragment.newInstance(mTask.getId());
dialog.setTargetFragment(ListFragment.this, REQUEST_TITLE);
dialog.show(manager, EDIT_DIALOG);
}
}
}
AddTaskFragment.java this will allow the user to add a task item to the RecyclerView
public class AddTaskFragment extends DialogFragment {
private EditText mTaskTitle;
private void addTask() {
if(!mTaskTitle.getText().toString().equals("")) {
Task task = new Task();
task.setTitle(mTaskTitle.getText().toString());
TaskLab.get(getActivity()).addTask(task);
}
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
//return super.onCreateDialog(savedInstanceState);
View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_task_dialog,null);
mTaskTitle = view.findViewById(R.id.task_title);
return new AlertDialog.Builder(getActivity())
.setView(view)
.setTitle(R.string.add_new_task_dialog_title)
.setPositiveButton(R.string.add_new_task_dialog_positive, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
addTask();
}
})
.create();
}
}
TaskLab.java this is a singleton class
public class TaskLab {
private static TaskLab sTaskLab;
private Context mContext;
private SQLiteDatabase mDatabase;
private TaskLab(Context context){
mContext = context.getApplicationContext();
mDatabase = new TaskBaseHelper(mContext).getWritableDatabase();
}
public static TaskLab get(Context context) {
if(sTaskLab == null) {
sTaskLab = new TaskLab(context);
}
return sTaskLab;
}
public List<Task> getTaskList(){
List<Task> taskList = new ArrayList<Task>();
TaskCursorWrapper cursor = queryTasks(null, null);
// If there is something in the table query it
try {
cursor.moveToFirst();
while(!cursor.isAfterLast()) {
Task task = cursor.getTask();
taskList.add(task);
cursor.moveToNext();
}
} finally {
cursor.close();
}
return taskList;
}
public void addTask(Task task) {
ContentValues values = getContentValues(task);
mDatabase.insert(TaskTable.NAME, null, values);
}
public void updateTask(Task task) {
ContentValues values = getContentValues(task);
String uuidString = task.getId().toString();
mDatabase.update(TaskTable.NAME,values, TaskTable.Cols.UUID + " = ?", new String[] {uuidString});
}
public Task getTask(UUID id){
TaskCursorWrapper cursor = queryTasks(TaskTable.Cols.UUID + " = ?",
new String[] {id.toString()});
try {
if(cursor.getCount() == 0) {
return null;
}
cursor.moveToFirst();
return cursor.getTask();
} finally {
cursor.close();
}
}
private static ContentValues getContentValues(Task task) {
ContentValues values = new ContentValues();
values.put(TaskTable.Cols.UUID, task.getId().toString());
values.put(TaskTable.Cols.TITLE, task.getTitle());
values.put(TaskTable.Cols.SOLVED, task.isSolved());
return values;
}
private TaskCursorWrapper queryTasks(String whereClause, String[] whereArgs) {
Cursor cursor = mDatabase.query(TaskTable.NAME,
null,
whereClause,
whereArgs,
null,
null,
null);
return new TaskCursorWrapper(cursor);
}
}
It must be reCreate your adapter in updateUI every time from the beginning
Try it like this and see. In your onCreateView() of fragment before updateUI() add below line of code.
Note: Create taskList as global variable.
mRecyclerView = view.findViewById(R.id.the_task_list);
mAdapter = new TaskAdapter(taskList);
mRecyclerView.setAdapter(mAdapter);
updateUI();
After that create your updateUI() method as below
public void updateUI() {
taskList.clear;
taskList = TaskLab.get(getActivity()).getTaskList();
mAdapter.notifyDataSetChanged();
}
Update:
As per your updated question, declare one global variable in ListFragment as
public static ListFragment listFragment;
In your onCreate method of ListFragment after inflating view add below line of code.
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_list, container, false);
listFragment = this;
Then change your addTask method in AddTaskFragment as below.
private void addTask() {
if(!mTaskTitle.getText().toString().equals("")) {
Task task = new Task();
task.setTitle(mTaskTitle.getText().toString());
TaskLab.get(getActivity()).addTask(task);
//import listfragment from your ListFragment
listFragment.updateUI();
}
}
I'm building an app that manages the tasks. The user can enter the task name, set priority and add that task. What I want to implement is for the user to be able to click an item, launch an alert dialog and edit the details of that item (name, priority) from that dialog, click "Save Edits" and save the edits for that particular list item. However, the alert dialog does not launch when an item is clicked. I'm trying to call a method containing the dialog through onclick:
recyclerView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
addTaskActivity.onClickEditTask(view);
return true;
}
});
And this is the onClickEditText method:
public class AddTaskActivity extends AppCompatActivity {
...
public void onClickEditTask(View view){
String editedInput = ((EditText)findViewById(R.id.edit_task)).getText().toString();
if(editedInput.length() == 0){
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(getLayoutInflater().inflate(R.layout.edit_dialog, null))
.create();
}
...
}
Currently, I want to know how to launch this method per item click and get the details of that item plastered onto the launched dialog. The following are my relevant classes:
AddTaskActivity.java:
public class AddTaskActivity extends AppCompatActivity {
private int mPriority;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_task);
((RadioButton) findViewById(R.id.radButton1)).setChecked(true);
mPriority = 1;
}
public void onClickAddTask(View view) {
String input = ((EditText) findViewById(R.id.editTextTaskDescription)).getText().toString();
if (input.length() == 0) {
return;
}
ContentValues contentValues = new ContentValues();
contentValues.put(TaskContract.TaskEntry.COLUMN_DESCRIPTION, input);
contentValues.put(TaskContract.TaskEntry.COLUMN_PRIORITY, mPriority);
Uri uri = getContentResolver().insert(TaskContract.TaskEntry.CONTENT_URI, contentValues);
if(uri != null) {
Toast.makeText(getBaseContext(), uri.toString(), Toast.LENGTH_LONG).show();
}
finish();
}
public void onClickEditTask(View view){
String editedInput = ((EditText)findViewById(R.id.edit_task)).getText().toString();
if(editedInput.length() == 0){
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(getLayoutInflater().inflate(R.layout.edit_dialog, null))
.create();
}
public void onPrioritySelected(View view) {
if (((RadioButton) findViewById(R.id.radButton1)).isChecked()) {
mPriority = 1;
} else if (((RadioButton) findViewById(R.id.radButton2)).isChecked()) {
mPriority = 2;
} else if (((RadioButton) findViewById(R.id.radButton3)).isChecked()) {
mPriority = 3;
}
}
}
MainActivity.java:
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {
private static final String TAG = MainActivity.class.getSimpleName();
private static final int LOADER_ID = 0;
private CustomCursorAdapter customCursorAdapter;
RecyclerView recyclerView;
private AddTaskActivity addTaskActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recyclerViewTasks);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
customCursorAdapter = new CustomCursorAdapter(this);
recyclerView.setAdapter(customCursorAdapter);
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) {
int id = (int) viewHolder.itemView.getTag();
String itemId = Integer.toString(id);
Uri uri = TaskContract.TaskEntry.CONTENT_URI;
uri = uri.buildUpon().appendPath(itemId).build();
getContentResolver().delete(uri, null, null);
getSupportLoaderManager().restartLoader(LOADER_ID, null, MainActivity.this);
}
}).attachToRecyclerView(recyclerView);
recyclerView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
addTaskActivity.onClickEditTask(view);
return true;
}
});
FloatingActionButton floatingActionButton = (FloatingActionButton) findViewById(R.id.fab_btn);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent addTaskIntent = new Intent(MainActivity.this, AddTaskActivity.class);
startActivity(addTaskIntent);
}
});
getSupportLoaderManager().initLoader(LOADER_ID, null, this);
}
#Override
protected void onResume() {
super.onResume();
getSupportLoaderManager().restartLoader(LOADER_ID, null, this);
}
#Override
public Loader<Cursor> onCreateLoader(int id, final Bundle loaderArgs) {
return new AsyncTaskLoader<Cursor>(this) {
Cursor cursor = null;
#Override
protected void onStartLoading() {
if (cursor != null) {
deliverResult(cursor);
} else {
forceLoad();
}
}
#Override
public Cursor loadInBackground() {
try {
return getContentResolver().query(TaskContract.TaskEntry.CONTENT_URI,
null,
null,
null,
TaskContract.TaskEntry.COLUMN_PRIORITY);
} catch (Exception e) {
Log.e(TAG, "Failed to load data.");
e.printStackTrace();
return null;
}
}
public void deliverResult(Cursor data) {
cursor = data;
super.deliverResult(data);
}
};
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
customCursorAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
customCursorAdapter.swapCursor(null);
}
}
CustomCursorAdapter.java:
public class CustomCursorAdapter extends RecyclerView.Adapter<CustomCursorAdapter.TaskViewHolder> {
private Cursor cursor;
private Context con;
public CustomCursorAdapter(Context context) {
this.con = context;
}
#Override
public TaskViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(con).inflate(R.layout.task_layout, parent, false);
return new TaskViewHolder(view);
}
#Override
public void onBindViewHolder(TaskViewHolder holder, int position) {
int index = cursor.getColumnIndex(TaskContract.TaskEntry._ID);
int descriptionOfIndex = cursor.getColumnIndex(TaskContract.TaskEntry.COLUMN_DESCRIPTION);
int priorityofIndex = cursor.getColumnIndex(TaskContract.TaskEntry.COLUMN_PRIORITY);
cursor.moveToPosition(position);
final int id = cursor.getInt(index);
String description = cursor.getString(descriptionOfIndex);
int priority = cursor.getInt(priorityofIndex);
holder.itemView.setTag(id);
holder.taskDescriptionView.setText(description);
String priorityString = "" + priority;
holder.priorityView.setText(priorityString);
GradientDrawable priorityCircle = (GradientDrawable) holder.priorityView.getBackground();
int priorityColor = getPriorityColor(priority);
priorityCircle.setColor(priorityColor);
}
private int getPriorityColor(int priority) {
int priorityColor = 0;
switch(priority) {
case 1: priorityColor = ContextCompat.getColor(con, R.color.materialRed);
break;
case 2: priorityColor = ContextCompat.getColor(con, R.color.materialOrange);
break;
case 3: priorityColor = ContextCompat.getColor(con, R.color.materialYellow);
break;
default: break;
}
return priorityColor;
}
#Override
public int getItemCount() {
if (cursor == null) {
return 0;
}
return cursor.getCount();
}
public Cursor swapCursor(Cursor c) {
if (cursor == c) {
return null;
}
Cursor temp = cursor;
this.cursor = c;
if (c != null) {
this.notifyDataSetChanged();
}
return temp;
}
class TaskViewHolder extends RecyclerView.ViewHolder {
TextView taskDescriptionView;
TextView priorityView;
public TaskViewHolder(View itemView) {
super(itemView);
taskDescriptionView = (TextView) itemView.findViewById(R.id.taskDescription);
priorityView = (TextView) itemView.findViewById(R.id.priorityTextView);
}
}
}
You appear to have omitted showing the alter dialog by coding builder.show();
Additionally may want to setup some buttons (you can use Neutral, Positive and Negative buttons, below is example with just Neutral button).
You probably want to set the title and make the AlertDialog cancelable.
You may also have an issue with the custom layout, so the code below will ignore that and use the default layout.
I believe that the following code will fix this issue:-
public void onClickEditTask(View view){
String editedInput = ((EditText)findViewById(R.id.edit_task)).getText().toString();
if(editedInput.length() == 0){
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Test");
builder.setCancelable(true);
builder.setNeutralButton("TEST", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.d("TAG","You click the TEST button of the dialog.");
}
});
builder.show();
}
Introducing a custom layout
The following is the above but with an added rudimentary custom view, first the layout, namely test_hi.xml :-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/buildertv"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_marginTop="30dp"
android:layout_marginStart="30dp"
android:layout_marginLeft="30dp"
android:text="TEST"
android:textColor="#ff557799"
android:gravity="center"
>
</TextView>
</LinearLayout>
And the code (i.e. with builder.setView(R.layout.test_hi); added) :-
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(R.layout.test_hi);
builder.setTitle("Test");
builder.setCancelable(true);
builder.setNeutralButton("TEST", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.d("TAG","You clicked the TEST button of the dialog.");
}
});
builder.show();
Running the above should be something like (*running the previous code will not have the middle *Test**):-
Clicking the bottom (Red) Test will add a line to the log along the lines of:-
....D/TAG: You clicked the TEST button of the dialog.
You would replace Log.d("TAG","You clicked the TEST button of the dialog."); with the code that you want to run when the Neutral Button is clicked. If you wanted other options then you can use the Positive and Negative buttons in a similar way by adding builder.setPositiveButton(.... and builder.setNegativeButton(.... accordingly.
Im building a simple aplication with a recycleView/CardLayout, i followeed this tutorial.
I see many questions answered for the card click, but what i need is to handle listeners with diferent actions when the user clicks the title or the user clicks on the image in each card.
My problem is, when the user clicks a radiobutton i need to get the radio on the listener so i can handle check and uncheck because i need to do pass that to a builder
This is what i have at the moment:
public class SimiliarPlantsAdapter extends RecyclerView.Adapter<SimiliarPlantsAdapter.PlantViewHolder>{
ArrayList<Plant> plants = new ArrayList<Plant>();
Context context;
public static class PlantViewHolder extends RecyclerView.ViewHolder {
CardView cv;
TextView plantName;
CheckBox plantCheck;
ImageView plantPhoto;
PlantViewHolder(View itemView) {
super(itemView);
cv = (CardView)itemView.findViewById(R.id.cv);
plantName = (TextView)itemView.findViewById(R.id.plantName);
plantCheck = (CheckBox)itemView.findViewById(R.id.plantCheck);
plantPhoto = (ImageView)itemView.findViewById(R.id.plantPhoto);
}
}
#Override
public PlantViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.similiar_photo_row, viewGroup, false);
PlantViewHolder pvh = new PlantViewHolder(v);
return pvh;
}
#Override
public void onBindViewHolder(PlantViewHolder holder, int position) {
holder.plantName.setText(plants.get(position).getSpecie());
holder.plantCheck.setText("Are you sure this is the plant?");
Log.d("foto",String.valueOf(holder.plantName));
String urlFoto = "http://10.0.2.2:3000/images/" + holder.plantName.getText().toString() + "/Thumbnail.jpg";
Picasso.with(context)
.load(urlFoto)
.resize(250, 250)
.into(holder.plantPhoto);
}
#Override
public int getItemCount() {
return plants.size();
}
public SimiliarPlantsAdapter(ArrayList<Plant> plants,Context context) {
this.plants = plants;
this.context = context;
}
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
}
MY Activity
public class SimiliarPhotos extends AppCompatActivity implements IResult,SimiliarPlantsAdapter.OnItemClickListener {
RecyclerView rv;
LinearLayoutManager llm;
ArrayList<Plant> plants = new ArrayList<Plant>();
SimiliarPlantsAdapter adapter;
CheckBox checkBox;
VolleyService mVolleyService;
IResult mResultCallback = null;
final String GETREQUEST = "GETCALL";
//login url connection
final String URL = "http://10.0.2.2:3000/plants";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_similiar_photos);
rv = (RecyclerView)findViewById(R.id.rv);
llm = new LinearLayoutManager(this);
llm.setAutoMeasureEnabled(true);
rv.setLayoutManager(llm);
initializeAdapter();
initVolleyCallback();
mVolleyService = new VolleyService(mResultCallback,this);
mVolleyService.getDataVolley(GETREQUEST,URL);
}
#Override
public void notifySuccess(String requestType, JSONObject response) {
Log.d("resposta",response.toString());
}
#Override
public void notifySuccess(String requestType, JSONArray response) {
Log.d("resposta",response.toString());
}
#Override
public void notifyError(String requestType, VolleyError error) {
Log.d("resposta",error.toString());
}
void initVolleyCallback(){
mResultCallback = new IResult() {
#Override
public void notifySuccess(String requestType, JSONObject response) {
}
#Override
public void notifySuccess(String requestType, JSONArray response) {
Plant plant;
Log.d("ENTERED","ENTEREDHERE1");
// iterate over the JSONArray response
for (int i=0; i < response.length(); i++) {
try {
JSONObject object = response.getJSONObject(i); // get the individual object from JSONArray
int id = Integer.parseInt(object.getString("id")); // get the unique identifier from the object
String specie = object.getString("specie"); // get the name of the specie from the object
String description = object.getString("description"); // get the description of the object
plant = new Plant(id,specie,description); // construct the object
Log.d("plant",String.valueOf(plant));
plants.add(plant); // add the object to the arraylist so it can be used on the cardLayout
} catch (JSONException e) {
Log.d("ENTERED",e.toString());
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
#Override
public void notifyError(String requestType, VolleyError error) {
Log.d("resposta",error.toString());
}
};
}
public void initializeAdapter(){
Log.d("plants",String.valueOf(plants.size()));
adapter = new SimiliarPlantsAdapter(plants,SimiliarPhotos.this,SimiliarPhotos.this);
rv.setAdapter(adapter);
}
#Override
public void onTitleClicked(int position, int id, View clickedview) {
}
#Override
public void onImageClicked(int position, View clickedview) {
}
#Override
public void onCheckClicked(int position, String specie, View clickedview) {
adapter.getItemId(position);
CreateDialog(specie);
}
public void CreateDialog(String specie){
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(SimiliarPhotos.this, android.R.style.Theme_Material_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(SimiliarPhotos.this);
}
builder.setTitle("Esta é a sua escolha?")
.setMessage("Confirma " + specie + " como a planta que fotografou?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//TODO associa nome da planta a fotografia na base de dados
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
The volley init is the request, not so important for the question, since i get the data correctly
You need to implement CompoundButton.OnCheckedChangeListener for CheckBox.
Your_CHECK_BOX.setOnCheckedChangeListener(checkedChangeListener);
CompoundButton.OnCheckedChangeListener checkedChangeListener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if(compoundButton == YOUR_CHECK_BOX) {
if(isChecked) {
// when check box is checked, call your action listener just like you did for title click/image click etc
} else {
// when check box is unchecked, call your action listener just like you did for title click/image click etc
}
}
I have a spinner that i select data from which goes into a arraylist that is used with a list view to display the contents. I know the values are going into the Arraylist but when it comes to the list view it does not work correctly.
What happens is the first item will load in fine, but when i add another item the previous one disappears, while the new one is displayed one position down from the previous one, this repeats for each one i added.
create itinerary code:
public class CreateItinerary extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
TextView txtDate;
private Spinner spinnerAttraction;
private Spinner spinnerTransport;
private boolean saved;
// array list for spinner adapter
private ArrayList<Category> categoriesList;
private ProgressDialog pDialog;
private List<String> lables = new ArrayList<String>();
private ArrayList<ItineraryAdapter>Entities;
private ArrayList<ItineraryAdapter>finalEntities;
private LayoutInflater myInflator;
private View myView;
private DBManager db;
private myAdapter adapter;
private int ID;
private String NAME;
private String LOCATION;
private String TIME;
static final int DIALOG_ID = 0;
int hour_x;
int min_x;
private ListView ls;
private TextView TextTime;
private String ItineraryName;
private String URL_ATTRACTIONS = "http://10.0.2.2/TravelApp/get_all_spinner.php";
private String URL_TRANSPORT = "http://10.0.2.2/TravelApp/get_all_transport_minor.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_itinerary);
txtDate = (TextView) findViewById(R.id.tvSelectDate);
saved = false;
ls = (ListView)findViewById(R.id.listCreateItinerary);
myInflator = getLayoutInflater();
myView = myInflator.inflate(R.layout.list_create_itinerary, null);
spinnerAttraction = (Spinner) findViewById(R.id.spinnerAttraction);
spinnerTransport = (Spinner) findViewById(R.id.spinnerTransport);
db = new DBManager(this);
categoriesList = new ArrayList<Category>();
Entities = new ArrayList<ItineraryAdapter>();
finalEntities = new ArrayList<ItineraryAdapter>();
// spinner item select listener
spinnerAttraction.setOnItemSelectedListener(this);
spinnerTransport.setOnItemSelectedListener(this);
new GetAttractions().execute();
showTimePickerDialog();
Bundle bundle = getIntent().getExtras();
ItineraryName = bundle.getString("Itinerary Name");
(this).registerForContextMenu(ls);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if(v.getId()== R.id.listCreateItinerary){
this.getMenuInflater().inflate(R.menu.context_menu,menu);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.menuDelete:
return true;
default:
return super.onContextItemSelected(item);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home_button, menu);
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();
//noinspection SimplifiableIfStatement
if (saved == false) {
if (id == R.id.go_home) {
final TextView alertMessage = new TextView(this);
alertMessage.setText(" All changes will be lost are you sure you want to return back to the home page? ");
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("Unsaved changes")
.setView(alertMessage)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(getApplicationContext(), QavelNav.class);
startActivity(i);
}
})
.setNegativeButton("No", null)
.create();
dialog.show();
}
}
else if(saved == true){
if (id == R.id.go_home) {
Intent i = new Intent(getApplicationContext(), QavelNav.class);
startActivity(i);
}
}
return super.onOptionsItemSelected(item);
}
public void pickDate(View v) {
DatePickerClass datepicker = new DatePickerClass();
datepicker.setText(v);
datepicker.show(getSupportFragmentManager(), "datepicker");
System.out.println(getDate());
}
public String getDate() {
String date;
date = txtDate.getText().toString();
return date;
}
public void addAttractionToItinerary(View v){
Entities.add(new ItineraryAdapter(ID,NAME,LOCATION,null));
loadAttractions();
System.out.println(ItineraryName);
}
public void addTransportToItinerary(View v){
Entities.add(new ItineraryAdapter(ID,NAME,LOCATION,null));
loadAttractions();
System.out.println(ItineraryName);
}
public void loadAttractions(){
adapter = new myAdapter(Entities);
ListView ls = (ListView) findViewById(R.id.listCreateItinerary);
ls.setAdapter(adapter);
for(int i =0; i < finalEntities.size(); i++){
System.out.println(finalEntities.get(i).NAME + " " + finalEntities.get(i).LOCATION + " " + finalEntities.get(i).TIME);
}
}
public void onSave(View v){
ContentValues values = new ContentValues();
for(int i = 0; i <finalEntities.size();i++) {
values.put(DBManager.ColItineraryName,ItineraryName);
values.put(DBManager.ColDate,txtDate.getText().toString());
values.put(DBManager.ColName,finalEntities.get(i).NAME );
values.put(DBManager.ColLocation,finalEntities.get(i).LOCATION);
values.put(DBManager.ColTime,finalEntities.get(i).TIME);
long id = db.Insert("Itinerary",values);
if (id > 0)
Toast.makeText(getApplicationContext(),"Added to Itinerary", Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(),"cannot insert", Toast.LENGTH_LONG).show();
}
saved = true;
}
public void showTimePickerDialog(){
TextTime = (TextView) myView.findViewById(R.id.tvCreateItineraryTime);
TextTime.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
showDialog(DIALOG_ID);
}
});
}
#Override
protected Dialog onCreateDialog(int id){
if(id== DIALOG_ID)
return new TimePickerDialog(CreateItinerary.this,KTimePickerListner, hour_x, min_x,false);
return null;
}
protected TimePickerDialog.OnTimeSetListener KTimePickerListner = new TimePickerDialog.OnTimeSetListener(){
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute){
hour_x = hourOfDay;
min_x = minute;
Toast.makeText(CreateItinerary.this,hour_x+" : " + min_x, Toast.LENGTH_LONG).show();
setTime(hour_x, min_x);
TIME = hour_x + ":" + min_x;
finalEntities.add(new ItineraryAdapter(ID,NAME,LOCATION,TIME));
}
};
public void setTime(int hour, int min){
TextTime.setText(hour_x+":"+min_x);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long l) {
Toast.makeText(
getApplicationContext(),
parent.getItemAtPosition(position).toString() + " Selected" ,
Toast.LENGTH_LONG).show();
NAME = categoriesList.get(position).getName();
LOCATION = categoriesList.get(position).getLocation();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
/**
* Adding spinner data
* */
private void populateSpinner() {
for (int i = 0; i < categoriesList.size(); i++) {
lables.add(categoriesList.get(i).getName() + " - " + categoriesList.get(i).getLocation());
System.out.println(categoriesList.get(i));
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinnerAttraction.setAdapter(spinnerAdapter);
spinnerTransport.setAdapter(spinnerAdapter);
}
/**
* Async task to get all attraction categories
* */
private class GetAttractions extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CreateItinerary.this);
pDialog.setMessage("Fetching attraction categories..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_ATTRACTIONS, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("attraction");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
Category cat = new Category(catObj.getInt("Id"),
catObj.getString("Name"), catObj.getString("Location"));
categoriesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
populateSpinner();
// new GetTransport().execute();
}
}
private class GetTransport extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CreateItinerary.this);
pDialog.setMessage("Fetching transport categories..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_TRANSPORT, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("transport");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
Category cat = new Category(catObj.getInt("Id"),
catObj.getString("Name"), catObj.getString("Location"));
categoriesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
populateSpinner();
}
}
class myAdapter extends BaseAdapter {
public ArrayList<ItineraryAdapter> listItem;
ItineraryAdapter ac;
public myAdapter(ArrayList<ItineraryAdapter> listItem) {
this.listItem = listItem;
}
#Override
public int getCount() {
return listItem.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View view, ViewGroup viewGroup) {
ac = listItem.get(position);
TextView Name = (TextView) myView.findViewById(R.id.tvCreateItineraryName);
Name.setText(ac.NAME);
TextView Location = (TextView) myView.findViewById(R.id.tvCreateItineraryLocation);
Location.setText(ac.LOCATION);
return myView;
}
public void deleteItineraryItem(){
Entities.remove(ID);
finalEntities.remove(ID);
loadAttractions();
}
}
}
The public void loadAttractions(){..., is the medthod code that updates the list view, the 2 methods above it relate to separate buttons and add the spinner item to the array list (Entities), thank you to anyone who can help me.
instead of:
#Override
public Object getItem(int position) {
return null;
}
try this code:
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listItem.get(position); //return list item
}