I made a navigation in my project, than I have activities, I would made menu from those activities into navigation. so I need to convert those activities into fragments.
This my first activity.java
public class ToDoList extends AppCompatActivity implements BatListener, OnItemClickListener, OnOutsideClickedListener {
private BatRecyclerView mRecyclerView;
private BatAdapter mAdapter;
private List<BatModel> mGoals;
private BatItemAnimator mAnimator;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.to_do_list);
// Navigator
FoldingTabBar tabBar = (FoldingTabBar) findViewById(R.id.folding_tab_bar);
tabBar.setOnFoldingItemClickListener(new FoldingTabBar.OnFoldingItemSelectedListener() {
#Override
public boolean onFoldingItemSelected(#NotNull MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_profile:
Intent intent0 = new Intent(ToDoList.this, Home.class);
startActivity(intent0);
break;
case R.id.menu_todo:
break;
case R.id.menu_schedule:
Intent intent1 = new Intent(ToDoList.this, TimeTable.class);
startActivity(intent1);
break;
case R.id.menu_settings:
break;
}
return false;
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
((TextView) findViewById(R.id.text_title)).setTypeface(TypefaceUtil.getAvenirTypeface(this));
mRecyclerView = (BatRecyclerView) findViewById(R.id.bat_recycler_view);
mAnimator = new BatItemAnimator();
mRecyclerView.getView().setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.getView().setAdapter(mAdapter = new BatAdapter(mGoals = new ArrayList<BatModel>() {{
}}, this, mAnimator).setOnItemClickListener(this).setOnOutsideClickListener(this));
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new BatCallback(this));
itemTouchHelper.attachToRecyclerView(mRecyclerView.getView());
mRecyclerView.getView().setItemAnimator(mAnimator);
mRecyclerView.setAddItemListener(this);
findViewById(R.id.root).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mRecyclerView.revertAnimation();
}
});
}
#Override
public void add(String string) {
mGoals.add(0, new Goal(string));
mAdapter.notify(AnimationType.ADD, 0);
}
#Override
public void delete(int position) {
mGoals.remove(position);
mAdapter.notify(AnimationType.REMOVE, position);
}
#Override
public void move(int from, int to) {
if (from >= 0 && to >= 0) {
mAnimator.setPosition(to);
BatModel model = mGoals.get(from);
mGoals.remove(model);
mGoals.add(to, model);
mAdapter.notify(AnimationType.MOVE, from, to);
if (from == 0 || to == 0) {
mRecyclerView.getView().scrollToPosition(Math.min(from, to));
}
}
}
#Override
public void onClick(BatModel item, int position) {
Toast.makeText(this, item.getText(), Toast.LENGTH_SHORT).show();
}
#Override
public void onOutsideClicked() {
mRecyclerView.revertAnimation();
}
}
I tried to use this code, from Mr Abhi instruction, I just edited a little bit for removing the toolbar, and some I solved.
This is my fragment.java
public class ToDoListFragment extends Fragment implements BatListener, OnItemClickListener, OnOutsideClickedListener {
private BatRecyclerView mRecyclerView;
private BatAdapter mAdapter;
private List<BatModel> mGoals;
private BatItemAnimator mAnimator;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.todo_list_fragment, null);
return root;
}
public void onViewCreated(View view, Bundle savedInstanceState) {
// you can add listener of elements here
/*Button mButton = (Button) view.findViewById(R.id.button);
mButton.setOnClickListener(this); */
((TextView) view.findViewById(R.id.tdl_date)).setTypeface(TypefaceUtil.getAvenirTypeface(getActivity()));
mRecyclerView = (BatRecyclerView) view.findViewById(R.id.tdl_bat_recyclerView);
mAnimator = new BatItemAnimator();
mRecyclerView.getView().setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerView.getView().setAdapter(mAdapter = new BatAdapter(mGoals = new ArrayList<BatModel>() {{
}}, this, mAnimator).setOnItemClickListener(this).setOnOutsideClickListener(this));
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new BatCallback(this));
itemTouchHelper.attachToRecyclerView(mRecyclerView.getView());
mRecyclerView.getView().setItemAnimator(mAnimator);
mRecyclerView.setAddItemListener(this);
view.findViewById(R.id.root).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mRecyclerView.revertAnimation();
}
});
}
#Override
public void add(String string) {
mGoals.add(0, new Goal(string));
mAdapter.notify(AnimationType.ADD, 0);
}
#Override
public void delete(int position) {
mGoals.remove(position);
mAdapter.notify(AnimationType.REMOVE, position);
}
#Override
public void move(int from, int to) {
if (from >= 0 && to >= 0) {
mAnimator.setPosition(to);
BatModel model = mGoals.get(from);
mGoals.remove(model);
mGoals.add(to, model);
mAdapter.notify(AnimationType.MOVE, from, to);
if (from == 0 || to == 0) {
mRecyclerView.getView().scrollToPosition(Math.min(from, to));
}
}
}
#Override
public void onClick(BatModel item, int position) {
Toast.makeText(getActivity(), item.getText(), Toast.LENGTH_SHORT).show();
}
#Override
public void onOutsideClicked() {
mRecyclerView.revertAnimation();
}
But it crushed when I started the app. the log showed that No view found for id 0x7f09004c (package:id/container) for fragment.
I hope you guys could help me as you teach me. Thanks for the second time.
To convert an Activity to a Fragment, you first have to extend Fragment. then you'll have to make some basic necessary changes in the code like:
1.onCreateView(LayoutInflater, ViewGroup, Bundle) instead of onCreate
2.findViewById() becomes getView().findViewById().
Your sample code:
public class ToDoList extends Fragment implements BatListener, OnItemClickListener, OnOutsideClickedListener {
private BatRecyclerView mRecyclerView;
private BatAdapter mAdapter;
private List<BatModel> mGoals;
private BatItemAnimator mAnimator;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.todo_list_fragment, null);
return root;
}
public void onViewCreated(View view, Bundle savedInstanceState) {
// you can add listener of elements here
/*Button mButton = (Button) view.findViewById(R.id.button);
mButton.setOnClickListener(this); */
// Navigator
FoldingTabBar tabBar = (FoldingTabBar) view.findViewById(R.id.folding_tab_bar);
tabBar.setOnFoldingItemClickListener(new FoldingTabBar.OnFoldingItemSelectedListener() {
#Override
public boolean onFoldingItemSelected(#NotNull MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_profile:
Intent intent0 = new Intent(ToDoList.this, Home.class);
startActivity(intent0);
break;
case R.id.menu_todo:
break;
case R.id.menu_schedule:
Intent intent1 = new Intent(ToDoList.this, TimeTable.class);
startActivity(intent1);
break;
case R.id.menu_settings:
break;
}
return false;
}
});
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
((TextView) view.findViewById(R.id.text_title)).setTypeface(TypefaceUtil.getAvenirTypeface(this));
mRecyclerView = (BatRecyclerView) view.findViewById(R.id.bat_recycler_view);
mAnimator = new BatItemAnimator();
mRecyclerView.getView().setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.getView().setAdapter(mAdapter = new BatAdapter(mGoals = new ArrayList<BatModel>() {{
}}, this, mAnimator).setOnItemClickListener(this).setOnOutsideClickListener(this));
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new BatCallback(this));
itemTouchHelper.attachToRecyclerView(mRecyclerView.getView());
mRecyclerView.getView().setItemAnimator(mAnimator);
mRecyclerView.setAddItemListener(this);
view.findViewById(R.id.root).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mRecyclerView.revertAnimation();
}
});
}
#Override
public void add(String string) {
mGoals.add(0, new Goal(string));
mAdapter.notify(AnimationType.ADD, 0);
}
#Override
public void delete(int position) {
mGoals.remove(position);
mAdapter.notify(AnimationType.REMOVE, position);
}
#Override
public void move(int from, int to) {
if (from >= 0 && to >= 0) {
mAnimator.setPosition(to);
BatModel model = mGoals.get(from);
mGoals.remove(model);
mGoals.add(to, model);
mAdapter.notify(AnimationType.MOVE, from, to);
if (from == 0 || to == 0) {
mRecyclerView.getView().scrollToPosition(Math.min(from, to));
}
}
}
#Override
public void onClick(BatModel item, int position) {
Toast.makeText(this, item.getText(), Toast.LENGTH_SHORT).show();
}
#Override
public void onOutsideClicked() {
mRecyclerView.revertAnimation();
}
}
I haven't edited all code and further changes maybe required. Do the changes accordingly.
Related
I have to display a list of items on recyclerview from a remote network call. I have initialized the recyclerview and set it's layout manager and adapter properly but the list doesn't show.
Here's my adapter class:
public class DashboardAdapter extends RecyclerView.Adapter<HomeDashboardHolder> {
private final Context context;
private List<HomeDashboard> itemsList;
public DashboardAdapter(Context context, List<HomeDashboard> itemsList) {
this.context = context;
this.itemsList = itemsList;
}
#Override
public HomeDashboardHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.home_dashboard_items_layout, parent, false);
return new HomeDashboardHolder(view);
}
#Override
public void onBindViewHolder(HomeDashboardHolder viewholder, int position) {
HomeDashboard dashboard = itemsList.get(position);
viewholder.dashTitle.setText(dashboard.getDashTitle());
Picasso.with(context)
.load(dashboard.getDashIcon())
.placeholder(R.drawable.noimage)
.into(viewholder.dashIcon);
}
#Override
public int getItemCount() {
if (itemsList == null) {
return 0;
}
return itemsList.size();
}
}
Here's my activity code so far:
public class HomeActivity extends AppCompatActivity {
private static final String TAG = HomeActivity.class.getSimpleName();
private Toolbar toolbar;
private SwipeRefreshLayout swipeRefresh;
private RecyclerView dashboardRV, recyclerDrawer;
private DrawerLayout drawerLayout;
private List<DrawerItems> itemsList = new ArrayList<>();
private List<HomeDashboard> dashboardsList = new ArrayList<>();
private RecyclerView.LayoutManager layoutManager;
private RecyclerDrawerAdapter drawerAdapter;
private DashboardAdapter dashboardAdapter;
private String slug;
private int cartLength;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
init();
setSupportActionBar(toolbar);
initDrawer();
setUpDashboard();
}
private void initDrawer() {
recyclerDrawer.setHasFixedSize(true);
recyclerDrawer.setLayoutManager(new LinearLayoutManager(this));
DrawerItems drawerItems = new DrawerItems("Products", R.drawable.basket);
itemsList.add(drawerItems);
DrawerItems drawerItems1 = new DrawerItems("Cart", R.drawable.cart);
itemsList.add(drawerItems1);
DrawerItems drawerItems2 = new DrawerItems("Checkout", R.drawable.check_out);
itemsList.add(drawerItems2);
DrawerItems drawerItems3 = new DrawerItems("Profile", R.drawable.profile);
itemsList.add(drawerItems3);
DrawerItems drawerItems4 = new DrawerItems("Info", R.drawable.info);
itemsList.add(drawerItems4);
DrawerItems drawerItems5 = new DrawerItems("About", R.drawable.about);
itemsList.add(drawerItems5);
drawerAdapter = new RecyclerDrawerAdapter(this, itemsList);
recyclerDrawer.setAdapter(drawerAdapter);
toolbar.setNavigationIcon(R.drawable.burger_menu);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
drawerLayout.openDrawer(GravityCompat.START);
}
}
});
setDrawerClickListener();
}
private void setDrawerClickListener() {
recyclerDrawer.addOnItemTouchListener(new RecyclerItemTouchListener(this, recyclerDrawer, new RecyclerClickListener() {
#Override
public void onClick(View view, int position) {
switch (position) {
case 0:
startActivity(new Intent(HomeActivity.this, AllProductsActivity.class));
drawerLayout.closeDrawer(GravityCompat.START);
break;
case 1:
startActivity(new Intent(HomeActivity.this, CartActivity.class));
drawerLayout.closeDrawer(GravityCompat.START);
break;
case 2:
Intent intent = new Intent(HomeActivity.this, CheckOutActivity.class);
startActivity(intent);
drawerLayout.closeDrawer(GravityCompat.START);
break;
case 3:
startActivity(new Intent(HomeActivity.this, ProfileActivity.class));
drawerLayout.closeDrawer(GravityCompat.START);
break;
case 4:
Log.d(TAG, "Info Clicked");
break;
case 5:
startActivity(new Intent(HomeActivity.this, AboutActivity.class));
drawerLayout.closeDrawer(GravityCompat.START);
break;
}
}
#Override
public void onLongClick(View view, int position) {
}
}));
}
private void init() {
swipeRefresh = findViewById(R.id.swipeRefresh);
toolbar = findViewById(R.id.toolbar);
dashboardRV = findViewById(R.id.dashboardRV);
recyclerDrawer = findViewById(R.id.recyclerDrawer);
drawerLayout = findViewById(R.id.drawerLayout);
}
private void setUpDashboard() {
dashboardRV.setHasFixedSize(true);
layoutManager = new GridLayoutManager(HomeActivity.this, 2, GridLayoutManager.VERTICAL, false);
dashboardRV.setLayoutManager(layoutManager);
getHomeDash();
}
public void getHomeDash() {
AndroidNetworking.get(Constants.CATEGORIES_ENDPOINT)
.setTag("Get Categories Dashboard")
.setPriority(Priority.HIGH)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, "Categories Response:\t" + response.toString());
try {
JSONObject jsonObject = new JSONObject(response.toString());
final JSONArray categories = jsonObject.getJSONArray("categories");
for (int i = 0; i < categories.length(); i++) {
JSONObject object = categories.getJSONObject(i);
String id = object.getString("_id");
String title = object.getString("title");
String image = object.getString("image");
slug = object.getString("slug");
HomeDashboard dashboard = new HomeDashboard();
dashboard.setDashIcon(image);
dashboard.setDashTitle(title);
dashboard.setId(id);
dashboardsList.add(dashboard);
}
dashboardAdapter = new DashboardAdapter(getApplicationContext(), dashboardsList);
dashboardRV.setAdapter(dashboardAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
dashboardAdapter.notifyDataSetChanged();
}
#Override
public void onError(ANError anError) {
Log.d(TAG, "Request Failed:\t" + anError.getMessage());
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.app_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_view_cart:
startActivity(new Intent(HomeActivity.this, CartActivity.class));
}
return true;
}
#Override
protected void onResume() {
super.onResume();
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
}
}
}
Here's my sample json response for this activity:
D/HomeActivity: Categories Response: {"success":true,"message":"All Categories","categories":[{"_id":"5aac46d8644ac63f14ffe89b","title":"Shrti","slug":"shrti","image":"http:\/\/res.cloudinary.com\/aapni-dukan\/image\/upload\/v1521239768\/categoryImages\/eBeSBYrG7MP7rW2Sa4qqQd06_lwakio.png"},{"_id":"5aac5b01d224ac3b801b9967","title":"Fruits","slug":"fruits","image":"http:\/\/res.cloudinary.com\/aapni-dukan\/image\/upload\/v1521244929\/categoryImages\/uWQT1XEplligclP4PrNC-Zyf_eamj8u.jpg"}]}
I am initializing and setting the adapter inside the getHomeDash(). I have also called notifyDataSetChanged() but nothing shows.
In the log, to check if the list is empty, I am getting the size as 2 but not able to show any items. I have also tried setting the adapter in onCreate() just after the call to getHomeDash() but still nothing is displayed on the screen.
Viewholder class:
public class HomeDashboardHolder extends RecyclerView.ViewHolder {
public ImageView dashIcon;
public TextView dashTitle;
public HomeDashboardHolder(View itemView) {
super(itemView);
dashIcon = itemView.findViewById(R.id.dashIcon);
dashTitle = itemView.findViewById(R.id.dashTitle);
}
}
Can someone help me out with this pls? Thanks
I think you are operating your UI ( notifyDataSetChanged() ) in a working thread in getHomeDash() JSONObjectRequestListener function.You should invoke this function in a main thread,and check the layout_height and layout_width in XML.
make change for recycler view layoutmanger set used below code..
dashboardRV.setLayoutManager(new GridLayoutManager(this, numberOfColumns,false));
You are calling dashboardAdapter.notifyDataSetChanged(); after creating new object of DashboardAdapter class
notifyDataSetChanged(); is used when there is some changes your list adapter
User this
layoutManager = new GridLayoutManager(HomeActivity.this,2);
Instead of this
layoutManager = new GridLayoutManager(HomeActivity.this, 2, GridLayoutManager.VERTICAL, false);
I am having a problem that whenever I switch between different tabs, the process lags for a second or two. How can I remove this lag? There is no such thing in oncreate function of the fragments. I am posting the code here.
This is the code for the activity that is calling the fragment Dashboardnew :
private void setupDrawerContent(final NavigationView navigationView) {
//revision: this don't works, use setOnChildClickListener() and setOnGroupClickListener() above instead
expandableList.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) {
if(i==0) {
//Toast.makeText(getApplicationContext(),"View Tasks",Toast.LENGTH_LONG).show();
fab.setVisibility(View.VISIBLE);
if (filterApplied) {
persistentbottomSheet.setVisibility(View.VISIBLE);
persistentbottomSheet.bringToFront();
fab.bringToFront();
}
fragment = new DashboardNew();
if (fragment != null) {
manager.beginTransaction().replace(R.id.dashboard_frame, fragment).commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
/* new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (fragment != null) {
manager.beginTransaction()
.replace(R.id.dashboard_frame, fragment)
.commit();
}
}
}, 300);*/
//drawer.closeDrawer(GravityCompat.START);
}
if(i==1) {
}
if(i==2) {
prefs.edit().remove("firstTime").apply();
Intent intent = new Intent(getApplication(), Login.class)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
finish();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
return false;
}
});
expandableList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView expandableListView, View view, int groupPosition, int childPosition, long l) {
if (groupPosition == 1 && childPosition == 0) {
fabvisibility = false;
//so this code only executes if the 2nd child in the 2nd group is clicked
fragment=new AddUser();
if (fragment != null) {
manager.beginTransaction()
.replace(R.id.dashboard_frame, fragment,"AddUser")
//.add(fragment,"AddUser")
// .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit();
}
drawer.closeDrawer(GravityCompat.START);
}
if (groupPosition == 1 && childPosition == 1) {
//so this code only executes if the 2nd child in the 2nd group is clicked
fabvisibility = false;
fragment=new ViewUsers();
if (fragment != null) {
manager.beginTransaction()
.replace(R.id.dashboard_frame, fragment)
.commit();
drawer.closeDrawer(GravityCompat.START);
}
}
return false;
}
});
}
#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.
switch (item.getItemId()) {
case android.R.id.home:
drawer.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
}
The code for Dashboardnew fragment is :
initialize(rootview);
clicklisteners();
createViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
createTabIcons();
return rootview;
}
private void clicklisteners()
{
usualTasks.setOnClickListener(this);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//you can set the title for your toolbar here for different fragments different titles
getActivity().setTitle("The Checklist");
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.toggleButton: {
if(usualTasks.isChecked()) {
Toast.makeText(getActivity(), "Toggle button is on", Toast.LENGTH_LONG).show();
showRoleDialog();
FragmentTransaction trans = getFragmentManager().beginTransaction();
trans.replace(R.id.base_pending, new UsualTasks());
WelcomeActivity.persistentbottomSheet.setVisibility(View.INVISIBLE);
//WelcomeActivity.fab.setVisibility(View.INVISIBLE);
trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
trans.commit();
}
else {
Toast.makeText(getActivity(), "Toggle button is Off", Toast.LENGTH_LONG).show();
FragmentTransaction trans = getFragmentManager().beginTransaction();
trans.replace(R.id.usual_pending, new PendingTasks());
trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
if (WelcomeActivity.filterApplied == true) {
WelcomeActivity.persistentbottomSheet.setVisibility(View.VISIBLE);
WelcomeActivity.persistentbottomSheet.bringToFront();
WelcomeActivity.fab.setVisibility(View.VISIBLE);
}
if(UsualTasks.shown) {
UsualTasks.mSnackBar.dismiss();
}
trans.commit();
}
}
}
}
public void populateList(HashMap<Integer, String> myMap, List myList){
Set<Map.Entry<Integer, String>> setMap = myMap.entrySet();
Iterator<Map.Entry<Integer, String>> iteratorMap = setMap.iterator();
int item=0;
while(iteratorMap.hasNext()) {
Map.Entry<Integer, String> entry = (Map.Entry<Integer, String>) iteratorMap.next();
myList.add(entry.getValue());
item++;
}
}
private void showRoleDialog() {
final Dialog dialog = new Dialog(getContext());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.usualtask_dialog);
rolelist = new ArrayList<Map<Integer,String>>();
roles= new HashMap<Integer, String>();
roles.put(1, "Senior Manager");
roles.put(2, "Admin");
roles.put(3, "HR");
populateList(roles,rolelist);
ArrayAdapter arrayAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_single_choice, rolelist)
{
#Override
public View getView(int position, View convertView, ViewGroup parent){
// Get the current item from ListView
View view = super.getView(position,convertView,parent);
TextView tv = (TextView) view.findViewById(android.R.id.text1);
tv.setTextColor(Color.parseColor("#353b41"));
return view;
}
};
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
selectRole= (ListView)dialog.findViewById(R.id.selectrole);
submitRole= (Button)dialog.findViewById(R.id.btsubmitrole);
selectRole.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
selectRole.setAdapter(arrayAdapter);
selectRole.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {}
});
submitRole.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.show();
}
private void createTabIcons() {
RelativeLayout tabOne = (RelativeLayout) LayoutInflater.from(getContext()).inflate(R.layout.pending_tab, null);
TextView textTab=(TextView)tabOne.findViewById(R.id.tab);
ImageView imageTab=(ImageView) tabOne.findViewById(R.id.notifyimage);
//TextDrawable drawable = TextDrawable.builder().buildRound("999",Color.RED); // radius in px
TextDrawable drawable = TextDrawable.builder()
.buildRoundRect("999",Color.RED,18); // radius in px
imageTab.setImageDrawable(drawable);
textTab.setText("Pending");
tabLayout.getTabAt(1).setCustomView(tabOne);
RelativeLayout tabTwo = (RelativeLayout) LayoutInflater.from(getContext()).inflate(R.layout.completed_tab, null);
TextView textTab1=(TextView)tabTwo.findViewById(R.id.pending_tab);
textTab1.setText("Completed");
tabLayout.getTabAt(0).setCustomView(tabTwo);
}
private void initialize(View rootview) {
toolbar = (Toolbar)rootview.findViewById(R.id.toolbar);
viewPager = (ViewPager)rootview.findViewById(R.id.viewpager);
tabLayout = (TabLayout)rootview.findViewById(R.id.tabs);
usualTasks=(ToggleButton)rootview.findViewById(R.id.toggleButton);
}
private void createViewPager(ViewPager viewPager) {
adapter = new DashboardNew.ViewPagerAdapter(getChildFragmentManager());
adapter.addFrag(new CompletedTasks(), "Completed");
adapter.addFrag(new PendingTasks(), "Pending");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
if (position == 0)
return new CompletedTasks();
else
return new PendingTasks();
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
And here is the code for Completed tasks:
completedTaskList = (ListView) rootview.findViewById(R.id.completedlist);
BaseMenuActivity.filterState=false;
if(UsualTasks.shown) {
UsualTasks.mSnackBar.dismiss();
}
generateListdata();
return rootview;
}
private void generateListdata() {
completedTasks.add(new completedTasks("Call the Owner","Wembley GP","Daily",R.drawable.completed_tick,R.drawable.access_dashboard));
completedTasks.add(new completedTasks("Check the safety of patients","Wembley GP","Daily",R.drawable.completed_tick,R.drawable.safety_dashboard));
completedTasks.add(new completedTasks("Admin needs to do specific task","Wembley GP","Daily",R.drawable.completed_tick,R.drawable.admin_dashboard));
completedTasks.add(new completedTasks("Get the specific work done","Wembley GP","Daily",R.drawable.completed_tick,R.drawable.access_dashboard));
completedTasks.add(new completedTasks("Need to hire more resources","Wembley GP","Daily",R.drawable.completed_tick,R.drawable.hr_dashboard));
completedTasks.add(new completedTasks("How are patients behaving?","Wembley GP","Daily",R.drawable.completed_tick,R.drawable.patient_experience_dashboard));
completedTasks.add(new completedTasks("Need to adjust the audit report","Wembley GP","Daily",R.drawable.completed_tick,R.drawable.finance_dashboard));
//getListView().setDividerHeight(10);
ArrayAdapter<com.example.attech.checklist_attech.Model.completedTasks> adapter = new CompletedTaskAdapter(getContext(), 0,completedTasks);
completedTaskList.setAdapter(adapter);
completedTaskList.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (position == 0) {}
if (position == 1) {}
if (position == 2) {
//Intent myIntent = new Intent(view.getContext(), ViewUser.class);
//startActivityForResult(myIntent, 0);
}
}
});
}
}
This is the code for pendingtasks:
initialize(rootview);
generateListdataAssigned();
generateListdata();
generateselectall();
clickListeners();
return rootview;
}
private void clickListeners() {
assignTask.setOnClickListener(this);
assignTaskbottom.setOnClickListener(this);
}
private void populateList(HashMap<Integer, String> myMap, List myList){
Set<Map.Entry<Integer, String>> setMap = myMap.entrySet();
Iterator<Map.Entry<Integer, String>> iteratorMap = setMap.iterator();
int item=0;
while(iteratorMap.hasNext()) {
Map.Entry<Integer, String> entry = (Map.Entry<Integer, String>) iteratorMap.next();
myList.add(entry.getValue());
item++;
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.assignTaskPending: {
selected = !selected;
if (selected) {
Toast.makeText(getActivity(), "Assigned", Toast.LENGTH_LONG).show();
assignTask.setBackgroundResource(R.color.dark_grey);
Toast.makeText(getActivity(),""+WelcomeActivity.filterApplied,Toast.LENGTH_LONG).show();
pendingTaskListAssigned.setVisibility(View.VISIBLE);
WelcomeActivity.persistentbottomSheet.setVisibility(View.INVISIBLE);
selectAllListView.setVisibility(View.VISIBLE);
assignTaskbottom.setVisibility(View.VISIBLE);
pendingTaskList.setVisibility(View.INVISIBLE);
}
else {
Toast.makeText(getActivity(), "Clicked", Toast.LENGTH_LONG).show();
Toast.makeText(getActivity(),""+WelcomeActivity.filterApplied,Toast.LENGTH_LONG).show();
pendingTaskListAssigned.setVisibility(View.INVISIBLE);
assignTaskbottom.setVisibility(View.INVISIBLE);
selectAllListView.setVisibility(View.INVISIBLE);
assignTask.setBackgroundResource(R.drawable.box_grey);
pendingTaskList.setVisibility(View.VISIBLE);
if (WelcomeActivity.filterApplied) {
WelcomeActivity.persistentbottomSheet.setVisibility(View.VISIBLE);
WelcomeActivity.persistentbottomSheet.bringToFront();
WelcomeActivity.fab.setVisibility(View.VISIBLE);
}
}
break;
}
case R.id.btassignTask: {
showAssignTaskDialog();
break;
}
}
}
private void initialize(View rootview) {
pendingTaskList = (ListView) rootview.findViewById(R.id.pendinglist);
pendingTaskListAssigned = (ListView) rootview.findViewById(R.id.pendinglistassigned);
assignTask = (Button) rootview.findViewById(R.id.assignTaskPending);
assignTaskbottom = (Button) rootview.findViewById(R.id.btassignTask);
selectAllListView= (ListView)rootview.findViewById(R.id.selectalllist);
}
private void generateListdataAssigned() {
pendingTasksAssigned.add(new pendingTasks("System Tasks","Wembley GP","Daily",R.drawable.pending_clock_icon, R.drawable.safety_dashboard));
pendingTasksAssigned.add(new pendingTasks("Call answer speed","Wembley GP","Daily",R.drawable.pending_clock_icon, R.drawable.access_dashboard));
pendingTasksAssigned.add(new pendingTasks("Appointment reasons","Wembley GP","Daily",R.drawable.pending_clock_icon, R.drawable.access_dashboard));
pendingTasksAssigned.add(new pendingTasks("Admin needs to do specific task","Wembley GP","Daily",R.drawable.pending_clock_icon, R.drawable.hr_dashboard));
ArrayAdapter<pendingTasks> adapter = new PendingAssignedAdapter(getContext(), 0, pendingTasksAssigned);
pendingTaskListAssigned.setAdapter(adapter);
pendingTaskListAssigned.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
CheckBox checkBox=(CheckBox)view.findViewById(R.id.checkboxassigned);
checkBox.performClick();
if(checkBox.isChecked()){
countChecks = countChecks + 1;
}
else{
countChecks = countChecks - 1;
}
if(check == true){
selectAllListView.setItemChecked(0, false);
check = !check;
}
if(countChecks == pendingTaskListAssigned.getCount()){
selectAllListView.setItemChecked(0, true);
check = ! check;
}
}
});
}
//populating the arraylist, creating an adapter and setting it to a list view
private void generateListdata() {
pendingTasks.add(new pendingTasks("System Tasks", "Wembley GP", "Daily", R.drawable.pending_clock_icon, R.drawable.safety_dashboard));
pendingTasks.add(new pendingTasks("Call answer speed", "Wembley GP", "Daily", R.drawable.pending_clock_icon, R.drawable.access_dashboard));
pendingTasks.add(new pendingTasks("Appointment reasons", "Wembley GP", "Daily", R.drawable.pending_clock_icon, R.drawable.access_dashboard));
ArrayAdapter<pendingTasks> adapter = new PendingTaskAdapter(getContext(), 0, pendingTasks);
pendingTaskList.setAdapter(adapter);
pendingTaskList.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
showInputDialog();
if (position == 0) {}
if (position == 1) {
//Intent myIntent = new Intent(view.getContext(), AddUser.class);
//startActivityForResult(myIntent, 0);
}
if (position == 2) {
//Intent myIntent = new Intent(view.getContext(), ViewUser.class);
//startActivityForResult(myIntent, 0);
}
}
});
}
private void generateselectall() {
selectallList= new ArrayList<Map<Integer,String>>();
selectall= new HashMap<Integer, String>();
selectall.put(1, "Select All");
populateList(selectall,selectallList);
ArrayAdapter arrayAdapter = new ArrayAdapter<String>(getContext(),
android.R.layout.simple_list_item_single_choice, selectallList)
{
#Override
public View getView(int position, View convertView, ViewGroup parent){
// Get the current item from ListView
View view = super.getView(position,convertView,parent);
TextView tv = (TextView) view.findViewById(android.R.id.text1);
tv.setTextColor(Color.BLACK);
tv.setTextSize(13);
ViewGroup.LayoutParams params = view.getLayoutParams();
// Set the height of the Item View
params.height = LinearLayout.LayoutParams.WRAP_CONTENT;
view.setLayoutParams(params);
view.setPadding(37,0,10,10);
return view;
}
};
selectAllListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
selectAllListView.setAdapter(arrayAdapter);
selectAllListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Toast.makeText(getContext(), "Hello", Toast.LENGTH_SHORT).show();
int firstListItem = pendingTaskListAssigned.getFirstVisiblePosition();
int lastVisibleItem = pendingTaskListAssigned.getFirstVisiblePosition() + pendingTaskListAssigned.getChildCount() - 1;
check = ! check;
for(int i=0; i < pendingTaskListAssigned.getCount(); i++){
if(i>lastVisibleItem || i<firstListItem){
View item = (View) pendingTaskListAssigned.getAdapter().getView(i, null, pendingTaskListAssigned);
CheckBox checkbox = (CheckBox)item.findViewById(R.id.checkboxassigned);
checkbox.setChecked(check);
}
else{
ViewGroup item = (ViewGroup)pendingTaskListAssigned.getChildAt(i - firstListItem);
CheckBox checkbox = (CheckBox)item.findViewById(R.id.checkboxassigned);
checkbox.setChecked(check);
}
}
if(check == true){
countChecks = pendingTaskListAssigned.getCount();
}
else{
countChecks = 0;
}
}
});
}
protected void showInputDialog() {
final Dialog dialog = new Dialog(getContext());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.task_dialog);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
tbutton = (ToggleButton)dialog.findViewById(R.id.toggleButton);
toollamp= (ImageButton)dialog.findViewById(R.id.lamptool);
tooli= (ImageButton)dialog.findViewById(R.id.itool);
tooldetails= (TextView) dialog.findViewById(R.id.tooldetail);
submit=(Button)dialog.findViewById(R.id.btsubmit);
toollamp.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
tooldetails.setText("Target for staff 2 rings and answer.Check daily for 2x 5 mins");
}
});
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(getActivity(), "Dismiss", Toast.LENGTH_LONG).show();
dialog.dismiss();
}
});
tooli.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
tooldetails.setText("Check daily for 2x 5 mins");
}
});
tbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(tbutton.isChecked()) {
Toast.makeText(getActivity(), "Toggle button is on", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getActivity(), "Toggle button is Off", Toast.LENGTH_LONG).show();
}
}
});
dialog.show();
}
protected void showAssignTaskDialog() {
final Dialog dialog = new Dialog(getContext());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.assign_task_dialog);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
Close= (ImageButton)dialog.findViewById(R.id.close);
myself=(Button)dialog.findViewById(R.id.btmyself);
others=(Button)dialog.findViewById(R.id.btothers);
Close.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
myself.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Myself", Toast.LENGTH_LONG).show();
}
});
others.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Others", Toast.LENGTH_LONG).show();
Intent intent= new Intent(getContext(), AssignTasks.class);
startActivity(intent);
}
});
dialog.show();
}
}
For those who have this problem , please use cardviews and recyclerviews. The data was too much for list view. Used cardviews and recyclerviews instead , and the lag was gone.
First of all I cant get why you create fragments twice
You actually create fragments here
private void createViewPager(ViewPager viewPager) {
adapter = new DashboardNew.ViewPagerAdapter(getChildFragmentManager());
adapter.addFrag(new CompletedTasks(), "Completed");
adapter.addFrag(new PendingTasks(), "Pending");
viewPager.setAdapter(adapter);
}
And then you create them here. Again
#Override
public Fragment getItem(int position) {
if (position == 0)
return new CompletedTasks();
else
return new PendingTasks();
}
I guess right way is removing these lines
adapter.addFrag(new CompletedTasks(), "Completed");
adapter.addFrag(new PendingTasks(), "Pending");
In other case you will have big problems with screen rotation.
You can set offscreen limit (by default its 1 only), so fragments will be created only one time and will not be removed
viewPager.setOffscreenPageLimit(2);
Also I refuse to understand what these lines mean
completedTasks.add(new completedTasks(...);
Is it CompletedTasks fragment? What do you add and how?
There is no such thing in onCreate() function of the fragments.
But it is still lagging, right? I think the problem is with your layout which is too heavy because the only work you are doing in onCreateView() is setting your layout.
Please check if your images are of very high pixel density. This is a most common mistake. Android System takes time to convert those high pixel images in layout to lower pixel density which is suitable for your device which takes time and causes lag.
Other reason could be bad layout hierarchy.
you should extends your container activity from FragmentActivity
public class MainActivity extends FragmentActivity
{
}
this is very fast switch between fragment.
is better using tag in xml layout
and show , hide when click the tab or bottom tabs
//code example :
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction()
.show(fm.findFragmentById(fragment))
.hide(fm.findFragmentById(activePage))
.commit();
Problem
I am new to android and i am using viewpager for the first time in my app and
i am suffering from very strange behavior in my app that is i am using viewpager with three fragments ( TrackFragment , AlbumFragment , ArtistFragment ) and when i swip page from TrackFragment to AlbumFragment and again come back to TrackFragment it becomes blank (but it was not at first time when i am at TrackFragment initially) and same thing happened when i jump to ArtistFragment or any other fragments from the tab layout (its become blank).
And in case when i am going to ArtistFragment from TrackFragment via AlbumFragments by swiping the pages it works correctly (that is contents are shown in pages).
Please suggest me a method to overcome the above problem or any other method to implement same thing.
Here is my code....
MainActivity
public class MainActivity extends AppCompatActivity {
private String[] mPlanetTitles={"Tracks","Album","Artist"};
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
SharedPreferences sharedPreferences;
Fragment [] fragments = {new TracksFragment(),new AlbumFragment(), new ArtistFragment()};
PagerAdapter pagerAdapter;
ViewPager viewPager;
public static ImageView im;
int pos= -1 ;
public static Context context;
MusicService musicService;
boolean mBound;
TabLayout tabLayout ;
public static Uri currentsonguri;
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = getSharedPreferences("lastplayed",Context.MODE_PRIVATE);
Intent i = new Intent(MainActivity.this,MusicService.class);
startService(i);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerList.setAdapter(new NavigationDrawerAdapter(this));
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(position == 3)
{
Intent i = new Intent(MainActivity.this,PlaylistActivity.class);
startActivity(i);
}
if(position == 4)
{
Intent intent = new Intent();
intent.setAction("android.media.action.DISPLAY_AUDIO_EFFECT_CONTROL_PANEL");
if((intent.resolveActivity(getPackageManager()) != null)) {
startActivity(intent);
} else {
// No equalizer found :(
Toast.makeText(getBaseContext(),"No Equaliser Found",Toast.LENGTH_LONG).show();
}
}
}
});
tabLayout = (TabLayout) findViewById(R.id.tablayout);
viewPager = (ViewPager) findViewById(R.id.viewPager);
tabLayout.setTabTextColors(Color.DKGRAY,Color.WHITE);
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
context = getBaseContext();
pagerAdapter = new myfragment(getSupportFragmentManager());
im = (ImageView) findViewById(R.id.currentsong);
viewPager.setPageTransformer(true, new ZoomOutPageTransformer());
viewPager.setAdapter(pagerAdapter);
tabLayout.setupWithViewPager(viewPager,true);
SharedPreferences.Editor editor= sharedPreferences.edit();
if(sharedPreferences.getInt("count",0)==0)
{
editor.putInt("count",1);
}
else
{
int c= sharedPreferences.getInt("count",0);
Log.d("Uses count",c+"");
editor.putInt("count",c++);
editor.apply();
}
if(!sharedPreferences.getString("uri","").equals(""))
{
String s = sharedPreferences.getString("uri","");
Uri u = Uri.parse(s);
currentsonguri = u;
MediaMetadataRetriever data=new MediaMetadataRetriever();
data.setDataSource(getBaseContext(),u);
try {
byte[] b = data.getEmbeddedPicture();
Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
bitmap = getRoundedCornerBitmap(bitmap);
im.setImageBitmap(bitmap);
}
catch (Exception e)
{
e.printStackTrace();
}
try {
musicService.setsongbyuri(u,getBaseContext());
musicService.setMediaPlayer();
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
}
editor.apply();
im.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, MusicPlayerActivity.class);
intent.setData(currentsonguri);
intent.putExtra("flag",1);
startActivity(intent);
}
});
final Uri r= getIntent().getData();
if(r!=null) {
currentsonguri = r;
Intent intent = new Intent(MainActivity.this, MusicPlayerActivity.class);
intent.setData(r);
intent.putExtra("flag",0);
startActivity(intent);
}
}
public class myfragment extends FragmentPagerAdapter {
myfragment(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return fragments[position];
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
String s = "non";
switch (position)
{
case 0 : s= "Tracks" ;
break;
case 1: s= "Albums" ;
break;
case 2: s= "Artist" ;
break;
}
return s;
}
}
public void setview(byte [] b, int position,Uri uri)
{
currentsonguri = uri;
Log.d("position in set view",""+position);
Log.d("fail","i am here");
if(im!=null)
{
if(b!=null)
{
Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
bitmap = getRoundedCornerBitmap(bitmap);
im.setImageBitmap(bitmap);
}
else {
songDetailloader loader = new songDetailloader(context);
String s = loader.albumartwithalbum(loader.songalbum(position));
Log.d("fail","fail to set small image");
if (s != null) {
im.setImageBitmap(BitmapFactory.decodeFile(s));
Log.d("fail","nowsetting set small image");
} else {
im.setImageResource(R.drawable.default_track_light);
Log.d("ic","ic_launcher setted");
}
}
}
else {
Log.d(""," im is null");
}
}
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = 100;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
private ServiceConnection serviceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicService.LocalBinder binder = (MusicService.LocalBinder) service;
musicService = binder.getService();
mBound =true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
mBound =false;
}
};
#Override
protected void onDestroy() {
super.onDestroy();
Log.d("MainActivity","Get distoryed");
}
#Override
protected void onResume() {
super.onResume();
Intent i = new Intent(this,MusicService.class);
bindService(i, serviceConnection, Context.BIND_AUTO_CREATE);
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
unbindService(serviceConnection);
}}
Tracks Fragment
public class TracksFragment extends Fragment {
songDetailloader loader = new songDetailloader();
ArrayList<Songs> give = new ArrayList<>();
public int pos = -1;
MediaPlayer mp ;
MusicService musicService;
boolean mBound;
ImageView search;
ListViewAdapter listViewAdapter;
RelativeLayout editreltive;
ListView listView;
EditText editText;
TextView ch;
private Cursor cursor ;
int albumindex,dataindex,titleindex,durationindex,artistindex;
private final static String[] columns ={MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.DURATION, MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.IS_MUSIC,MediaStore.Audio.Media.IS_RINGTONE,MediaStore.Audio.Media.ARTIST,MediaStore.Audio.Media.SIZE ,MediaStore.Audio.Media._ID};
private final String where = "is_music AND duration > 10000 AND _size <> '0' ";
private final String orderBy = MediaStore.Audio.Media.TITLE;
public TracksFragment() {
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("fragment created","created");
setRetainInstance(true);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable final ViewGroup container, #Nullable Bundle savedInstanceState)
{
View v =inflater.inflate(R.layout.listviewofsongs,container,false);
listView = (ListView) v.findViewById(R.id.listView);
allsongs();
intlistview();
new Thread(new Runnable() {
#Override
public void run() {
Intent i = new Intent(getActivity(),MusicService.class);
getActivity().bindService(i, serviceConnection, Context.BIND_AUTO_CREATE);
}
}).start();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Log.d("Uri of ",""+give.get(position).getSonguri());
musicService.setplaylist(give,give.get(position).getPosition());
musicService.setMediaPlayer();
view.setSelected(true);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
View v =LayoutInflater.from(getContext()).inflate(R.layout.select_dialog_layout,null);
builder.setView(v);
builder.setTitle(give.get(position).gettitle()+"\n "+give.get(position).getalbum());
builder.create();
final AlertDialog d=builder.show();
//seting click listner.....
TextView play = (TextView) v.findViewById(R.id.dialogplay);
TextView playnext = (TextView) v.findViewById(R.id.dialogplaynext);
TextView queue = (TextView) v.findViewById(R.id.dialogqueue);
TextView fav = (TextView) v.findViewById(R.id.dialogaddtofav);
TextView album = (TextView) v.findViewById(R.id.dialogalbum);
TextView artist = (TextView) v.findViewById(R.id.dialogartist);
TextView playlist = (TextView) v.findViewById(R.id.dialogaddtoplaylsit);
TextView share = (TextView) v.findViewById(R.id.dialogshare);
TextView delete = (TextView) v.findViewById(R.id.dialogdelete);
TextView properties = (TextView) v.findViewById(R.id.dialogproperties);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
File f= new File(give.get(position).getSonguri().getLastPathSegment());
Log.d("LENGTH IS",""+f.length());
musicService.setplaylist(give,position);
musicService.setMediaPlayer();
d.dismiss();
}
});
playnext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
}
});
queue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
musicService.insertinqueue(give.get(position));
}
});
fav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
DataBaseClass db = new DataBaseClass(getContext());
int i=db.insetintoliked(give.get(position));
if(i==1)
{
Toast.makeText(getContext(),"Added to Favorites",Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(getContext(),"Already in Favorites",Toast.LENGTH_SHORT).show();
}
});
album.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
Intent i = new Intent( getActivity() , AlbumDetail.class);
Bundle b= new Bundle();
b.putCharSequence("album",give.get(position).getalbum());
i.putExtras(b);
startActivity(i);
}
});
artist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getActivity(),ArtistActivity.class);
i.putExtra("artist",give.get(position).getartist());
startActivity(i);
d.dismiss();
}
});
playlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
}
});
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder b = new AlertDialog.Builder(getContext());
b.setMessage("Audio '"+give.get(position).gettitle()+"' will be deleted permanently !");
b.setTitle("Delete ?");
b.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
d.dismiss();
}
});
b.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
File f= new File(give.get(position).getSonguri().getPath());
boolean b = f.delete();
Log.d("Is file exist",f.exists()+"");
Log.d("File Lenth",""+f.length());
Log.d("Return value",""+b);
loader.set(getContext());
loader.deleteSong(getContext(),give.get(position).getPosition());
give.remove(position); // give is Arraylist of Songs(datatype);
listViewAdapter.notifyDataSetChanged();
if(b)
{
Toast.makeText(getContext(),"Deleted",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getContext(),"Fail to Delete",Toast.LENGTH_SHORT).show();
}
}
});
b.create().show();
d.dismiss();
}
});
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("audio/*");
share.putExtra(Intent.EXTRA_STREAM, give.get(position).getSonguri());
startActivity(Intent.createChooser(share, "Share Audio"));
}
});
properties.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder b = new AlertDialog.Builder(getContext());
File f= new File(give.get(position).getSonguri().getPath());
long size = (f.length())/1024;
long mb= size/1024;
long kb= size%1024;
b.setMessage("Size:"+"\n"+"Size "+mb+"."+kb+" MB\n"+"Path:"+f.getAbsolutePath()+"\n");
b.setTitle(f.getName());
b.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
b.create().show();
d.dismiss();
}
});
return true;
}
});
return v;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.d("fragment","instance saved");
}
#Override
public void onViewStateRestored(#Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
Log.d("Fragment","Instance Restored");
}
public void intlistview()
{
listViewAdapter = new ListViewAdapter(getContext(),give);
listView.setAdapter(listViewAdapter);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d("Fragment","Destroyed");
getActivity().unbindService(serviceConnection);
}
private ServiceConnection serviceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicService.LocalBinder binder = (MusicService.LocalBinder) service;
musicService = binder.getService();
mBound =true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
mBound =false;
}
};
public void allsongs()
{
cursor = getContext().getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, columns, where, null, orderBy);
dataindex = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
albumindex = cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM);
titleindex = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
durationindex = cursor.getColumnIndex(MediaStore.Audio.Media.DURATION);
artistindex = cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
cursor.moveToFirst();
for(int i=0;i<cursor.getCount();i++)
{
Songs song = new Songs();
song.setalbum(cursor.getString(albumindex));
song.settitle(cursor.getString(titleindex));
song.setSonguri(Uri.parse(cursor.getString(dataindex)));
song.setartist(cursor.getString(artistindex));
song.setDuration(Long.decode(cursor.getString(durationindex)));
song.setPosition(cursor.getPosition());
this.give.add(song);
cursor.moveToNext();
}
cursor.close();
}}
Album Fragment
public class AlbumFragment extends Fragment {
songDetailloader songDetailloader = new songDetailloader();
public AlbumFragment() {
super();
}
GridView gridView;
AlbumAdapter a;
private static ArrayList<Bitmap> image = new ArrayList<>();
LinearLayout linearLayout;
Cursor cursor ;
ImageView album;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View v =inflater.inflate(R.layout.albumgridview,container,false);
gridView = (GridView) v.findViewById(R.id.gridview);
album = (ImageView) v.findViewById(R.id.albumart);
/*Animation animation = AnimationUtils.loadAnimation(getContext(),R.anim.grid_layout_anim);
GridLayoutAnimationController controller = new GridLayoutAnimationController(animation,0.2f,0.2f);
gridView.setLayoutAnimation(controller);*/
final TextView albumname = (TextView) v.findViewById(R.id.albumname);
cursor = songDetailloader.getAlbumCursor(getContext());
if(image.size()==0)
new getbitmaps().execute();
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String s = songDetailloader.albumart(position);
Intent i = new Intent( getActivity() , AlbumDetail.class);
Bundle b= new Bundle();
b.putCharSequence("album",songDetailloader.album(position));
i.putExtras(b);
startActivity(i);
}
});
return v;
}
public class getbitmaps extends AsyncTask<Void,Void,Void>
{
Bitmap b;
public getbitmaps() {
super();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
for(int i=0;i<cursor.getCount();i++)
{
cursor.moveToPosition(i);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize= 2;
b=BitmapFactory.decodeFile(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART)),options);
if(b==null)
{
b=BitmapFactory.decodeFile(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART)));
}
image.add(b);
}
cursor.close();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
a =new AlbumAdapter(getContext(),image);
a.setCursor();
gridView.setAdapter(a);
new Thread(new Runnable() {
#Override
public void run() {
songDetailloader.set(getContext());
}
}).start();
}
}}
Artist Fragment
public class ArtistFragment extends Fragment {
ListView listView ;
ArrayList<Artists> aa = new ArrayList<>();
final String[] columns3 = {MediaStore.Audio.Artists._ID, MediaStore.Audio.Artists.ARTIST,MediaStore.Audio.Artists.NUMBER_OF_ALBUMS,MediaStore.Audio.Artists.NUMBER_OF_TRACKS};
final static String orderBy3 = MediaStore.Audio.Albums.ARTIST;
public Cursor cursor3;
public ArtistFragment() {
super();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v= inflater.inflate(R.layout.listviewofsongs,container,false);
listView = (ListView) v.findViewById(R.id.listView);
new artist().execute();
return v;
}
public class artist extends AsyncTask<Void, Void ,Void>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
allartist();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
ArtistAdapter artistAdapter = new ArtistAdapter(getActivity().getBaseContext(),aa);
listView.setAdapter(artistAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i= new Intent(getActivity(), ArtistActivity.class);
i.putExtra("artist", aa.get(position).getArtistname());
i.putExtra("noofsongs",aa.get(position).getNofosongs());
startActivity(i);
}
});
}
}
#Override
public void setInitialSavedState(SavedState state) {
super.setInitialSavedState(state);
}
#Override
public void onViewStateRestored(#Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
}
#Override
public void onDestroy() {
super.onDestroy();
}
public void allartist()
{
cursor3 = getContext().getContentResolver().query(MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI, columns3, null, null, orderBy3);
cursor3.moveToFirst();
for(int i=0;i< cursor3.getCount() ;i++)
{
Artists art = new Artists();
art.setArtistname(cursor3.getString(cursor3.getColumnIndex(MediaStore.Audio.Artists.ARTIST)));
art.setNoalbums(Integer.parseInt(cursor3.getString(cursor3.getColumnIndex(MediaStore.Audio.Artists.NUMBER_OF_ALBUMS))));
art.setNofosongs(Integer.parseInt(cursor3.getString(cursor3.getColumnIndex(MediaStore.Audio.Artists.NUMBER_OF_TRACKS))));
this.aa.add(art);
cursor3.moveToNext();
}
cursor3.close();
}}
Maybe you can try to add this property to you viewpager, in the onCreate method of your MainActivity :
viewPager.setOffscreenPageLimit(fragments.size());
Update
Another thing you could try is:
In your myfragment override getItemPosition in this way:
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
And add this code in your onCreate of your MainActivity:
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
int previousState;
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
if (previousState == ViewPager.SCROLL_STATE_SETTLING && state == ViewPager.SCROLL_STATE_IDLE) {
pagerAdapter.notifyDataSetChanged();
}
previousState = state;
}
});
The aim of this code is not to be efficient, but to try to understand your problem.
Hope this can help you
I looked at the documentation of the arrayadapter, and the constructor says that I can either abstain from passing in elements, pass in an array of strings, or a List, which is required to be one of strings.
When I pass in an empty list, it causes a nullpointerexception when I try to call .clear from another activity.
When I pass in an array with values in it, it doesn't call that, but it throws an error because the clear operation isn't supported for array values.
How can I pass in a list with no predefined values and have it not cause an error? I can't use the array version, or no data (same error as empty list).
Note: I don't care how the values get put in, I just don't want any strings of characters in the adapters if I can avoid it.
In case it matters, here is how I am implementing the adapters (with the empty lists):
public class GroupTasksFragment extends Fragment {
public ArrayAdapter<String> adapter;
private Context context;
public GroupTasksFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_group_tasks, container, false);
ListView taskListView = (ListView) rootView.findViewById(R.id.tasksList);
List<String> list = new ArrayList<>(0);
adapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, list);
taskListView.setAdapter(adapter);
return rootView;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
}
#Override
public void onDetach() {
super.onDetach();
}
}
The other fragment is thus:
public class GroupChatFragment extends Fragment{
public ArrayAdapter<String> adapter;
private Context context;
public GroupChatFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_group_chat, container, false);
ListView chatListView = (ListView) rootView.findViewById(R.id.chatList);
List<String> list = new ArrayList<>();
adapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, list);
chatListView.setAdapter(adapter);
return rootView;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
}
#Override
public void onDetach() {
super.onDetach();
}
}
This is the adapter throwing the exception.
Stack Trace:
12-29 22:15:45.641 23253-23253/nuffsaidm8.me.assignme E/AndroidRuntime: FATAL EXCEPTION: main
Process: nuffsaidm8.me.assignme, PID: 23253
java.lang.NullPointerException: Attempt to read from field 'android.widget.ArrayAdapter nuffsaidm8.me.assignme.frags.GroupChatFragment.adapter' on a null object reference
at nuffsaidm8.me.assignme.activities.GroupContentActivity$1$1.onResponse(GroupContentActivity.java:98)
at nuffsaidm8.me.assignme.activities.GroupContentActivity$1$1.onResponse(GroupContentActivity.java:68)
at com.pubnub.api.endpoints.Endpoint$1.onResponse(Endpoint.java:194)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Comes from this line:
chatFrag.adapter.clear();
In this class:
public class GroupContentActivity extends AppCompatActivity {
private GroupChatFragment chatFrag;
private GroupTasksFragment taskFrag;
private PubNub connection;
private String groupName;
private String nickName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_group_content);
FragmentTabHost tabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
tabHost.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);
tabHost.addTab(tabHost.newTabSpec("tasks").setIndicator("Tasks"),
GroupTasksFragment.class, null);
tabHost.addTab(tabHost.newTabSpec("chat")
.setIndicator("Chat"), GroupChatFragment.class, null);
groupName = getIntent().getStringExtra("groupName");
nickName = getIntent().getStringExtra("nickName");
PNConfiguration config = new PNConfiguration();
config.setPublishKey("pub-c-d8414fbe-6925-4511-9bda-8fa682138fb1");
config.setSubscribeKey("sub-c-50acdc56-c1a3-11e6-b07a-0619f8945a4f");
connection = new PubNub(config);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
chatFrag = (GroupChatFragment) getSupportFragmentManager().findFragmentByTag("chat");
taskFrag = (GroupTasksFragment) getSupportFragmentManager().findFragmentByTag("tasks");
connection.history()
.channel(groupName)
.count(50)
.async(new PNCallback<PNHistoryResult>() {
#Override
public void onResponse(PNHistoryResult result, PNStatus status) {
for (PNHistoryItemResult item : result.getMessages()) {
String[] sForm = item.getEntry().getAsString().split(">>>>");
String m = "";
if (sForm.length > 2) {
for (int x = 1; x < sForm.length; x++) {
m += sForm[x];
}
} else {
m = sForm[1];
}
switch (sForm[0]) {
case "chat":
chatFrag.adapter.add(m);
break;
case "addTask":
if (taskFrag.adapter.getPosition(m) < 0) {
taskFrag.adapter.add(m);
}
break;
case "deleteTask":
if (taskFrag.adapter.getPosition(m) >= 0) {
taskFrag.adapter.remove(m);
}
break;
case "groupCreated":
taskFrag.adapter.clear();
chatFrag.adapter.clear();
break;
}
}
}
});
connection.addListener(new SubscribeCallback() {
#Override
public void status(PubNub pubnub, PNStatus status) {
if (status.getCategory() == PNStatusCategory.PNUnexpectedDisconnectCategory) {
Toast.makeText(getApplicationContext(), "You were disconnected!", Toast.LENGTH_SHORT).show();
} else if (status.getCategory() == PNStatusCategory.PNConnectedCategory) {
if (status.getCategory() == PNStatusCategory.PNConnectedCategory) {
pubnub.publish().channel(groupName).message("chat>>>><ADMIN> User '" + nickName + "' Connected").async(new PNCallback<PNPublishResult>() {
#Override
public void onResponse(PNPublishResult result, PNStatus status) {
}
});
}
} else if (status.getCategory() == PNStatusCategory.PNReconnectedCategory) {
Toast.makeText(getApplicationContext(), "You were reconnected!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void message(PubNub pubnub, PNMessageResult message) {
String[] sForm = message.getMessage().getAsString().split(">>>>");
String m = "";
if (sForm.length > 2) {
for (int x = 1; x < sForm.length; x++) {
m += sForm[x];
}
} else {
m = sForm[1];
}
switch (sForm[0]) {
case "chat":
chatFrag.adapter.add(m);
break;
case "addTask":
taskFrag.adapter.add(m);
connection.publish().channel(groupName).message("chat>>>><ADMIN> Task '" + m + "' added.").async(new PNCallback<PNPublishResult>() {
#Override
public void onResponse(PNPublishResult pnPublishResult, PNStatus pnStatus) {
}
});
break;
case "deleteTask":
taskFrag.adapter.remove(m);
connection.publish().channel(groupName).message("chat>>>><ADMIN> Task '" + m + "' deleted.").async(new PNCallback<PNPublishResult>() {
#Override
public void onResponse(PNPublishResult pnPublishResult, PNStatus pnStatus) {
}
});
break;
}
}
#Override
public void presence(PubNub pubnub, PNPresenceEventResult presence) {
}
});
connection.subscribe().channels(java.util.Collections.singletonList(groupName)).execute();
}
}, 100);
}
public void goHome(View v) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
public void sendMessage(View v) {
String message = ((EditText) findViewById(R.id.messageToSend)).getText().toString();
connection.publish().channel(groupName).message("chat>>>><" + nickName + "> " + message).async(new PNCallback<PNPublishResult>() {
#Override
public void onResponse(PNPublishResult pnPublishResult, PNStatus pnStatus) {
}
});
}
public void deleteTask(View v) {
final EditText input = new EditText(getApplicationContext());
input.setTextColor(Color.BLACK);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
new AlertDialog.Builder(this)
.setTitle("Delete Task")
.setMessage("What task would you like to delete?")
.setView(input)
.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (taskFrag.adapter.getPosition(input.getText().toString()) < 0) {
connection.publish().channel(groupName).message("deleteTask>>>>" + input.getText().toString()).async(new PNCallback<PNPublishResult>() {
#Override
public void onResponse(PNPublishResult pnPublishResult, PNStatus pnStatus) {
}
});
dialog.cancel();
} else {
Toast.makeText(getApplicationContext(), "This task doesn't exist", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
}
})
.setNegativeButton(R.string.CANCEL, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.show();
}
public void addTask(View v) {
final EditText input = new EditText(getApplicationContext());
input.setTextColor(Color.BLACK);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
new AlertDialog.Builder(this)
.setTitle("Create New Task")
.setView(input)
.setMessage("What task would you like to create?")
.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (taskFrag.adapter.getPosition(input.getText().toString()) >= 0) {
connection.publish().channel(groupName).message("addTask>>>>" + input.getText().toString()).async(new PNCallback<PNPublishResult>() {
#Override
public void onResponse(PNPublishResult pnPublishResult, PNStatus pnStatus) {
}
});
dialog.cancel();
} else {
Toast.makeText(getApplicationContext(), "This task already exists", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
}
})
.setNegativeButton(R.string.CANCEL, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.show();
}
}
Try this:
Initialise your list above.
Your first fragment will look like this:
public class GroupTasksFragment extends Fragment {
public ArrayAdapter<String> adapter;
private Context context;
List<String> list = new ArrayList<>();
public GroupTasksFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_group_tasks, container, false);
ListView taskListView = (ListView) rootView.findViewById(R.id.tasksList);
adapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, list);
taskListView.setAdapter(adapter);
return rootView;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
}
#Override
public void onDetach() {
super.onDetach();
}
}
Your second fragment will look like this:
public class GroupChatFragment extends Fragment{
public ArrayAdapter<String> adapter;
private Context context;
List<String> list = new ArrayList<>();
public GroupChatFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_group_chat, container, false);
ListView chatListView = (ListView) rootView.findViewById(R.id.chatList);
adapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, list);
chatListView.setAdapter(adapter);
return rootView;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
}
#Override
public void onDetach() {
super.onDetach();
}
}
Hello am trying to delete an item from my listview am able to delete item from my db but my adapter is not getting updated I have attached the code below`
public class SavedPolygonFragment extends android.support.v4.app.Fragment implements RefreshListener {
private static String LOG_TAG = SavedPolygonFragment.class.getName();
private String message = "No message";
private ListView shapeList;
private TextView textView;
private Button startMainBtn;
private SavedShapeAdapter savedShapeAdapter;
private long shapeId;
private float scaleFactor;
private List<Shape> savedShapes = new ArrayList<>();
private StartDrawingListener startListener;
private DeleteShapesDialog deleteDialog;
public SavedPolygonFragment() {
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
startListener = (StartDrawingListener) activity;
}
#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_one, container, false);
savedShapes = getArguments().getParcelableArrayList("shapes");
AssetLog.verbose(LOG_TAG, "savedshapes.size " + savedShapes.size());
shapeList = (ListView) view.findViewById(R.id.shapeList);
textView = (TextView) view.findViewById(R.id.polygonTitle);
startMainBtn = (Button) view.findViewById(R.id.gotoMain);
startMainBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startListener.startMainReceived();
}
});
if (!savedShapes.isEmpty() && !savedShapes.equals(null) && savedShapes.size() != 0) {
textView.setText("Polygons");
shapeList.setVisibility(View.VISIBLE);
startMainBtn.setVisibility(View.GONE);
if (savedShapeAdapter != null) {
savedShapeAdapter.notifyDataSetChanged();
} else {
savedShapeAdapter = new SavedShapeAdapter(savedShapes, getActivity());
shapeList.setAdapter(savedShapeAdapter);
shapeList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
MainActivity_.intent(getActivity())
.savedProjectId(ProjectShapesActivity.projId)
.scaleFactor(ProjectShapesActivity.scaleFactor)
.shapeId(((Shape) view.getTag()).getShapeId())
.lineId(-1)
.pointId(-1)
.start();
}
});
}
}
else{
shapeList.setVisibility(View.GONE);
startMainBtn.setVisibility(View.VISIBLE);
textView.setText("Sorry no shapes are saved");
}
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
registerForContextMenu(shapeList);
}
#Override
public void onRefreshPressed() {
}
#Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, view, menuInfo);
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
shapeId = info.id;
menu.add(Menu.NONE, R.id.deleteShapes, Menu.NONE, "Delete");
menu.add(Menu.NONE, R.id.editShapes, Menu.NONE, "Edit");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.refresh:
return false;
case R.id.deleteShapes:
if(deleteDialog == null){
Bundle bundle = new Bundle();
bundle.putString("SHAPE", "SHAPE");
bundle.putLong("shapeId", shapeId);
deleteDialog = new DeleteShapesDialog();
deleteDialog.setArguments(bundle);
deleteDialog.show(getActivity().getFragmentManager().beginTransaction(), "showDeleteDialog");
}
return true;
case R.id.editShapes:
return true;
}
return super.onContextItemSelected(item);
}
public void onDataChanged(long shapeid) {
Shape shape;
for (int i = 0; i <savedShapes.size() ; i++) {
shape = savedShapes.get(i);
if(shape.getShapeId() == shapeid){
savedShapes.remove(i);
shapeList.removeViewAt(i);
shapeList.invalidate();
savedShapeAdapter.notifyDataSetChanged();
break;
}
}
}
}
`
Now when user selects yes from deleteDialog i wrote a callback to my activity and in the corresponding methods this is what I do
SavedPolygonFragment polygonFragment = new SavedPolygonFragment();
polygonFragment.onDataChanged(shapeId);
Can somebody show me whats wrong
/////EDIT 1
public void onDataChanged(long shapeid) {
savedShapeAdapter.removeItemById(shapeid);
}
and my adapter
public void removeItemById(long itemId){
for(int i =0; i< shapeList.size() ; i++){
if(shapeList.get(i).getShapeId() == itemId){
shapeList.remove(i);
}
}
notifyDataSetChanged();
}
am able to delete item from my db but my adapter is not getting
updated
Problem is caused by :
savedShapes.remove(i);
line.
Currently removing item from ArrayList which is in SavedPolygonFragment class, not from ArrayList which is used by Adapter to fill ListView.
Using current approach try this way will work by setting new Adapter every time:
if(shape.getShapeId() == shapeid){
savedShapes.remove(i);
savedShapeAdapter = new SavedShapeAdapter(savedShapes, getActivity());
shapeList.setAdapter(savedShapeAdapter);
savedShapeAdapter.notifyDataSetChanged();
break;
}
But this is not optimize solution to create and set new object of Adapter every-time when want to update ListView.
Right approach is create a method in SavedShapeAdapter class for removing item for ArrayList which is used by Adapter and then call it inside onDataChanged method:
public void deleteRowItem(int index){
this.savedShapes.remove(index);
this..notifyDataSetChanged();
}
Now call deleteRowItem when want to delete row item from ListView :
if(shape.getShapeId() == shapeid){
savedShapeAdapter.deleteRowItem(i);
break;
}