How to refresh RecyclerView from button on DialogFragment - android

I have an application with a RecyclerView and a DialogFragment, in the Dialog I add data to the database and display it in the RecyclerView. I tried to refresh the RecyclerView when I clicked in to add.
This is the Fragment
public class addAction extends DialogFragment implements View.OnClickListener {
EditText addTitle, addDesc;
Button add, clear,close;
Context context;
private DatabaseHelpher db;
String Title,Des;
public addAction() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.addaction, container, false);
addTitle = (EditText) rootView.findViewById(R.id.todotitle);
addDesc = (EditText) rootView.findViewById(R.id.tododescription);
add = (Button) rootView.findViewById(R.id.addbutton);
add.setOnClickListener(this);
close = (Button) rootView.findViewById(R.id.Close);
close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dismiss();
}
});
clear = (Button) rootView.findViewById(R.id.clear);
clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addTitle.setText("");
addDesc.setText("");
}
});
return rootView;
}
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getDialog().setTitle("Add Action");
db = new DatabaseHelpher(getContext());
}
private void insert() {
Title = addTitle.getText().toString();
Des= addDesc.getText().toString();
db.insertIntoDB(Title, Des);
}
#Override
public void onClick(View v) {
if (addTitle.getText().toString().trim().equals("")) {
addTitle.setError(" Title is required!");
} else if (addDesc.getText().toString().trim().equals("")) {
addDesc.setError(" Postion is required!");
}
insert();
}
}
and this is the MainActivity
public class MainActivity extends AppCompatActivity {
List<ToDoModule> dbList;
RecyclerView mRecyclerView;
DatabaseHelpher helpher;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().hide();
helpher = new DatabaseHelpher(this);
dbList= new ArrayList<ToDoModule>();
dbList = helpher.getDataFromDB();
mRecyclerView = (RecyclerView)findViewById(R.id.AppRecyclerView);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new RecyclerAdapter(this,dbList);
mAdapter.notifyDataSetChanged();
mRecyclerView.setAdapter(mAdapter);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setImageResource(R.drawable.ic_action_name);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentManager fm = getSupportFragmentManager();
addAction add = new addAction();
add.show(fm, "fragment_edit_name");
}
});}
#Override
protected void onResume() {
super.onResume();
dbList = helpher.getDataFromDB();
mAdapter.notifyDataSetChanged();
}
}

Call mAdapter.notifyDataSetChanged(); in your Activity's onResume() method.

First Solution
cast activity and call your method like this:
in your activity add this method
public void myMethod(){
runOnUiThread(new Runnable() {
#Override
public void run() {
//your code here
}
});
}
in your DialogFragment call the activity method after you cast it.
((YourActivity)getActivity()).myMethod();
Second Solution
add eventbus to your gradle
compile 'org.greenrobot:eventbus:3.0.0'
make a class that you want to pass to activity
public class MessageEvent {
public final String message;
public MessageEvent(String message) {
this.message = message;
}
}
listen to events in your activity
// This method will be called when a MessageEvent is posted (in the UI thread for Toast)
#Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {
Toast.makeText(getActivity(), event.message, Toast.LENGTH_SHORT).show();
}
register EventBus in your Activity
#Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
public void onStop() {
EventBus.getDefault().unregister(this);
super.onStop();
}
finally send in Event from Dialog to your Activity
EventBus.getDefault().post(new MessageEvent("Hello everyone!"));
don't forgot adding this to proguard file
-keepattributes *Annotation*
-keepclassmembers class ** {
#org.greenrobot.eventbus.Subscribe <methods>;
}
-keep enum org.greenrobot.eventbus.ThreadMode { *; }

Related

android viewpager2 page buton controller

