Custom listview and Sherlock List Fragment - java

In my application I'm trying to make navigation between pages by Dropdown navigation menu, but when i'm running the application there is no items in my list
Main Activity
public class Main extends SherlockFragmentActivity implements OnNavigationListener{
//----------------------------------New Variables
private static final String KEY_MODELS="models";
private static final String KEY_POSITION="position";
private static final String[] labels= { "All", "Downloads","Completed","Later" };
private CharSequence[] models=new CharSequence[4];
private DownloadList frag=null;
private int lastPosition=-1;
//----------------------------------
ActionBar act;
ViewPager myviewpager;
int mSelectedPageIndex=1;
DownloadService downloadservice;
Intent serviceIntent ;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
frag=(DownloadList)getSupportFragmentManager().findFragmentById(android.R.id.content);
if (frag==null) {
frag=new DownloadList();
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, frag).commit();
}
if (state != null) {
models=state.getCharSequenceArray(KEY_MODELS);
}
if (downloadservice==null)
downloadservice= new DownloadService();
ArrayAdapter<String> nav=null;
act=getSupportActionBar();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
{
nav= new ArrayAdapter<String>(act.getThemedContext(),
android.R.layout.simple_spinner_item,labels);
}
else
{
nav=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,labels);
}
nav.setDropDownViewResource(android.R.layout.simple_list_item_1);
act.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
act.setDisplayShowTitleEnabled(false);
act.setHomeButtonEnabled(false);
act.setListNavigationCallbacks(nav, this);
if (state != null) {
act.setSelectedNavigationItem(state.getInt(KEY_POSITION));
}
serviceIntent= new Intent(Main.this,downloadservice.getClass());
if (startService(serviceIntent)==null)
startService(serviceIntent);
act.setTitle("");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater infalter = getSupportMenuInflater();
infalter.inflate(R.menu.mymenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==R.id.sub1)
{
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Downlaod New File");
alert.setMessage("Enter URL");
final EditText input = new EditText(this);
alert.setView(input);
input.setText( "http://205.196.123.184/ddpha7c5b8lg/616c36j0d1xbztf
/Lecture+ppt+Ch2.ppt");
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText().toString();
downloadservice.addandstart(value);
Log.d("value",value);
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alert.show();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
lastPosition=itemPosition;
frag=(DownloadList)getSupportFragmentManager().findFragmentById(android.R.id.content);
return false;
}
Custom adapter and SherlockFragmentList
public class DownloadList extends SherlockListFragment {
int index=0;
Button downloadButton;
Button pauseButton;
Button resumeButton;
TextView textLink;
TextView progressbar;
DownloadService downloadservice= new DownloadService();
MyAdapter listadapter;
Intent serviceIntent ;
String state;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivity().setContentView(R.layout.downloadlist);
setListAdapter(new MyAdapter(getSherlockActivity(), downloadservice.downloads));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle
savedInstanceState) {
View rootView = inflater.inflate(R.layout.downloadlist, container, false);
setListAdapter(new MyAdapter(getSherlockActivity(), downloadservice.downloads));
return rootView;
}
int getIndex()
{
return index;
}
public class MyAdapter extends ArrayAdapter<NewDownload>
{
private final List<NewDownload> list;
//private final Activity context;
Thread t;
public MyAdapter(Context context,List<NewDownload> list) {
super(context, R.layout.list_item, list);
// this.context = (Activity) context;
this.list = list;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater)
getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.list_item, null);
pauseButton = (Button) row.findViewById(R.id.btn1);
resumeButton = (Button) row.findViewById(R.id.btn2);
textLink = (TextView) row.findViewById(R.id.tv1);
progressbar = (TextView) row.findViewById(R.id.progressBar1);
textLink.setText(downloadservice.downloads.get(position).getName());
progressbar.setBottom(downloadservice.downloads.get(position).getDownloadedSize());
progressbar.setTop(downloadservice.downloads.get(position).getTotalSize());
final int p = position;
final NewDownload r = list.get(p);
if (r.state=="downloading")
{
progressbar.setText("DownLoading...");
pauseButton.setEnabled(true);
resumeButton.setEnabled(false);
}
else if (r.state=="pause")
{
pauseButton.setEnabled(false);
resumeButton.setEnabled(true);
progressbar.setText(r.state);
}
pauseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
downloadservice.pause(p);
setListAdapter(listadapter );
}
});
resumeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (getActivity().startService(serviceIntent)==null)
getActivity().startService(serviceIntent);
downloadservice.resume(p);
setListAdapter(listadapter );
}
});
return row;
}
}
Anyone can tell me how to implement my list right and where is my mistake ?
thx a lot

