In my application I have dynamic vertical boom menu. However menu is being opened only if user clicks boom menu button and I want to show it immidiately after activity is created. I searched for solution this this issue and found few but none of them worked. Heres my onCreate method :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_new_pik, container, false);
ButterKnife.bind(this,view);
EventBus.getDefault().register(this);
Category category1 = new Category();
Category category2 = new Category();
Category category3 = new Category();
Category category4 = new Category();
Category category5 = new Category();
categories = new ArrayList<>();
categories.add(category1);
categories.add(category2);
categories.add(category3);
categories.add(category4);
categories.add(category5);
adapter = new CategoryAdapter(categories,getActivity().getApplicationContext());
mScrollView.setAdapter(adapter);
mScrollView.scrollToPosition(2);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
mScrollView.findViewHolderForAdapterPosition(2).itemView.callOnClick();
}
},1);
mScrollView.setItemTransformer(new ScaleTransformer.Builder()
.setMaxScale(1.05f)
.setMinScale(0.8f)
.setPivotX(Pivot.X.CENTER) // CENTER is a default one
.setPivotY(Pivot.Y.BOTTOM) // CENTER is a default one
.build();
return view;
}
This is my onBindViewHolder :
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
Category category = channelList.get(position);
holder.menuButton.clearBuilders();
holder.menuButton.setButtonEnum(ButtonEnum.SimpleCircle);
holder.menuButton.setPiecePlaceEnum(PiecePlaceEnum.DOT_6_3);
holder.menuButton.setButtonPlaceEnum(ButtonPlaceEnum.SC_6_3);
holder.menuButton.setDotRadius(0);
holder.menuButton.setBackground(mContext.getResources().getDrawable(R.drawable.category_empty_icon));
holder.menuButton.setNormalColor(mContext.getResources().getColor(R.color.transparent));
holder.menuButton.setShadowEffect(false);
for (int i = 0; i < holder.menuButton.getButtonPlaceEnum().buttonNumber(); i++) {
holder.menuButton.addBuilder(new SimpleCircleButton.Builder()
.normalColor(mContext.getResources().getColor(R.color.white))
.normalImageRes(R.drawable.logo_splash_screen)
.listener(new OnBMClickListener() {
#Override
public void onBoomButtonClick(int index) {
mContext.startActivity(new Intent(mContext.getApplicationContext(), AddPikActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
}
}));
}
}
Any help please ?
Related
I have an app which displays the Matchday of some soccer competitions depending date of the match. I am using a spinner to re-create the adapter of my RecyclerView depending on the User selection with some dummyData(). But sometimes while the RecyclerView is first initialized or recycled it displays literally the format of my .xml.
I managed to reduce the level of visual glitch by adding a custom animation on the Adapter but still sometimes it just happens, like 10% of the time I change Matchday.
format_home.xml
This is the placeholder I created to design this format.
Gif showing problem:
HomeFragment.java
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
mRecyclerView = view.findViewById(R.id.home_recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
mSpinner = view.findViewById(R.id.spinner_home);
List<String> matchDay = new ArrayList<>();
for (int i = 0; i < 20; i++){
matchDay.add("Matchday " + (i + 1));
}
HomeSpinnerAdapter dataAdapter = new HomeSpinnerAdapter(getContext(), R.layout.format_home_spinner, matchDay);
mSpinner.setAdapter(dataAdapter);
mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
mHomeItems = new ArrayList<>();
mDisposable.add(Observable.fromArray(mHomeItems)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(homeItems -> {
Map<String, List<Matchday>> hashMap = toMap(dummyData());
// Map Key
for (String date : hashMap.keySet()) {
Header header = new Header(date);
homeItems.add(header);
for (Matchday matchday : hashMap.get(date)) {
MatchItem matchItem = new MatchItem(matchday);
homeItems.add(matchItem);
}
}
mAdapter = new HomeAdapter(homeItems, getActivity(), mTeamViewModel);
mRecyclerView.setAdapter(mAdapter);
}));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
return view;
}
// Map Value List<T>
private Map<String,List<Matchday>> toMap(List<Matchday> matchdays) {
Map<String, List<Matchday>> map = new TreeMap<>();
for (Matchday matchday : matchdays){
List<Matchday> value = map.get(matchday.getDate());
if (value == null) {
value = new ArrayList<>();
map.put(matchday.getDate(), value);
}
value.add(matchday);
}
return map;
}
public List<Matchday> dummyData(){
mMatchdayList = new ArrayList<>();
Random random = new Random();
for (int i = 0; i < 20; i ++){
mMatchdayList.add(new Matchday((i+1), buildRandomDateInCurrentMonth(), 1, random.nextInt(36), 0, 0, random.nextInt(36)));
}
return mMatchdayList;
}
If you have any feedback or need any other activity, let me know! TY
Thanks to #jantursky and some deep digging in the web I came across this series of articles and managed to identify that my RecyclerView was recreating all views in the absence of setStableIds(true) because in recyclers Scrap lists are the first place where the RecyclerView looks when searching for a ViewHolder.
So to resolve the problem:
Created an interface to retrieve List IDS.
Created a refreshAdapter() method in the Adapter.
Initialized and instantiate the Adapter outside the ` mSpinner.setOnItemSelectedListener() with setHasStableIds(true).
Inside the mSpinner.setOnItemSelectedListenercall refreshAdapter()
I have a recycler view which is showing fruit list. Each item has a buy button.When I click the buy button of an item in the list, the details of that item should pass to the order list page through intent and should be displayed in recycler view.I have used ArrayList for passing the data.Then when I click the continue button it will come back to fruit list page and I want to buy another fruit.But my issue is, when I click the buy button of another item, only that particular item is displayed in the order list.the previous item is missing and the recycler view is showing only one row.(ie, latest data).Can any one please help?
this is the adapter code:
public ViewHolder(View view) {
super(view);
fruitname = (TextView) view.findViewById(R.id.category_name);
rate = (TextView) view.finenter code heredViewById(R.id.rate);
buy = (TextView) view.findViewById(R.id.buy);
mProfilepic = (ImageView) view.findViewById(R.id.profilepic);
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View rootView = LayoutInflater.
from(mContext).inflate(R.layout.list_item, null, false);
RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
rootView.setLayoutParams(lp);
return new ViewHolder(rootView);
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, final int position) {
item = mListItem.get(position);
final ViewHolder mViewHolder = (ViewHolder) viewHolder;
mViewHolder.fruitname.setText(item.get_name());
mViewHolder.rate.setText(item.get_email()+"/kg");
}
mViewHolder.buy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
item1.set_contact(mListItem.get(position).get_designation());
item1.set_bank_fee(mListItem.get(position).get_name());
item1.set_category(mListItem.get(position).get_email());
dataItem.add(item1);
Intent intent = new Intent(mContext,OrderListActivity.class);
intent.putExtra("arraylist",dataItem);
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return mListItem.size();
}
note:I have used notifyDataSetChanged.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.order_list);
mrecyclerview = (RecyclerView)findViewById(R.id.fruits_recycler);
mrecyclerview.setLayoutManager(new
LinearLayoutManager(getApplicationContext()));
dataItem =
(ArrayList<ListItem>)getIntent().getSerializableExtra("arraylist");
mOrderAdapter = new OrderAdapter(OrderListActivity.this,dataItem);
mrecyclerview.setAdapter(mOrderAdapter);
mOrderAdapter.notifyDataSetChanged();
}
}
Try this .
Intent intent = new Intent(mContext,OrderListActivity.class);
// edited here
intent.putParcelableArrayListExtra("arraylist", productList);
mContext.startActivity(intent);
And next Activity .
ArrayList<ListItem>) dataItem = getIntent().getParcelableArrayListExtra("arraylist");
if (dataItem != null && dataItem.size() > 0) {
mOrderAdapter = new OrderAdapter(OrderListActivity.this, dataItem);
mrecyclerview.setAdapter(mOrderAdapter);
// remove this
// mOrderAdapter.notifyDataSetChanged();
}
I have four fragments in a tab layout. In one of the fragments, I am displaying 10 notes in a listview. In addition to that, I am giving the user the option to add new notes using a dialog box. So, on adding a new note, the listview gets refreshed to show the new note as well but when I switch to another tab and then get back to my original tab, the new note is not displayed in the listview. How to solve this problem?
This is my java code:
public class NoteFragment extends Fragment {
ListView lv_notes;
Button btn_newNote;
ArrayList<NotesModel> notesModelArrayList;
private static NotesAdapter notesAdapter;
NotesModel newNote;
public NoteFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_note, container, false);
lv_notes = (ListView)rootView.findViewById(R.id.lv_notes);
btn_newNote = (Button)rootView.findViewById(R.id.btn_newNote);
notesModelArrayList = new ArrayList<>();
for (int i = 1; i <= 10; i++){
notesModelArrayList.add(new NotesModel("Note " + i,"24/05/2017"));
}
notesAdapter = new NotesAdapter(notesModelArrayList, getContext());
lv_notes.setAdapter(notesAdapter);
btn_newNote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LayoutInflater newNoteInflater = LayoutInflater.from(getContext());
View newNoteView = newNoteInflater.inflate(R.layout.noteprompt,null);
final AlertDialog.Builder noteDialogBuilder = new AlertDialog.Builder(getContext());
noteDialogBuilder.setView(newNoteView);
final EditText et_newNote = (EditText)newNoteView.findViewById(R.id.et_newNote);
noteDialogBuilder.setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
newNote = new NotesModel(et_newNote.getText().toString(),LogFragment.day_d + "/" + (LogFragment.month_d + 1) + "/" + LogFragment.year_d);
notesModelArrayList.add(newNote);
notesAdapter = new NotesAdapter(notesModelArrayList, getContext());
lv_notes.setAdapter(notesAdapter);
}
}).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog newNoteDialog = noteDialogBuilder.create();
newNoteDialog.show();
}
});
return rootView;
}
}
Your problem is caused by the fragment lifecycle. In case that it is destroyed, the new instance of the fragment will not keep the updated list, but the original one. To fix this, you have to save the array:
Save the data when fragment is about to be destroyed:
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList("notesList", notesModelArrayList);
}
And retrieve/create the data when fragment is created:
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
notesModelArrayList = savedInstanceState.getParcelableArrayList("notesList");
} else {
for (int i = 1; i <= 10; i++){
notesModelArrayList.add(new NotesModel("Note " + i,"24/05/2017"));
}
}
}
Beside this, I have 2 things to mention: you should implement Parcelable in the NotesModel class to be able to save them and, this will only work if you don't close the app. If you want a persistent solution, please consider using SharedPreferences.
EDIT - forgot to mention that you should remove the following lines from onCreateView:
notesModelArrayList = new ArrayList<>();
for (int i = 1; i <= 10; i++){
notesModelArrayList.add(new NotesModel("Note " + i,"24/05/2017"));
}
Instead of these 2 lines
notesAdapter = new NotesAdapter(notesModelArrayList, getContext());
lv_notes.setAdapter(notesAdapter);
try calling notesAdapter.notifyDatasetChanged(); inside setPositiveButton onclick.
I am using BackendLess backend service, but my prob is (i guess) more to android/java. So even if u are not familiar with BackendLess, i guess u can help, if u know of course :)
I have there a Fragment that calls and opens a DialogFragment with a ListView.
Using there an iterator to retrieve the data. It brings each column from the data table as an Array.
I set an onClickedItemListener that when item is clicked, it send the value to a TextView in the Fragment it was called from.
The data comes in the wrong order - didnt get how to do a sortBy, that connects to the bigger prob i have there -
There is a column there named "PropertyTypes". It holds 4 strings, which are coming out in the opposite order that i need. I want the "A" first, and get:
"D"
"C"
"B"
"A"
ok, so far no big deal, i guess can be sorted out with a sortBy that i just dont know how to do.
But... what happens is that it sends the wrong value to the TextView, meaning, for example, when i press "C" it set "A" on the TextView and so on, and, when i press the last one, in this case "A", the app is crashing...
What the hell is going on there?? :))
Here is the code -
The DialogFragment code:
public class OptionDialogFragment extends DialogFragment implements
AdapterView.OnItemClickListener {
ListView mylist;
TextView chosenProperty;
TextView presentListItem;
ArrayAdapter adapter;
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//mylist.addHeaderView(inflater.inflate(R.layout.option_dialog_header, null, false));
View view = inflater.inflate(R.layout.option_dialog_content, null, false);
mylist = (ListView) view.findViewById(R.id.list);
View headerView = inflater.inflate(R.layout.option_dialog_header, mylist, false);
headerView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dismiss();
}
});
mylist.addHeaderView(headerView);
View footerView = inflater.inflate(R.layout.option_dialog_footer, mylist, false);
footerView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dismiss();
}
});
mylist.addFooterView(footerView);
chosenProperty = (TextView) view.findViewById(R.id.chosenProperty);
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final ArrayList<String> propertyTypes = new ArrayList<String>();
final ArrayList<Integer> numOfRoomies = new ArrayList<Integer>();
Backendless.Data.of(DialogOptions.class).find(new AsyncCallback<BackendlessCollection<DialogOptions>>() {
#Override
public void handleResponse(final BackendlessCollection<DialogOptions> dialogOptions) {
final Iterator<DialogOptions> iterator = dialogOptions.getCurrentPage().iterator();
while (iterator.hasNext()) {
DialogOptions dialogOptionsObject = iterator.next();
propertyTypes.add(dialogOptionsObject.getPropertyTypes());
// numOfRoomies.add( dialogOptionsObject.getNumOfRoomies() );
}
adapter = new ArrayAdapter<String>(getActivity(), R.layout.dialog_option_list_item, R.id.presentListItem, propertyTypes);
mylist.setAdapter(adapter);
mylist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String chosenItem = propertyTypes.get(position);
Intent intent = new Intent();
intent.putExtra("chosenItem", chosenItem);
getTargetFragment().onActivityResult(
getTargetRequestCode(), Activity.RESULT_OK, intent);
dismiss();
}
});
}
#Override
public void handleFault(BackendlessFault fault) {
// TODO: make sure to log the exception, just in case
}
});
}
}
This is the Relevant code in the Fragment that calls the DialogFragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.find_a_place, container, false);
chosenProperty = (TextView) view.findViewById(R.id.chosenProperty);
return view;
}
#Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
final LinearLayout propertTypes = (LinearLayout)view.findViewById(R.id.propertyTypes);
propertTypes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(getActivity(), "OptionDialog");
}
});
}
private void showDialog(FragmentActivity activity, String optionDialog) {
android.support.v4.app.FragmentManager manager = getFragmentManager();
DialogFragment dialog = new OptionDialogFragment();
dialog.setTargetFragment(this, 0);
dialog.show(manager, "OptionDialog");
dialog.setCancelable(true);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case 0:
if (resultCode == Activity.RESULT_OK) {
if(data!=null){
// set value to your TextView
chosenProperty.setText(data.getStringExtra("chosenItem"));
}
}
break;
}
}
Thanks a lot in advance for any answer!!
Reference :-
https://backendless.com/feature-47-loading-data-objects-from-server-with-sorting/
To Sort while retrieving Object use :-
QueryOptions queryOptions = new QueryOptions();
queryOptions.addSortByOption( "created ASC" );
dataQuery.setQueryOptions( queryOptions );
Use Query as below:-
// fetch restaurants
Backendless.Data.of( Restaurant.class ).find( dataQuery, new AsyncCallback<BackendlessCollection<Restaurant>>(){
Right. I have an action that needs to call another activity. As I understand this, I need to use Intents to do so if I want to parse values to this activity.
However, my code fails and im a little lost as to why.
My main activity:
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
final ArrayList<menuItem> AMI = new ArrayList<menuItem>();
/*Menu item: String name, String menu ID*/
/*ToDo: Logic to fecth new menu structure from server*/
menuItem MI1 = new menuItem("menu item 1","1");
menuItem MI2 = new menuItem("menu item 2","2");
AMI.add(MI1);
AMI.add(MI2);
GridView gridview = (GridView) findViewById(R.id.GridView01);
gridview.setAdapter(new menuAdapter(this, AMI));
gridview.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
//Toast.makeText(Runner.this, AMI.get(position).getMenuID(), Toast.LENGTH_SHORT).show();
Intent myIntent = new Intent(v.getContext(), showMenu.class);
myIntent.putExtra("parentID", AMI.get(position).getMenuID());
startActivityForResult(myIntent, 0);
}
});
The "Toast" works just fine, however when I call the showMenu class it crashes.
The showMenu class looks as follows:
public class showMenu extends Activity{
public String menuParent = "";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.submenu);
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
menuParent = extras.getString("parentID");
}
/*ToDo: Logic to fecth new menu structure from server*/
final ArrayList<menuItem> AMI = new ArrayList<menuItem>();
menuItem MI1 = new menuItem("submenu 1","1");
menuItem MI2 = new menuItem("submenu 2","2");
AMI.add(MI1);
AMI.add(MI2);
GridView gridview = (GridView) findViewById(R.id.GridView01);
gridview.setAdapter(new subMenuAdapter(this, AMI));
}
public class subMenuAdapter extends BaseAdapter {
private ArrayList<menuItem> MIL = new ArrayList<menuItem>();
public static final int ACTIVITY_CREATE = 10;
public subMenuAdapter(Context c, ArrayList<menuItem> AMI) {
MIL = AMI;
}
public int getCount() {
return MIL.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v;
if (convertView == null) {
LayoutInflater li = getLayoutInflater();
v = (LinearLayout) li.inflate(R.layout.grid_item, null);
TextView tv = (TextView)v.findViewById(R.id.grid_text);
tv.setText(MIL.get(position).getMenuname());
} else {
v = convertView;
}
return v;
}
}
}
Any idea why it crashes?
I think you have to register your Intent in your AndroidManifest.xml
<activity
android:name="Package.Name.showMenu"
android:theme="#android:style/Theme.Light"></activity>
As both activities are from same application, there are some other ways as well to pass data between instead of intents. check the link below:
http://developer.android.com/resources/faq/framework.html#3
If you want to use only intents, can you please specify the error you are facing, so that someone can reply you correctly.
if you want to parse values to another activity,you must use startActivityForResult.This is called sub_activity.