if the page is loaded, the button is active, if not, how can I do passive control?
What I want to do is, if the Viewpager Page is loaded, the button is active, if not, the Button is Passive. But I couldn't do any kind.
Is there anyone who can help?
If viewpager2 is installed Button enabled, if viewpager2 is not installed button false;
List<Movie> movieList = new ArrayList<>();
private ImageButton btn_down, btn_fav;
private Button btn_setter;
private DatabaseReference movies;
private IFirebaseLoadDone iFirebaseLoadDone;
public CartoonFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_cartoon, container, false);
movies = FirebaseDatabase.getInstance().getReference("Sports");
movies.keepSynced(true);
iFirebaseLoadDone = this;
loadMovie();
viewPager2 = view.findViewById(R.id.viewPager2_);
btn_down = view.findViewById(R.id.btn_down);
btn_setter = view.findViewById(R.id.btn_setter);
btn_fav = view.findViewById(R.id.btn_fav);
btn_down.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SaveToGallery();
}
});
btn_setter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
btn_fav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return view;
}
private void loadMovie() {
movies.addValueEventListener(this);
}
#Override
public void onFirebaseLoadSuccess(List<Movie> movieList) {
viewPagerAdapter = new ViewPagerAdapter(getContext(), movieList, viewPager2);
viewPager2.setAdapter(viewPagerAdapter);
}
#Override
public void onFirebasLoadFailed(String message) {
}
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot moviesSnapShot : dataSnapshot.getChildren())
movieList.add(moviesSnapShot.getValue(Movie.class));
Collections.reverse(movieList);
iFirebaseLoadDone.onFirebaseLoadSuccess(movieList);
viewPagerAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
iFirebaseLoadDone.onFirebasLoadFailed(databaseError.getMessage());
}
#Override
public void onDestroy() {
movies.removeEventListener(this);
super.onDestroy();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onStop() {
movies.removeEventListener(this);
super.onStop();
}
}
Replace your methods with mine.
private void loadMovie() {
movies.addValueEventListener(this);
btn_down.setEnabled(false);
btn_fav.setEnabled(false);
btn_setter.setEnabled(false);
}
Firebase methods
#Override
public void onFirebaseLoadSuccess(List<Movie> movieList) {
viewPagerAdapter = new ViewPagerAdapter(getContext(), movieList, viewPager2);
viewPager2.setAdapter(viewPagerAdapter);
if(movieList!=null && !movieList.isEmpty()){
btn_down.setEnabled(true);
btn_fav.setEnabled(true);
btn_setter.setEnabled(true);
}
}
#Override
public void onFirebasLoadFailed(String message) {
btn_down.setEnabled(false);
btn_fav.setEnabled(false);
btn_setter.setEnabled(false);
}
There was an error loading
private void loadMovie() {
movies.addValueEventListener(this);
btn_down.setEnabled(false);
btn_fav.setEnabled(false);
btn_setter.setEnabled(false);
}
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageButton.setEnabled(boolean)' on a null object reference
at com.example.duvarlar.Fragment.CartoonFragment.loadMovie(CartoonFragment.java:386)
at com.example.duvarlar.Fragment.CartoonFragment.onCreateView(CartoonFragment.java:90)

How to use "onClickListener" in MPV in android?

I use mvp architecture.
I have the setupViews () method in which the buttons and ... are defined
how i can use setOnclickListener for Button in "presenter" and call it in SetupViews in "activity".
I do not want to use it directly in "view",I want to tell the presenter that the click is done and the presenter will do the job.
My interface:
public interface HomeContract {
interface View extends BaseView {
void showNews(List<News> newsList);
void showError(String error);
}
interface Presenter extends BasePresenter<View> {
void getNewsList();
} }
presenter class :
public class HomePresenter implements HomeContract.Presenter {
private HomeContract.View view;
private NewsDataSourse newsDataSourse;
CompositeDisposable compositeDisposable = new CompositeDisposable();
public HomePresenter(NewsDataSourse newsDataSourse) {
this.newsDataSourse = newsDataSourse;
}
#Override
public void getNewsList() {
newsDataSourse.getNews().subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new SingleObserver<List<News>>() {
#Override
public void onSubscribe(Disposable d) {
compositeDisposable.add(d);
}
#Override
public void onSuccess(List<News> news) {
view.showNews(news);
}
#Override
public void onError(Throwable e) {
view.showError(e.toString());
}
});
}
#Override
public void attachView(HomeContract.View view) {
this.view = view;
getNewsList();
}
#Override
public void detachView() {
this.view = null;
if (compositeDisposable != null && compositeDisposable.size() > 0) {
compositeDisposable.clear();
}
}}
my view :
public class HomeActivity extends BaseActivity implements HomeContract.View {
private HomeContract.Presenter presenter;
private NewsRepository newsRepository = new NewsRepository();
private RecyclerView recyclerView;
private RecyclerAdapter recyclerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
presenter = new HomePresenter(newsRepository);
}
#Override
public void setupViews() {
Button btn_Ok = (Button) findViewById(R.id.btn_Ok);
recyclerView = (RecyclerView) findViewById(R.id.recycler);
recyclerView.setLayoutManager(new LinearLayoutManager(getViewContext(), LinearLayout.VERTICAL, false));
// btn_Ok.setOnClickListener();
}
#Override
public void showNews(List<News> newsList) {
setupViews();
recyclerView.setAdapter(new RecyclerAdapter(newsList, getViewContext()));
if (newsList.size() > 0) {
Toast.makeText(getViewContext(), "ok", Toast.LENGTH_SHORT).show();
Toast.makeText(getViewContext(), newsList.get(0).getName(), Toast.LENGTH_SHORT).show();
} else
Toast.makeText(getViewContext(), "not Ok", Toast.LENGTH_SHORT).show();
}
#Override
public void showError(String error) {
Toast.makeText(getViewContext(), error, Toast.LENGTH_SHORT).show();
}
#Override
public Context getViewContext() {
return getApplicationContext();
}
#Override
protected void onStart() {
super.onStart();
presenter.attachView(this);
}
#Override
protected void onStop() {
super.onStop();
presenter.detachView();
}
}
i want to use btn_Ok.setOnClickListener(presenter....); in view Or any better solution you need to do this
In your presenter interface type a method :
interface Presenter extends BasePresenter<View> {
void getNewsList();
void onButtonClicked();
}
And than in your HomePresenter class use it :
#Override
public void onButtonClicked(){
// continue logic here
}
If you don't override it the class will show an error