Don't set the layout from your fragment big no no!
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// getActivity().setContentView(R.layout.downloadlist); // Never do this!
// Also this will do nothing remove this! This should be in your `onActivityCreated()`
// setListAdapter(new MyAdapter(getSherlockActivity(), downloadservice.downloads));
}
Don't override onCreateView in your Fragment, SherlockListFragment creates the ListView layout for you.
If you want to set the adapter, remove your onCreateView and set you adapter in onActivityCreated()
#Override
public void onActivityCreated(Bundle saveState){
setListAdapter(new MyAdapter(getSherlockActivity(), downloadservice.downloads));
}
Setting your setListAdapter(listadapter ); in your Adapter getView is wrong too. If you update your List<?> of data make sure you call notifyDataSetChanged() from the mainThread after you update the list.
Otherwise make sure you layout has a ListView with android:id="#android:id/list" defined otherwise SherlockListView won't have a view to set the adapter too.

Related

Transition between 2 recycler views having cards

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.

How to set two different fonts in two different Fragment (TabLayout)

I have an app using tab layout and RecyclerView for getting items. I have 2 different tabs and I wanna use two different fonts on them. I have OneActivity and for tabsi have FirstFragment, SecondFragment.
I can change whole app's font with RecyclerView_Adapter. But i don't wanna change whole app's font. In FirstFragment (First Tab) i wanna use Arial and Text size 20 sp, in SecondFragment i wanna use Comic Sans and Text size 16 sp.
How can i do that, is it possible?
OneActivity.Java
public class OneActivity extends AppCompatActivity {
private static Toolbar toolbar;
private static ViewPager viewPager;
private static TabLayout tabLayout;
private static BottomNavigationView bottomNavigationView;
private ImageButton forwardbtn, backwardbtn, pausebtn, playbtn;
private MediaPlayer mPlayer;
private TextView songName, startTime, songTime;
private SeekBar songPrgs;
private static int oTime =0, sTime =0, eTime =0, fTime = 15000, bTime = 15000;
private Handler hdlr = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one);
backwardbtn = (ImageButton)findViewById(R.id.btnBackward);
forwardbtn = (ImageButton)findViewById(R.id.btnForward);
playbtn = (ImageButton)findViewById(R.id.btnPlay);
pausebtn = (ImageButton)findViewById(R.id.btnPause);
startTime = (TextView)findViewById(R.id.txtStartTime);
songTime = (TextView)findViewById(R.id.txtSongTime);
mPlayer = MediaPlayer.create(this, R.raw.deneme);
songPrgs = (SeekBar)findViewById(R.id.sBar);
songPrgs.setClickable(false);
pausebtn.setEnabled(false);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = (ViewPager) findViewById(R.id.viewPager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);//setting tab over viewpager
bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavigationView);
//Implementing tab selected listener over tablayout
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());//setting current selected item over viewpager
switch (tab.getPosition()) {
case 0:
Log.e("TAG","TAB1");
break;
case 1:
Log.e("TAG","TAB2");
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
playbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(OneActivity.this, "One Oynatılıyor", Toast.LENGTH_SHORT).show();
mPlayer.start();
eTime = mPlayer.getDuration();
sTime = mPlayer.getCurrentPosition();
if(oTime == 0){
songPrgs.setMax(eTime);
}
songTime.setText(String.format("%d dk, %d sn", TimeUnit.MILLISECONDS.toMinutes(eTime),
TimeUnit.MILLISECONDS.toSeconds(eTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS. toMinutes(eTime))) );
startTime.setText(String.format("%d dk, %d sn", TimeUnit.MILLISECONDS.toMinutes(sTime),
TimeUnit.MILLISECONDS.toSeconds(sTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS. toMinutes(sTime))) );
songPrgs.setProgress(sTime);
hdlr.postDelayed(UpdateSongTime, 100);
pausebtn.setEnabled(true);
playbtn.setEnabled(false);
}
});
pausebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPlayer.pause();
pausebtn.setEnabled(false);
playbtn.setEnabled(true);
Toast.makeText(getApplicationContext(),"One Duraklatıldı", Toast.LENGTH_SHORT).show();
}
});
forwardbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if((sTime + fTime) <= eTime)
{
sTime = sTime + fTime;
mPlayer.seekTo(sTime);
}
else
{
Toast.makeText(getApplicationContext(), "Daha fazla ileri sarılamaz", Toast.LENGTH_SHORT).show();
}
if(!playbtn.isEnabled()){
playbtn.setEnabled(true);
}
}
});
backwardbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if((sTime - bTime) > 0)
{
sTime = sTime - bTime;
mPlayer.seekTo(sTime);
}
else
{
Toast.makeText(getApplicationContext(), "Daha fazla geri sarılamaz", Toast.LENGTH_SHORT).show();
}
if(!playbtn.isEnabled()){
playbtn.setEnabled(true);
}
}
});
}
public Runnable UpdateSongTime = new Runnable() {
#Override
public void run() {
sTime = mPlayer.getCurrentPosition();
startTime.setText(String.format("%d dk, %d sn", TimeUnit.MILLISECONDS.toMinutes(sTime),
TimeUnit.MILLISECONDS.toSeconds(sTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(sTime))) );
songPrgs.setProgress(sTime);
hdlr.postDelayed(this, 100);
songPrgs.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(mPlayer != null && fromUser){
mPlayer.seekTo(progress); // clear ' * 1000 '
}
}
});
}
};
public void onBackPressed(){
mPlayer.stop();
finish();
}
//Setting View Pager
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new FirstFragment("Android"), "Android");
adapter.addFrag(new SecondFragment("Ios"), "Ios");
viewPager.setAdapter(adapter);
}
//View Pager fragments setting adapter class
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();//fragment arraylist
private final List<String> mFragmentTitleList = new ArrayList<>();//title arraylist
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
//adding fragments and title method
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
FirstFragment
public class FirstFragment extends Fragment {
private View view;
private String title;//String for tab title
private String ebaka;
// Intent it = getActivity().getIntent();
// String isim = getActivity().getIntent().getStringExtra("FOO");
// Bundle bundle = getActivity().getIntent().getExtras();
// String value = bundle.getString("key1");
private static RecyclerView recyclerView;
public FirstFragment() {
}
#SuppressLint("ValidFragment")
public FirstFragment(String title) {
this.title = title;//Setting tab title
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.dummy_fragment, container, false);
// getActivity().getActionBar().setTitle(title);
setRecyclerView();
return view;
}
//Setting recycler view
private void setRecyclerView() {
recyclerView = (RecyclerView) view
.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView
.setLayoutManager(new LinearLayoutManager(getActivity()));//Linear Items
// String[] eArray=getActivity().getResources().getStringArray(R.array.books);
//
String[] ebaka=getActivity().getResources().getStringArray(R.array.bakara);
ArrayList<String> arrayList = new ArrayList<>();
// arrayList.add("cdscsdc");
for (int i = 0; i < ebaka.length; i++) {
arrayList.add(ebaka[i]);
}
RecyclerView_Adapter adapter = new RecyclerView_Adapter(getActivity(), arrayList);
recyclerView.setAdapter(adapter);// set adapter on recyclerview
}
}
RecyclerView_Adapter
public class RecyclerView_Adapter extends RecyclerView.Adapter<DemoViewHolder> {
private ArrayList<String> arrayList;
private Context context;
public RecyclerView_Adapter(Context context,
ArrayList<String> arrayList) {
this.context = context;
this.arrayList = arrayList;
this.arrayList = arrayList;
}
#Override
public int getItemCount() {
return (null != arrayList ? arrayList.size() : 0);
}
#Override
public void onBindViewHolder(DemoViewHolder holder,
int position) {
Typeface customTypeOne = Typeface.createFromAsset(context.getAssets(), "arial.ttf");
final DemoViewHolder mainHolder = (DemoViewHolder) holder;
//Setting text over textview
mainHolder.title.setText(arrayList.get(position));
mainHolder.title.setTypeface(customTypeOne); // With this code i change font, but it is changing whole apps font. i don't need that.
}
#Override
public DemoViewHolder onCreateViewHolder(
ViewGroup viewGroup, int viewType) {
LayoutInflater mInflater = LayoutInflater.from(viewGroup.getContext());
ViewGroup mainGroup = (ViewGroup) mInflater.inflate(
R.layout.item_row, viewGroup, false);
DemoViewHolder mainHolder = new DemoViewHolder(mainGroup) {
#Override
public String toString() {
return super.toString();
}
};
return mainHolder;
}
}
DemoViewHolder
public abstract class DemoViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public DemoViewHolder(View view) {
super(view);
this.title = (TextView) view.findViewById(R.id.cardTitle);
}
}
Update your adapter constructor and onBindViewHolder():
public class RecyclerView_Adapter extends RecyclerView.Adapter<DemoViewHolder> {
private ArrayList<String> arrayList;
private Context context;
//add this
private String comingFrom;
//constructor
public RecyclerView_Adapter(Context context, ArrayList<String> arrayList, String comingFrom) {
this.context = context;
this.arrayList = arrayList;
this.arrayList = arrayList;
this.comingFrom = comingFrom;
}
........
........
#Override
public void onBindViewHolder(DemoViewHolder holder,int position) {
Typeface customTypeOne = Typeface.createFromAsset(context.getAssets(),"arial.ttf");
final DemoViewHolder mainHolder = (DemoViewHolder) holder;
//Setting text over textview
mainHolder.title.setText(arrayList.get(position));
//check in which fragment you are
if(comingFrom.equals("fragment_one")){
//in fragment one set some font
mainHolder.title.setTypeface(........);
}else{
//in fragment two set some other font
mainHolder.title.setTypeface(.........);
}
}
............
}
When initializing adapter from FirstFragment:
.......
.......
RecyclerView_Adapter adapter = new RecyclerView_Adapter(getActivity(), arrayList, "fragment_one");
recyclerView.setAdapter(adapter);// set adapter on recyclerview
........
When initializing adapter from SecondFragment:
.......
.......
RecyclerView_Adapter adapter = new RecyclerView_Adapter(getActivity(), arrayList, "fragment_two");
recyclerView.setAdapter(adapter);// set adapter on recyclerview
........

