I am trying to have a button within a Tab which is part of an activity for uploading images, when clicking the button inside one of the 2 Tabs presented in the activity ( Tab 1 pics, Tab 2 Vid ) the user could choose an image from the device.
My problem is implemneting the onClick Listener and onActivityResult which is not being used when placed after onClick, plus the #Override is being underlined as an error.
I guess i am not implementing the onClick the right way and not sure how to activate onActivityResult the proper way, i would appreciate any guidance;
MainActivty;
public class upload extends AppCompatActivity {
public String UserID;
private static final int REQUEST_SIGNUP = 0;
private DrawerLayout mDrawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.upload);
Firebase.setAndroidContext(this);
// Adding Toolbar to Main screen
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Setting ViewPager for each Tabs
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
// Set Tabs inside Toolbar
TabLayout tabs = (TabLayout) findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getSupportFragmentManager());
adapter.addFragment(new UploadPictures(), "Pictures");
adapter.addFragment(new UploadVideos(), "Videos");
viewPager.setAdapter(adapter);
}
static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public Adapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
And here is the Fragment Code;
public class UploadPictures extends android.support.v4.app.Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final RecyclerView recyclerView = (RecyclerView) inflater.inflate(
R.layout.recycler_view, container, false);
ContentAdapter adapter = new ContentAdapter(recyclerView.getContext());
recyclerView.setAdapter(adapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return recyclerView;
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ImageView picture;
public EditText tagEditText;
public Button tagCurLoc, choosePic, uploadContent;
public ViewHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.pictue_upload, parent, false));
picture = (ImageView) itemView.findViewById(R.id.imgToUpload);
tagEditText = (EditText) itemView.findViewById(R.id.tagEditText);
tagCurLoc = (Button) itemView.findViewById(R.id.tagCurLoc);
choosePic = (Button) itemView.findViewById(R.id.choosePic);
choosePic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMAGE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null) {
onActivityResult(requestCode, resultCode, data);
Toast.makeText(getActivity().getApplicationContext(), "Canceled ", Toast.LENGTH_SHORT).show();
} else {
if (requestCode == RESULT_LOAD_IMAGE) {
Uri selectedImgPath = data.getData();
picture.setImageURI(selectedImgPath);
RealFilePath = Uri.parse(String.valueOf(selectedImgPath));
Toast.makeText(getActivity().getApplicationContext(), " " + RealFilePath, Toast.LENGTH_SHORT).show();
}
}
}
});
uploadContent = (Button) itemView.findViewById(R.id.uploadContent);
}
}
/**
* Adapter to display recycler view.
*/
public class ContentAdapter extends RecyclerView.Adapter<ViewHolder> {
// Set numbers of List in RecyclerView.
private Context mContext;
public ContentAdapter(Context context) {
this.mContext = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()), parent);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
}
#Override
public int getItemCount() {
return LENGTH;
}
}
Not sure if the onClick listener for the button should be implemented in the Adapter or the View holder, and from there the issue of onActivityResult cant be used ?
Weel, solved after some more reading and few try outs.
The onClick listener should be implemented at the ViewHolder class followed by
#Override
onActivityResult.
within the onClickListener onActivityResult invoked by;
startActivityForResult(intent, RESULT_LOAD_IMAGE);
and within onActivityResult;
onActivityResult(requestCode, resultCode, data);
Considering all of this taking place in an activity extending Fragment.
Related
mainActivity has button. After button is clicked a popup message show having a button and a TextInputLayout.
data is sent to a tabbed acticity having 2 fragments and
the data is shown in textview of first fragment. Error is the data wont show in the textview while running
adapter for 2 fragments--
public class adapter extends FragmentPagerAdapter {
public adapter(#NonNull FragmentManager fm) {
super(fm);
}
#NonNull
#Override
public Fragment getItem(int position) {
Fragment fragment;
if (position == 1) {
fragment = new SecondFragment();
} else {
fragment = new FirstFragment();
}
return fragment;
}
#Override
public int getCount() {
return 2;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
String title = null;
if (position == 0) {
title = "TextView";
} else if (position == 1) {
title = "Listview";
}
return title;
}
}
mainActivity(having popup window on clicking button)
myDialog = new Dialog(this);
}
//for for joining match
public void ShowPopup(View view) {
myDialog.setContentView(R.layout.popup);
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
myDialog.show();
name = myDialog.findViewById(R.id.ig_name);
String igname = Objects.requireNonNull(name.getEditText()).getText().toString();
entry = myDialog.findViewById(R.id.entry);
entry.setOnClickListener(v -> {
Intent intent = new Intent(getApplicationContext(), secondActivity.class);
intent.putExtra("igname", igname);
startActivity(intent);
finish();
});
}
}
my firstFragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_first, container, false);
secondActivity activity = (secondActivity) getActivity();
TextView output = view.findViewById(R.id.textshow);
Bundle results = activity.getMyData();
String value1 = results.getString("value");
output.setText(value1);
return view;
}
secondActivity (intent is transfered from popup window)
public class secondActivity extends AppCompatActivity {
private String name;
TabLayout tabLayout;
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(new adapter(getSupportFragmentManager()));
tabLayout = findViewById(R.id.tabs_layout);
tabLayout.setupWithViewPager(viewPager);
Intent intent = getIntent();
name = intent.getExtras().getString("igname");
}
public Bundle getMyData() {
Bundle bundle = new Bundle();
bundle.putString("value", name);
return bundle;
}
}
Get the "igname" String value in onClickListner & also dismiss the dialog before finishing the activity.
entry.setOnClickListener(v -> {
String igname = Objects.requireNonNull(name.getEditText()).getText().toString();
Intent intent = new Intent(getApplicationContext(), secondActivity.class);
intent.putExtra("igname", igname);
startActivity(intent);
finish();
});
I had created a app in which i have multiple edittext and one buttonwith recyclerviuew and one button which are setvisibilty as Gone.On Button click it add all my data in my recyclerview list with by chnaging visibality of my recycelr view and my button.In my Custom Adapter i am using a image view to delete the item from postion now i want that if it delete all data from list then it should automatically hide my Button and recyclerview.
//Recycler_view Adapter
public class Myviewholder extends RecyclerView.ViewHolder {
public TextView land_Detail, area_detail, s_no1;
public Button delete;
public Myviewholder(View view) {
super(view);
land_Detail = view.findViewById(R.id.hint31);
area_detail = view.findViewById(R.id.hint21);
s_no1 = view.findViewById(R.id.hint11);
delete = view.findViewById(R.id.hint41);
}
}
public Land_adapters(List<Land_list> land_list, Context context) {
this.laand_list = land_list;
this.context = context;
}
#NonNull
#Override
public Land_adapters.Myviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.land_list, parent, false);
return new Myviewholder(itemView);
}
#Override
public void onBindViewHolder(#NonNull Myviewholder holder, final int position) {
final Land_list current_year = laand_list.get(position);
holder.area_detail.setText("District :" + current_year.getDistrict_name() + "\n" + "Village :" + current_year.getVillage_name());
holder.s_no1.setText(String.valueOf(position + 1));
holder.land_Detail.setText("Acre :" + current_year.getAcre() + "\n" + "Kanal :" + current_year.getKanal() + "\n" + "Marla :" + current_year.getMarla());
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "", Toast.LENGTH_SHORT).show();
Land_list theRemovedItem = laand_list.get(position);
// remove your item from data base
laand_list.remove(position); // remove the item from list
notifyItemRemoved(position); // notify the adapter about the removed item
}
});
}
#Override
public int getItemCount() {
return laand_list.size();
}
//how i am using my recycler in mainactivity class
public void final_step() {
// marla_edit.setError(null);
recyclerView = findViewById(R.id.recycler_view_last1);
mAdapter1 = new Land_Adapter(last_Year1);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setAdapter(mAdapter1);
Land_list last_year1 = new Land_list(land_acre, land_kanal, village_selected1, land_marla, district_selected1, teshil_selected1, block_selected1, block_code, teshil_code1, village_code1, district_code);
last_Year1.add(last_year1);
mAdapter1.notifyDataSetChanged();
if (!(last_Year1.size() == 0)) {
RelativeLayout linearLayout = findViewById(R.id.linear123);
recyclerView.setVisibility(View.VISIBLE);
next_button.setVisibility(View.VISIBLE);
}
else
{
next_button.setVisibility(View.INVISIBLE);
}
// i just want that when it press delete image in recycelr view it should hide my button automatically.
you can use an interface to inform the fragment/activity, the list is empty.
Adapter like as below:
public class CustomAdapter extends RecyclerView.Adapter<CustomViewHolder> {
AdapterListener listener;
public void setListener(AdapterListener listener) {
this.listener = listener;
}
...
#Override
public void onBindViewHolder(#NonNull Myviewholder holder, final int position) {
...
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
...
// remove your item from data base
laand_list.remove(position); // remove the item from list
notifyItemRemoved(position); // notify the adapter about the removed item
if (laand_list.size()==0)
listener.onDataListIsEmpty();
}
});
}
public interface AdapterListener {
void onDataListIsEmpty();
}
}
The Activity/Fragment like as below:
class MyActivity extends Activity implements CustomAdapter.AdapterListener {
CustomAdapter adapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
adapter = new CustomAdapter();
adapter.setListener(this);
...
}
#Override
public void onDataListIsEmpty() {
// set visible or gone views
}
}
I'm working on my 1st android project, which uses a tab layout. I want to keep track of the active tab and change a textview present in the appbar (main activity).
Here is my main activity, tab manager, and a fragment
MAIN ACTIVITY
private static final String TAG = "MainActivity";
private SectionsPageAdapter mSectionsPageAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPageAdapter = new SectionsPageAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
setupViewPager(mViewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.Tabs);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.tab_rooms_24dp);
tabLayout.getTabAt(1).setIcon(R.drawable.tab_feed_24dp);
tabLayout.getTabAt(2).setIcon(R.drawable.tab_profile_24dp);
tabLayout.getTabAt(0).getIcon().setColorFilter(getResources().getColor(R.color.Accent), PorterDuff.Mode.SRC_IN);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
tab.getIcon().setColorFilter(getResources().getColor(R.color.Accent),PorterDuff.Mode.SRC_IN);
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
tab.getIcon().clearColorFilter();
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
private void setupViewPager(ViewPager viewPager){
SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
adapter.addFragment(new Tab1Fragment(), "");
adapter.addFragment(new Tab2Fragment(), "");
adapter.addFragment(new Tab3Fragment(), "");
viewPager.setAdapter(adapter);
}
TAB MANAGER
private final List<Fragment> mFragmentList =new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public void addFragment(Fragment fragment, String title){
mFragmentList.add(fragment);
mFragmentTitleList.add(title );
}
public SectionsPageAdapter(FragmentManager fm) {
super(fm);
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
FRAGMENT
private static final String TAG = "Tab3Fragment";
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_tab1,container,false);
return view;
}
I tried creating a variable in an abstract class then extending it into all three of these scripts which would be a simple solution but fragments dont seem to work well with extending, not to mention that probably isnt the most efficient method.
So I'm thinking the best method would be to simply handle it from the SectionsPageManager script?
Use addOnPageChangeListener on you pager.
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (position == 1) {
setTitle("Tab 1");
} else if (position == 2)
{
setTitle("Tab 2");
}
else
{
setTitle("Home");
}
}
So I got it worked out and figured I'd come post the answer for anyone who may need it.
Not that the above answer sets the app title, not a TextView withing the appbar as stated in the question.
private static final String TAG = "MainActivity";
private SectionsPageAdapter mSectionsPageAdapter;
private ViewPager mViewPager;
private TextView activeTab;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activeTab = (TextView)findViewById(R.id.PageTitle);
mSectionsPageAdapter = new SectionsPageAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
setupViewPager(mViewPager);
}
private void setupViewPager(ViewPager viewPager)
{
SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
adapter.addFragment(new Tab1Fragment(), "");
adapter.addFragment(new Tab2Fragment(), "");
adapter.addFragment(new Tab3Fragment(), "");
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { }
#Override
public void onPageSelected(int position)
{
switch (position){
case 0: activeTab.setText("text");
break;
case 1: activeTab.setText("better text");
break;
case 2: activeTab.setText("best text");
break;
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
Here I'm using Custom Adapter by implementing listAdapter to Support buttons in the list items. When i click the Delete button it deletes currect row. But i can't able to refresh this listView.
File Structure is MainActivity -> FragmentClass-> this Custom class for the listAdpater.
public class Category_ListView_Custom_Adapter extends BaseAdapter implements ListAdapter{
private Realm realm;
private ArrayList<String> list = new ArrayList<>();
private Context context;
public Category_ListView_Custom_Adapter(ArrayList<String> list, Context context){
this.list = list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
View view1 = view;
realm = Realm.getDefaultInstance();
if(view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.category_listview_row, null);
}
TextView listItemText = (TextView) view.findViewById(R.id.item);
listItemText.setText(list.get(i));
ImageView edit = (ImageView) view.findViewById(R.id.image);
ImageView delete = (ImageView) view.findViewById(R.id.delete);
edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// list.remove(i);
/// Toast.makeText(view.getContext(), "hey "+list.get(i).toString(), Toast.LENGTH_SHORT).show();
// notifyDataSetChanged();
Intent intent = new Intent(context, AddCategory.class);
intent.putExtra("category","expense");
intent.putExtra("subcategory", list.get(i));
context.startActivity(intent);
}
});
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
RealmResults<Category> categorylist = realm.where(Category.class).equalTo("Id",i+1).and().equalTo("Subcategory",list.get(i)).findAll();
for (Category category : categorylist) {
realm.beginTransaction();
categorylist.deleteFirstFromRealm();
realm.commitTransaction();
try {
context.notifyAll();
}catch (Exception e){
Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
}
// Expense.call_resume
}
}
});
return view;
}
}
Please Help me. Thank you.
You are .removing from a wrong view. Try to make root List<> static and do Class.list.get(i).remove or something like that.
Also, try to hide a view inside your get view.
I have a car that loads data from a remote database. Each item in the list has two buttons and I need to make different volley requests for each button. I know how to make the onclick work in the complete item but not how to do it for a widget inside the item.
Item screenshot
I hope you can help me, thanks in advance.
RecyclerViewAdapater:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{
private static final String TAG = "RecyclerViewAdapter";
//vars
private List<Buttons> buttonsList;
private Context mContext;
public RecyclerViewAdapter(List<Buttons> buttonsList, Context mContext) {
this.buttonsList = buttonsList;
this.mContext = mContext;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_list_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
Log.d(TAG, "onBindViewHolder: called.");
Buttons buttons = buttonsList.get(position);
Glide.with(mContext)
.load(buttons.getButton_url())
.into(holder.image);
holder.name.setText(buttons.getButton_score());
holder.price.setText(buttons.getButton_price());
}
#Override
public int getItemCount() {
return buttonsList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
CircleImageView image;
TextView name, price;
Button buy_button, select_button;
public ViewHolder(View itemView) {
super(itemView);
image = (CircleImageView) itemView.findViewById(R.id.image_view);
name = (TextView) itemView.findViewById(R.id.name);
price = (TextView) itemView.findViewById(R.id.price);
buy_button = (Button) itemView.findViewById(R.id.buy_button_item);
select_button = (Button) itemView.findViewById(R.id.select_button_item);
}
}
}
MainActivity:
private void initRecyclerView(){
Log.d(TAG, "initRecyclerView: init recyclerview");
final LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerButtonsView);
recyclerView.setLayoutManager(layoutManager);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(buttonsList, this);
recyclerView.setAdapter(adapter);
}
I solved this with the answer of LordParsley in this post