How to create a callback from MainActivity to a fragment?

I am trying to create a callback from MainActivity to a fragment.
In MainActivity I have 5 tabs. Each tab has a different UI through a fragment. The fragments are added via viewpager. My objective is to inform a fragment when an ad has been loaded in MainAcitivty. After the fragment gets the message it can then display the add itself by calling a method of MainActivity. At the moment I dont want to send any message back to MainActivity.
The code of the MainActivity is:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
private ViewPager viewPager = null;
private RewardedVideoAd mRewardedVideoAd;
private NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
this.setTitle(R.string.app_title);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText(R.string.Tab1));
tabLayout.addTab(tabLayout.newTab().setText(R.string.Tab2));
tabLayout.addTab(tabLayout.newTab().setText(R.string.Tab3));
tabLayout.addTab(tabLayout.newTab().setText(R.string.Tab4));
tabLayout.addTab(tabLayout.newTab().setText( R.string.Tab5));
viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
drawer = (DrawerLayout) findViewById(R.id.drawerLayout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
//handling navigation view item event
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setItemIconTintList(null);
assert navigationView != null;
navigationView.setNavigationItemSelectedListener(this);
MobileAds.initialize(this, "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
mRewardedVideoAd.setRewardedVideoAdListener(new RewardedVideoAdListener() {
#Override
public void onRewarded(RewardItem rewardItem) {
Toast.makeText(getApplication(),"Ad Rewarded.", Toast.LENGTH_SHORT).show();
loadRewardedVideoAd();
}
#Override
public void onRewardedVideoAdLoaded() {
Toast.makeText(getApplication(),"Ad loaded.", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdOpened() {
Toast.makeText(getApplication(),"Ad opened.", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoStarted() {
Toast.makeText(getApplication(),"Ad started", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoCompleted() {
Toast.makeText(getApplication(),"Ad completed.", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdClosed() {
Toast.makeText(getApplication(),"Ad closed.", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdLeftApplication() {
Toast.makeText(getApplication(),"Ad left application.", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
Toast.makeText(getApplication(),"Ad failed to load.", Toast.LENGTH_SHORT).show();
}
});
loadRewardedVideoAd();
}
public void loadRewardedVideoAd() {
mRewardedVideoAd.loadAd("xxxxxxxxxxxxxxxxxxxxxxxxxxxx",new AdRequest.Builder().build());
}
public void showRewardedVideoAd() {
mRewardedVideoAd.show();
}
#Override
public void onResume() {
mRewardedVideoAd.resume(getParent());
super.onResume();
}
#Override
public void onPause() {
mRewardedVideoAd.pause(getParent());
super.onPause();
}
#Override
public void onDestroy() {
mRewardedVideoAd.destroy(getParent());
super.onDestroy();
}
public interface onToggledListener{
void onToggled();
}
private onToggledListener toggledListener;
public void setOnToggledlistener(onToggledListener listener){
toggledListener = listener;
}
}//end of MainActivity
The code of the fragment is:
public class Tab1 extends Fragment implements MainActivity.onToggledListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab1, container, false);
buttonVideo = (Button) view.findViewById(R.id.videoAd);
fab =(FloatingActionButton) view.findViewById(R.id.fab);
return view;
}
//method implemented here
#Override
public void onToggled(){
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
buttonVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showad();// some method
}
});
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
add();//some method
}
});
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
}
}// end of fragment class
This is how I am trying to achieve my objective but I am not getting the result. Callback is not working
You not call method setOnToggledlistener which initialize your interface & then you can get call back from MainActivity to Fragment.
So, call setOnToggledlistener from activity .
In activity :
#Override
public void onRewardedVideoAdLoaded() {
toggledListener.onToggled(); //trigger callback when video loaded.
}
In fragment:
#Override
public void onResume() {
super.onResume();
getActivity().setOnToggledlistener(this); //register callback
}

Issue with coding the communication between a fragment and an async task

I'm new to this concept. I read several threads but I block so thanks in advance for your patience!
In a fragment (frag1) I launch an async task. I want to prevent the user of doing anything while the task is not completed so I want to communicate the % of the task completed so the user waits informed.
I've defined an interface in a java SetVal.java:
interface SetVal {
void setVal(int val);
}
My async task:
class AsyncCounter extends AsyncTask<Void, Integer, Void> {
private SetVal sender;
public AsyncCounter(SetVal sv){
this.sender = sv;
}
#Override
protected Void doInBackground(Void... params) {
for(int i=0;i<60;i++){
publishProgress(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
Log.i("ASYNC TASK","val: "+values[0]);
sender.setVal(values[0]);
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
public interface SetVal {
public void setVal(int val);
}
public void setListener(SetVal listener) {
this.sender = listener;
}
}
I'm struggling to know how to pass the interface to the task.
Is my code correct?
How do I instantiate the async task?
fragment:
public class Frag1 extends android.app.Fragment implements SetVal {
private static TextView txt;
private int counter;
SetVal listener;
public Frag1() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_frag1, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
txt = (TextView) getActivity().findViewById(R.id.txt);
Button btn = (Button) getActivity().findViewById(R.id.btn1);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.i("Frag1", "val: " + counter);
if (counter > 0) return;
FragmentTransaction ft = getFragmentManager().beginTransaction();
Frag2 f2 = new Frag2();
ft.replace(R.id.content_frame, f2);
ft.addToBackStack("f2");
ft.commit();
}
});
Button btn2 = (Button) getActivity().findViewById(R.id.btn2);
btn2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AsyncCounter ac = new AsyncCounter(???????);
ac.execute();
}
});
}
#Override
public void setVal(int val) {
counter = val;
}
}
Not sure what and why you are trying to do that, but you can pass the Fragment :
Try to create a private method:
public void onClick(View v) {
startMyAsync();
}
private void startMyAsync() {
new AsyncCounter(this).execute();
}
finally:
public AsyncCounter(Frag1 context){
this.sender = (SetVal)context;
}