How to set up custom input dialog for saving data in Firebase when user clicks any textview widget in cardview?

In MainActivity I have NavigationDrawer. For each menu item, I have a fragment class with a corresponding layout. One of them is MyCardFragment.java. In this fragment, I am showing CardView through RecyclerView.
My CardView contains some TextViews and an ImageView. What I wanted is when a user clicks a widget it will open a custom input dialog (contains a TextView, an EditText, a positive button, and a negative button) for updating data in Firebase Real-time database. I created a dialog fragment class, but don't know how to implement it in my adapter class.
This is my main activity which holds RecyclerView and CardView:
MainActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth=FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
if (currentUser != null){
myRef = FirebaseDatabase.getInstance().getReference().child("user").child(currentUser.getUid());
}
mContext = MainActivity.this;
mDrawerLayout = findViewById(R.id.drawer_layout);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionbar = getSupportActionBar();
actionbar.setDisplayHomeAsUpEnabled(true);
actionbar.setHomeAsUpIndicator(R.drawable.ic_action_name);
NavigationView navigationView = findViewById(R.id.nav_view);
//navigationView.inflateHeaderView(R.layout.nav_header);
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
// set item as selected to persist highlight
menuItem.setChecked(true);
// close drawer when item is tapped
mDrawerLayout.closeDrawers();
// Add code here to update the UI based on the item selected
// For example, swap UI fragments here
switch (menuItem.getItemId()) {
case R.id.nav_myCards:
menuItem.setChecked(true);
getSupportActionBar().setTitle("MY Cards");
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame,new MyCardFragment())
.commit();
break;
return true;
}
});
mDrawerLayout.addDrawerListener(
new DrawerLayout.DrawerListener() {
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
// Respond when the drawer's position changes
}
#Override
public void onDrawerOpened(View drawerView) {
// Respond when the drawer is opened
}
#Override
public void onDrawerClosed(View drawerView) {
// Respond when the drawer is closed
}
#Override
public void onDrawerStateChanged(int newState) {
// Respond when the drawer motion state changes
}
}
);
navigationView.getMenu().getItem(0).setChecked(true);
//Highlighted
//onNavigationItemSelected(navigationView.getMenu().getItem(0));
setupFirebaseAuth();
if (currentUser != null){
//updateNavHeader();
}
}
Custom Dialog Fragment:
DialogCompanyAddress.java:
public class DialogCompanyAddress extends DialogFragment {
public DialogCompanyAddress() {
// Required empty public constructor
}
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.fragment_dialog_company_address,null));
builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//save data to the firebase
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Do
}
});
return builder.create();
}
}
finally the adapter:
RecyclerviewAdapter.java:
public class RecyclerviewAdapter extends RecyclerView.Adapter<RecyclerviewAdapter.MyHolder> {
// ... constructor and member variables
// Usually involves inflating a layout from XML and returning the holder
Context mContext;
List<Template> listdata;
public RecyclerviewAdapter(Context context,List<Template> listdata) {
this.mContext = context;
this.listdata = listdata;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
/*// Inflate the custom layout
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview,parent,false);
// Return a new holder instance
MyHolder myHolder = new MyHolder(view);
return myHolder;*/
View view = LayoutInflater.from(mContext).inflate(R.layout.cardview,parent,false);
return new MyHolder(view);
}
public void onBindViewHolder(MyHolder holder, int position) {
holder.pname.setText(listdata.get(position).getP_name());
holder.pdesignation.setText(listdata.get(position).getP_designation());
holder.pemail.setText(listdata.get(position).getP_email());
holder.pphone.setText(listdata.get(position).getP_phone());
holder.cname.setText(listdata.get(position).getC_name());
holder.caddress.setText(listdata.get(position).getC_address());
//holder.tempID.setText(listdata.get(position).getTempID());
Glide.with(mContext).load(listdata.get(position).getC_logo()).into(holder.logo_image);
}
#Override
public int getItemCount() {
//return listdata.size();
int arr = 0;
try{
if(listdata.size()==0) {
arr = 0;
} else {
arr=listdata.size();
}
} catch (Exception e){
e.printStackTrace();
}
return arr;
}
class MyHolder extends RecyclerView.ViewHolder{
// Your holder should contain a member variable
// for any view that will be set as you render a row
TextView pname,caddress,pemail,pdesignation,pphone,cname,tempID;
ImageView logo_image;
// We also create a constructor that accepts the entire item row
// and does the view lookups to find each subview
public MyHolder(final View itemView) {
// Stores the itemView in a public final member variable that can be used
// to access the context from any ViewHolder instance.
super(itemView);
pname = (TextView) itemView.findViewById(R.id.txt_personName);
caddress = (TextView) itemView.findViewById(R.id.txt_address);
pemail = (TextView) itemView.findViewById(R.id.txt_email);
pdesignation = (TextView) itemView.findViewById(R.id.txt_designation);
pphone = (TextView) itemView.findViewById(R.id.txt_phone);
cname = (TextView) itemView.findViewById(R.id.txt_companyName);
logo_image = itemView.findViewById(R.id.imageView);
tempID = itemView.findViewById(R.id.tempID);
caddress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(mContext,"Clicked on Address",Toast.LENGTH_SHORT).show();
DialogCompanyAddress address = new DialogCompanyAddress();
//address.show(getSupportFragmentManager);--->This line give me error
}
});
}
}
use a interface in your adapter like below
public class RecyclerviewAdapter extends RecyclerView.Adapter<RecyclerviewAdapter.MyHolder> {
public interface ClickListner {
void IconClick(Template template);
}
Context mContext;
List<Template> listdata;
private final ClickListner listner;
public RecyclerviewAdapter(Context context, List<Template> listdata, ClickListner listner) {
this.mContext = context;
this.listdata = listdata;
this.listner = listner;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.cardview, parent, false);
return new MyHolder(view);
}
public void onBindViewHolder(MyHolder holder, int position) {
holder.pname.setText(listdata.get(position).getP_name());
holder.pdesignation.setText(listdata.get(position).getP_designation());
holder.pemail.setText(listdata.get(position).getP_email());
holder.pphone.setText(listdata.get(position).getP_phone());
holder.cname.setText(listdata.get(position).getC_name());
holder.caddress.setText(listdata.get(position).getC_address());
//holder.tempID.setText(listdata.get(position).getTempID());
Glide.with(mContext).load(listdata.get(position).getC_logo()).into(holder.logo_image);
holder.bind(listdata.get(position), listner);
}
#Override
public int getItemCount() {
//return listdata.size();
int arr = 0;
try {
if (listdata.size() == 0) {
arr = 0;
} else {
arr = listdata.size();
}
} catch (Exception e) {
e.printStackTrace();
}
return arr;
}
class MyHolder extends RecyclerView.ViewHolder {
TextView pname, caddress, pemail, pdesignation, pphone, cname, tempID;
ImageView logo_image;
public MyHolder(final View itemView) {
super(itemView);
pname = (TextView) itemView.findViewById(R.id.txt_personName);
caddress = (TextView) itemView.findViewById(R.id.txt_address);
pemail = (TextView) itemView.findViewById(R.id.txt_email);
pdesignation = (TextView) itemView.findViewById(R.id.txt_designation);
pphone = (TextView) itemView.findViewById(R.id.txt_phone);
cname = (TextView) itemView.findViewById(R.id.txt_companyName);
logo_image = itemView.findViewById(R.id.imageView);
tempID = itemView.findViewById(R.id.tempID);
// caddress.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// //Toast.makeText(mContext,"Clicked on
Address",Toast.LENGTH_SHORT).show();
// DialogCompanyAddress address = new DialogCompanyAddress();
// //address.show(getSupportFragmentManager);--->This line give me
error
//
// }
// });
}
public void bind(final Template template, final ClickListner Listner) {
// DeleteIcon.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// delListner.onDeleteIconClick(card, position);
// }
// });
caddress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Listner.IconClick(template);
}
});
}
}
and in your fragment you need to initialize the adapter. when initialize you can override the ClickListner interface.