Android tcp/ip read and write buffer out of main code

I can read and write TCP/IP buffer on the Main layout and MainActivity java with a button.
But can't do so on different fragment or different layout.
ERROR MESSAGE IS:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.murat.ev.TcpClient.sendMessage(java.lang.String)' on a null object reference
My code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
public TcpClient mTcpClient;
public Thread send_data;
public Button button;
public byte data[]=new byte[1024];
public DatabaseConstruction db;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DatabaseConstruction(getApplicationContext());
new datasync().execute("");
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment1 fragment1=new Fragment1();
fragmentTransaction.replace(R.id.container, fragmen1_layout);
fragmentTransaction.commit();
button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
send_data_pre();
}
});
}
public class datasync extends AsyncTask<String, String, TcpClient>
{
#Override
protected TcpClient doInBackground(String... message)
{
//we create a TCPClient object and
mTcpClient = new TcpClient(new TcpClient.OnMessageReceived()
{
#Override
//here the messageReceived method is implemented
public void messageReceived(String message)
{
Log.i("Debug","Input message: " + message);
publishProgress(message);
}
});
mTcpClient.run();
return null;
}
#Override
protected void onProgressUpdate(String... values)
{
super.onProgressUpdate(values);
Log.i("onProgressUpdate",values[0]);
}
}
public void send_data_pre()
{
send_data = new Thread(new send_data("hello"));
send_data.start();
}
public class send_data implements Runnable
{
private String message;
public send_data (String message)
{
this.message = message;
}
#Override
public void run()
{
mTcpClient.sendMessage(message);
Log.i("Debug", "mesaj did send");
}
}
}
Fragment1.java
public class Fragment1 extends Fragment {
Button button1;
MainActivity main=new MainActivity();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment1_layout, container, false);
button1 =(Button)view.findViewById(R.id.buton_1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
main.send_data(); ////THIS HERE IS APP STOP AND ERROR
}
});
return view;
}
}
maybe in fragment you want to do
main.send_data_pre(); insted of
main.send_data();
like you do in OnCreate() of the MainActivity if i understood your question well.

Categories

Resources