Passing results (serializable class) from DialogFragment to Fragment

I have main activity which contains fragments. One of the fragment is calling dialogFragment for new item entry. This new item is specified by Serializable class.
Just to be more specific:
item.java
public class Item implements Serializable {
private String mTitle;
private String mDescription;
private Boolean mTrue;
//getters and setters
public String getTitle() {
return mTitle;
}
public void setTitle(String mTitle) {
this.mTitle = mTitle;
}
public String getDescription() {
return mDescription;
}
public void setDescription(String mDescription) {
this.mDescription = mDescription;
}
public Boolean isTrue() {
return mTrue;
}
public void setTrue(Boolean mTrue) {
this.mTrue = mTrue;
}
}
DialogNewItem
public class DialogNewItem extends DialogFragment {
//filters state holder
Boolean isTrue = false;
//filters state end
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.new_item, null);
final EditText editTitle = (EditText) dialogView.findViewById(R.id.editTitle);
final EditText editDescription = (EditText) dialogView.findViewById(R.id.editDescription)
//filter icons
final ImageView ivIsTrue = (ImageView) dialogView.findViewById(R.id.filterTrue);
//filter icons end
//onClickListener for filter icons
ivIsTrue.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (isTrue == false) {
ivIsTrue.setBackgroundResource(R.drawable.border_white);
ivIsTrue.setImageResource(R.drawable.true_white);
isTrue = true;
} else {
ivIsTrue.setBackgroundResource(R.drawable.border_green);
ivIsTrue.setImageResource(R.drawable.true_green);
isTrue = false;
}
}
});
Button btnCancel = (Button) dialogView.findViewById(R.id.btnCancel);
Button btnOK = (Button) dialogView.findViewById(R.id.btnOK);
builder.setView(dialogView);
//cancel button
btnCancel.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
dismiss();
}
});
//give button
btnOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//new item
final Item newItem = new Item();
//Set its variables to match the users entries on the form
newItem.setTitle(editTitle.getText().toString());
newItem.setDescription(editDescription.getText().toString());
newItem.setTrue(isTrue);
dismiss();
}
});
return builder.create();
}
}
Now, I want to pass newItem from DialogNewItem (btnOK) to a listView Fragment. In other words I want to make a listView Fragment which will contain all the new items created in DialogNewItem.
I was trying different methods (set/getFragment, ArrayList, different interfaces, etc) but some how non of it works. I have no problem with passing newItem to listView in an activity:
//get the reference to dashboard
Dashboard callingActivity = (Dashboard) getActivity();
//pass new item back to dashboard
callingActivity.createNewItem(newItem);
and then dashboard activity:
public class Dashboard extends AppCompatActivity {
private ItemAdapter mItemAdapter;
public void createNewItem(Item n) {
mItemAdapter.addItem(n);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
mItemAdapter = new ItemAdapter();
ListView listItem = (ListView) findViewById(R.id.listView);
listItem.setAdapter(mItemAdapter);
}
//handle clicks on listView
listItem.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick (AdapterView<?> adapter, View view, int whichItem, long id ){
//creating temporary item which is reference to the clicked item
Item tempItem = mItemAdapter.getItem(whichItem);
//new dialog window
DialogShowItem dialog = new DialogShowItem();
//send reference to the item to be shown
dialog.sendItemSelected(tempItem);
//show the dialog window with the item
dialog.show(getFragmentManager(),"");
}
});
#Override
public View getView(int whichItem, View view, ViewGroup viewGroup){
//has been inflated already
if (view==null){
//creating layout inflater
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//instantiate view by inflating inflater (listItem layout)
view = inflater.inflate(R.layout.listitem, viewGroup, false);
}
Item tempItem = itemList.get(whichItem);
//grabbing the refrence to all variables
TextView txtTitle = (TextView) view.findViewById(R.id.txtTitle);
TextView txtDescription = (TextView) view.findViewById(R.id.txtDescription);
ImageView ivTrue = (ImageView) view.findViewById(R.id.imgSmTrue);
//setting text variables
txtTitle.setText(tempItem.getTitle());
txtDescription.setText(tempItem.getDescription());
//hide not relevant images
if (!tempItem.isTrue()){
ivTrue.setVisibility(View.INVISIBLE);
} else {ivTrue.setVisibility(View.VISIBLE);}
//category with different image src
return view;
}
and everything works perfectly, but when I want to do the same with Fragment instead of Activity, somehow I cannot make it work.
I would appreciate any help. Thanx
Fragment (with listview):
public class ListItems extends ListFragment {
private ItemAdapter mItemAdapter;
public void createNewItem(Item i) {
mItemAdapter.addItem(i);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstatceState) {
View view = inflater.inflate(R.layout.list_items, container, false);
//Item adapter
mItemAdapter = new ItemAdapter();
final ListView listItems = (ListView) view.findViewById(R.id.listView);
listItems.setAdapter(mItemAdapter);
//floating give button
FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DialogNewItem dialog = new DialogNewItem();
dialog.show(getFragmentManager(), "");
}
});
//handle clicks on itemList
listItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int whichItem, long id) {
Item tempItem = mItemAdapter.getItem(whichItem);
DialogShowItem dialog = new DialogShowItem();
dialog.sendItemSelected(tempItem);
dialog.show(getFragmentManager(), "");
}
});
return view;
}
#Override
protected void onPause() {
super.onPause();
mItemAdapter.saveItems();
}
public class ItemAdapter extends BaseAdapter {
List<Item> itemList = new ArrayList<Item>();
private JSONSerializer mSerializer;
public ItemAdapter() {
mSerializer = new JSONSerializer("myProject.json", getActivity().getApplicationContext());
try {
itemList = mSerializer.load();
} catch (Exception e) {
itemList = new ArrayList<Item>();
Log.e("Error loading items: ", "", e);
}
}
public void saveItems() {
try {
mSerializer.save(itemList);
} catch (Exception e) {
Log.e("Error saving items: ", "", e);
}
}
#Override
public int getCount() {
return itemList.size();
}
#Override
public Item getItem(int whichItem) {
return itemList.get(whichItem);
}
#Override
public long getItemId(int whichItem) {
return whichItem;
}
public void addItem(Item n) {
itemList.add(n);
notifyDataSetChanged();
}
#Override
public View getView(int whichItem, View view, ViewGroup viewGroup) {
if (view==null) {
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_items, viewGroup, false);
}
Item tempItem = itemList.get(whichItem);
TextView txtTitle = (TextView) view.findViewById(R.id.txtTitle);
TextView txtDescription = (TextView) view.findViewById(R.id.txtDescription);
ImageView ivTrue = (ImageView) view.findViewById(R.id.imgSmTrue);
//setting text variables
txtTitle.setText(tempItem.getTitle());
txtDescription.setText(tempItem.getDescription());
//hide irrelevant images
if (!tempItem.isTrue()){
ivTrue.setVisibility(View.INVISIBLE);
} else {ivTrue.setVisibility(View.VISIBLE);}
return view;
}
}
}
It's a drawer activity so I'm showing it after drawer item click:
private void switchFragment(int position) {
Fragment fragment = null;
String fragmentID = "";
switch (position) {
case 0:
fragmentID = "LISTITEMS";
fragment = new ListItems();
break;
case 1:
fragmentID = "PROFILE";
fragment = new Profile();
break;
default:
break;
}
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragmentHolder, fragment, fragmentID).commit();
//close the drawer
mDrawerLayout.closeDrawer(mNavDrawerList);
}
You can make a public method in ListItems fragment class in which you receive an Item class object and add it in adapter. And then inside your DialogNewItem Fragment, On OK Button click, you can search the ListItems using SupportFragmentManager by using its tag and call the public method you wrote.
The following code might help you.
DialogNewItem class
btnOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//new item
final Item newItem = new Item();
//Set its variables to match the users entries on the form
newItem.setTitle(editTitle.getText().toString());
newItem.setDescription(editDescription.getText().toString());
newItem.setTrue(isTrue);
FragmentManager manager = getActivity().getSupportFragmentManager();
ListItems fragment = (ListItems)manager.findFragmentByTag("LISTITEMS");
if(fragment != null){
fragment.createNewItem(newItem);
}
dismiss();
}
});
In your ListItems fragment the following code will depict an ItemAdapter as the data member of the ListViewFragment class and below that is the method you can call to add the item in the adapter.
private ItemAdapter mItemAdapter;
public void createNewItem(Item n) {
mItemAdapter.addItem(n);
}

How to refresh ListView after deleting element?

I have created a listview but when i delete a element, it doesn't refresh. I have tried
adapter.notifyDataSetChanged();
and
getListView().invalidateViews();
in mainactivity:
case R.id.ordini:
Ordini O = new Ordini();
android.app.FragmentManager fragmentManager0 = getFragmentManager();
android.app.FragmentTransaction fragmentTransaction0 = fragmentManager0
.beginTransaction();
fragmentTransaction0.replace(R.id.frame, O);
fragmentTransaction0.commit();
Ordini.java
public class Ordini extends ListFragment implements AdapterView.OnItemClickListener {
int ArraySize;
CustomAdapterOrdini adapter;
private List<RowItemOrdini> rowItems;
Button SendButton;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.ordini, null, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArraySize = MainActivity.ArrayProdotto.size();
SendButton = (Button) getActivity().findViewById(R.id.send_btn);
rowItems = new ArrayList<RowItemOrdini>();
for (int i = 0; i < ArraySize; i++) {
RowItemOrdini items = new RowItemOrdini(
MainActivity.ArrayProdotto.get(i),
R.drawable.ic_delete_black_24dp,
MainActivity.ArrayCode.get(i),
MainActivity.ArrayPrezzo.get(i),
MainActivity.ArrayColli.get(i),
MainActivity.ArrayQuantita.get(i));
rowItems.add(items);
}
adapter = new CustomAdapterOrdini(getActivity(), rowItems);
setListAdapter(adapter);
getListView().setOnItemClickListener(this);
SendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "invio ordine in corso... ", Toast.LENGTH_SHORT)
.show();
SendOrdine();
}
});
}
#Override
public void onResume(){
super.onResume();
adapter.notifyDataSetChanged();
getListView().invalidateViews();
}
CustomAdapterOrdini
public class CustomAdapterOrdini extends BaseAdapter {
Context context;
List<RowItemOrdini> rowItem;
ImageView Del;
TextView Colli, Prezzo, Quantita, Code, Product;
CustomAdapterOrdini(Context context, List<RowItemOrdini> rowItem) {
this.context = context;
this.rowItem = rowItem;
}
#Override
public int getCount() {
return rowItem.size();
}
#Override
public Object getItem(int position) {
return rowItem.get(position);
}
#Override
public long getItemId(int position) {
return rowItem.indexOf(getItem(position));
}
#Override
public boolean areAllItemsEnabled() {
return false;
}
#Override
public boolean isEnabled(int position) {
return false;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.list_ordini, null);
}
Code = (TextView) convertView.findViewById(R.id.prodcode);
Product = (TextView) convertView.findViewById(R.id.PRODOTTO);
Del = (ImageView) convertView.findViewById(R.id.del);
Colli = (TextView) convertView.findViewById(R.id.T1);
Prezzo = (TextView) convertView.findViewById(R.id.T2);
Quantita = (TextView) convertView.findViewById(R.id.T3);
Del.setFocusable(true);
Del.setClickable(true);
Del.setTag(convertView);
final RowItemOrdini row_pos = rowItem.get(position);
// setting the image resource and title
Del.setImageResource(R.drawable.ic_delete_black_24dp);
Product.setText(row_pos.getTitle());
Code.setText(row_pos.getCode());
Colli.setText(row_pos.getColli());
Prezzo.setText(row_pos.getPrezzo());
Quantita.setText(row_pos.getQuantita());
Del.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// HERE I WANT REFRESH MY LISTVIEW
MainActivity.ArrayQuantita.remove(0);
MainActivity.ArrayCode.remove(0);
MainActivity.ArrayProdotto.remove(0);
MainActivity.ArrayColli.remove(0);
MainActivity.ArrayPrezzo.remove(0);
CustomAdapter.ShowDialog("Elemento eliminato con successo!", context);
}
});
return convertView;
}
Can someone help me with listview refresh?
I want refresh my listview in CustomAdapterOrdini or in onResume in Ordini.java.
public void onClick(View v) {
// HERE I WANT REFRESH MY LISTVIEW
There is a simple way?
Thank you so much!
You have declare ArrayProdotto in your MainActivity and you are display your data from rowItem in CustomAdapterOrdini. You have to remove your data from both list and call notifyDataSetChanged();
Like as below code.
Del.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// HERE I WANT REFRESH MY LISTVIEW
MainActivity.ArrayProdotto.remove(position); //Delete from main source
rowItem.remove(position) // Delete from adapter
CustomAdapter.ShowDialog("Elemento eliminato con successo!", context);
notifyDataSetChanged(); // Refresh Adapter
}
});
1). Remove your item from adapter:
adapter.remove(adapter.getItem(position));
2). Call adapter.notifyDataSetChanged();
You should call notifyDataSetChanged() every time when you deleting item from adapter. Not only in onResume.
Note, that you should remove item from adapter, to change ListView items, not from storage(ArrayList, SQLite, or else).

Categories