I seek to receive data from AsyncTask inside a fragment. I'm aware to achieve this with activity but having difficulties in fragment.
GetResult class
public interface GetResult {
void getData(ArrayList<String> result);
}
myFrag class
public class myFrag extends Fragment implements GetResult{
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.myFrag_layout, container, false);
Button myBtn = (Button) view.findViewById(R.id.Button1);
myBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
myAsync obj = new myAsync();
obj.setListener(getActivity());
}
});
}
}
myAsync class
public class myAsync extends AsyncTask<Void, Void, String>{
GetResult interfaceObj = null;
public void setListener( GetResult interfaceObj ) {
this.interfaceObj = interfaceObj;
}
}
I'm having problem with obj.setListener(getActivity). It say The method setListener(GetResult) in the type myAsync is not applicable for the arguments (FragmentActivity). Thanks in advance to everyone.
I didn't figured out wt the problem is but there is another way to do it. I'll just share it here.
1st the interface class GetResult.class is same
2nd Changes in the fragment class myFrag.class
public class myFrag extends Fragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.myFrag_layout, container, false);
Button myBtn = (Button) view.findViewById(R.id.Button1);
myBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
getLoc obj = new getLoc(getActivity(), new GetResultInterface() {
#Override
public void processFinish(ArrayList<String> result) {
// U can get the result here
}
obj.execute(url);
});
}
}
3rd In AsyncTask myAsync.class
public class myAsync extends AsyncTask<Void, Void, String>{
Context context;
GetResult interfaceObj = null;
public myAsync(Context context, GetResultInterface interfaceObj) {
this.context = context;
this.interfaceObj = interfaceObj;
}
#Override
protected void onPostExecute(ArrayList<String> result) {
super.onPostExecute(result);
interfaceObj.processFinish(result);
}
}
Related
I'm using TabLayout and ViewPager in MainActivity and I want to open a specific website in a fragment(BrowserFragment) that contains a webview by clicking a button in another fragment(FragmentHome). In HomeFragment I've 2 buttons, goToFacebook which lead to Facebook and goToAmazon which lead to Amazon.
This is my code:
MainActivity extends AppCompatActivity
TabLayout tabLayout;
ViewPager viewPager;
TabItem homeTabItem;
TabItem browserTabItem;
TabItem profilTabItem;
PagerAdapter pagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabLayout=findViewById(R.id.tabLayout);
homeTabItem=findViewById(R.id.homeTabItem);
browserTabItem=findViewById(R.id.browserTabItem);
profilTabItem=findViewById(R.id.profilTabItem);
viewPager=findViewById(R.id.viewPager);
pagerAdapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(pagerAdapter);
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) {
}
});
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
}
PagerAdapter extends FragmentPagerAdapter
private int numOfTabs;
public PagerAdapter(#NonNull FragmentManager fm, int numOfTabs) {
super(fm);
this.numOfTabs=numOfTabs;
}
#NonNull
#Override
public Fragment getItem(int position) {
Fragment fragment;
switch(position){
case 0 :
return new HomeFragment();
case 1 :
return new BrowserFragment();
case 2 :
return new ProfilFragment();
default:
return null;
}
}
#Override
public int getCount() {
return numOfTabs;
}
BrowserFragment extends Fragment
WebView webView;
ProgressBar progressBar;
public BrowserFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_browser, container, false);
progressBar = v.findViewById(R.id.progressBar);
progressBar.setMax(100);
webView=v.findViewById(R.id.webView);
webView.setWebViewClient(new MyWebViewClient());
webView.setWebChromeClient(new MyWebChromeClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("https://www.google.com/");
return v;
}
private class MyWebViewClient extends WebViewClient
{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String request)
{
view.loadUrl(request);
return true;
}
#Override
public void onPageFinished(WebView view, String url)
{
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
progressBar.setProgress(100);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress(0);
}
}
private class MyWebChromeClient extends WebChromeClient
{
public void onProgressChanged(WebView view, int progress)
{
progressBar.setProgress(progress);
}
}
HomeFragment extends Fragment
Button goToAmazon, goToFacebook;
String urlAmazon ="https://www.amazon.com";
String urlFacebook="https://www.facebook.com";
String urlDestination;
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_home, container, false);
goToAmazon=v.findViewById(R.id.goToAmazon);
goToFacebook=v.findViewById(R.id.goToFacebook);
goToAmazon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
urlDestination=urlAmazon;
}
});
goToFacebook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
urlDestination=urlFacebook;
}
});
return v;
}
Which code should I put in onClick() method to load the specific address in the webview and display the fragment containing webview?
My question is simple how to send data from Main activity to fragment through interface but not through intent or bundle in android.
Please guide me thanks.
Here is my code from fragment to Activity data send through interface but I want against it Activity to fragment which I don't know how to do.
public interface OnRestaurantSelectedListener {
public void onRestaurantSelected(String s);
}
MainActivity extends AppCompatActivity implements OnRestaurantSelectedListener{
String mPosition;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onRestaurantSelected(String s) {
mPosition =s;
}
}
In fragment:
public class ListFragment extends Fragment {
...
private OnRestaurantSelectedListener mOnRestaurantSelectedListener;
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
mOnRestaurantSelectedListener = (OnRestaurantSelectedListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + e.getMessage());
}
}
mOnRestaurantSelectedListener.onRestaurantSelected("AliResturant");
}
Create interface FragmentCommunicator as,
public interface FragmentCommunicator{
public void passDataToFragment(String someValue);
}
In your main Activity we can use interface and pass data to fragment. Like below,
public class MainActivity extends FragmentActivity{
//interface through which communication is made to fragment
public FragmentCommunicator fragmentCommunicator;
private Button fragmentButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.title_viewpager);
fragmentButton = (Button)findViewById(R.id.fragmentButton);
setUIListeners();
}
private void setUIListeners(){
fragmentButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if(fragmentCommunicator != null)
fragmentCommunicator.passDataToFragment("Hi from FragmentActivity");
}
});
}
}
Access passed data in fragment like below,
public class CustomFragment extends Fragments implements FragmentCommunicator{
public Context context;
private Button activityButton;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View fragmentView = inflater.inflate(R.layout.activity_frag, container, false);
activityButton =(Button)fragmentView.findViewById(R.id.activityButton);
textView =(TextView)fragmentView.findViewById(R.id.textView);
setRetainInstance(true);
return fragmentView;
}
//FragmentCommunicator interface implementation
#Override
public void passDataToFragment(String someValue){
String activityAssignedValue = someValue;
textView.setText(activityAssignedValue);
}
}
I am trying to implement viewpager with Tablayout. In this everything is fine working properly, but the one problem is when i come back from another screen view pager lost their position with Tablayout and when i scroll its crash the app.I find many solutions but all of these cannot work for this. Here is my code Adapter Class:-
public class Portfolio_Adapter extends FragmentStatePagerAdapter {
int tabCount;
public Portfolio_Adapter(FragmentManager fm,int tabCount) {
super(fm);
this.tabCount=tabCount;
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
Websites_Fragment websites_fragment=new Websites_Fragment();
return websites_fragment;
case 1:
Mobileapplication_fragment mobileapplication_fragment=new Mobileapplication_fragment();
return mobileapplication_fragment;
case 2:
Graphics_Fragment graphics_fragment=new Graphics_Fragment();
return graphics_fragment;
default:
return null;
}
}
#Override
public int getCount() {
return tabCount;
}
}
Fragment class:-
public class Portfolio_fragment extends Fragment {
TabLayout tabLayout;
ViewPager viewPager;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.portfolio_fragment, container, false);
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Portfolio");
tabLayout = (TabLayout) view.findViewById(R.id.portfolio_tabLayout);
tabLayout.setupWithViewPager(viewPager);
tabLayout.addTab(tabLayout.newTab().setText("Websites"));
tabLayout.addTab(tabLayout.newTab().setText("Mobile Application"));
tabLayout.addTab(tabLayout.newTab().setText("Graphics"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
viewPager = (ViewPager) view.findViewById(R.id.portfolio_pager);
Portfolio_Adapter adapter = new Portfolio_Adapter(getChildFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(3);
tabLayout.setOnTabSelectedListener(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) {
}
});
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
ViewGroup slidingTabStrip = (ViewGroup) tabLayout.getChildAt(0);
for (int i = 0; i < tabLayout.getTabCount(); i++) {
View tab = slidingTabStrip.getChildAt(i);
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) tab.getLayoutParams();
layoutParams.weight = 1;
tab.setLayoutParams(layoutParams);
}
return view;
}
}
Your code is right you only have to change the placement of code put your
tabLayout.setupWithViewPager(viewPager);
,
tabLayout.addTab(tabLayout.newTab().setText("Websites"));
tabLayout.addTab(tabLayout.newTab().setText("Mobile Application"));
tabLayout.addTab(tabLayout.newTab().setText("Graphics"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
after setadapter in viewPager
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(3);
So I got 2 fragments and an activity. Those 2 fragments are communicating each other via an interface.
Problem is, I can't change the TextView in the second fragment from Activity wih some text from fragment1.
There is the same problem( How to change fragment's textView's text from activity ) but there is no real solution so i thought i should open this.
Fragment 1:
public class test_layout extends Fragment {
DearListener activityCommander;
TextView custom_question_bar, list_number;
String selectedCustomQuestion;
boolean buttonClicked;
Button yiyecekButton;
Context c;
public interface DearListener {
public void getMyText(String theQuestion);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
activityCommander = (DearListener) activity;
Log.i("MYLOG", "onAttach");
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString());
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.new_test_layout, container, false);
//custom_question_bar= (TextView) v.findViewById(R.id.custom_question_bar);
//list_number= (TextView) v.findViewById(R.id.list_number);
yiyecekButton = (Button) v.findViewById(R.id.yiyecekButton);
Log.i("MYLOG", "Button referenced");
yiyecekButton.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View v){
Log.i("MYLOG", "onCLickListener Called");
onClickYiyecek(v);
}
}
);
return v;
}
public void onClickYiyecek(View v){
Log.i("MYLOG", "OnClickYiyecek");
activityCommander.getMyText("En sevdiğim yiyecek ne?");
}
public void onClickQuestionReady(View v){
if( custom_question_bar == null)
{
Toast.makeText(c, "Boşluğu doldurmadınız", Toast.LENGTH_SHORT).show();
}
activityCommander.getMyText(custom_question_bar.getText().toString());
}
}
And the Activity:
public class NewTest extends Activity implements test_layout.DearListener {
FragmentManager manager;
test_layout test_layout_frag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_holder);
manager=getFragmentManager();
test_layout_frag = new test_layout();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.the_frame_layout, test_layout_frag);
transaction.commit();
}
#Override
public void getMyText(String theQuestion) {
manager=getFragmentManager();
answer_layout answer_layout_frag = new answer_layout();
answer_layout answer_layout_obj = (answer_layout)getFragmentManager().findFragmentById(R.id.fragment2);
answer_layout_obj.changeText(theQuestion);
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.the_frame_layout, answer_layout_frag);
transaction.commit();
Log.i("MYLOG", "Transaction Called");
//transaction.addToBackStack(null);
}
}
And the second fragment:
public class answer_layout extends Fragment {
TextView yourSelectedQuestion;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.new_answer_layout, container, false);
yourSelectedQuestion= (TextView) v.findViewById(R.id.yourSelectedQuestion);
return v;
}
public void changeText(String a) {
Log.i("MYLOG", "changeText");
Log.i("MYLOG", a);
yourSelectedQuestion.setText(a);
}
}
No exception is given but the TextView in second fragment isn't changing.
Since i didn't write the xml here, I can if its needed. Using FrameLayout and it contains 2 fragments inside it.
In myFragment class write a static method:
public static myFragment newInstance(String txt) {
myFragment myfragment = new myFragment();
Bundle args = new Bundle();
args.putString("TEXT", txt);
myfragment.setArguments(args);
return myfragment;
}
after that in OnCreate method of myFragment class inflate the textView tv and
tv.setText(getArguments().getString("TEXT"));
In main FragmentActivity class do:
myFragment fragment = myFragment.newInstance(textToBeSent);
before replace,
fragmentTransaction.replace(R.id.fr_dynamic, fragment);
fragmentTransaction.commit();
I have a ParseQueryAdapter that is populating a listview inside of a fragment:
QueryAdapter:
public class CustomAdapter extends ParseQueryAdapter implements AdapterView.OnItemClickListener {
public CustomAdapter(Context context) {
super(context, new ParseQueryAdapter.QueryFactory<ParseObject>() {
public ParseQuery create() {
ParseQuery query = new ParseQuery("Invoice");
query.whereEqualTo("CustomerID", ParseUser.getCurrentUser());
return query;
}
});
}
#Override
public View getItemView(ParseObject object, View cellview, ViewGroup parent) {
if (cellview == null) {
cellview = View.inflate(getContext(), R.layout.cell_layout, null);
}
TextView cellDate = (TextView) cellview.findViewById(R.id.dateTextView);
TextView invoice = (TextView) cellview.findViewById(R.id.invoiceNoTextView);
cellDate.setText(object.getString("Date"));
invoice.setText(object.getString("InvoiceNumber"));
return cellview;
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
}
Fragment Containing Listview:
public class InvoiceHistory extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final FrameLayout layout = (FrameLayout) inflater.inflate(R.layout.fragment_invoice_history, container, false);
ListView invoicesListView = (ListView) layout.findViewById(R.id.invoiceList);
ParseQueryAdapter adapter = new CustomAdapter(getActivity());
invoicesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Fragment detailView = new InvoicesFragment();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.placeholder, detailView);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
invoicesListView.setAdapter(adapter);
adapter.loadObjects();
return layout;
}
}
This populates the ListView with the proper fields from the query, but when I click on one of the cells the fragment transaction takes place, but i can't figure out how to set textfields on that new fragment with ParseObject Keys from the Query.
This is the fragment that gets Presented that I want to set the Textfields in:
public class InvoicesFragment extends Fragment {
public InvoicesFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
RelativeLayout layout = (RelativeLayout) inflater.inflate(R.layout.fragment_invoices, container, false);
return layout;
}
Android is super new to me so maybe this is a wrong way to approach it. But all i want to do here is have that detail fragment show up with populated TextViews. Im not really sure what I'm doing.
You could approach this by setting up a constructor in your DetailsFragment that you can pass in the textview info you want to show. In the example below, the data and invoice number are passed into the constructor. When the fragment is set up, this fragment is set up with the Parse object's data:
invoicesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
ParseObject object = adapter.getItem(i);
Fragment detailView = DetailsFragment.newInstance(object.getString("Date"),
object.getString("InvoiceNumber"));
// ...
}
});
Here's a portion of the DetailsFragment showing the new constructor as well as how you could use them in setting up your view:
// InvoicesFragment.java
public static class InvoicesFragment extends Fragment {
// ...
public static InvoicesFragment newInstance(String invoiceDate, String invoiceNumber) {
InvoicesFragment f = new InvoicesFragment();
Bundle args = new Bundle();
args.putString("invoiceDate", InvoiceDate);
args.putString("invoiceNumber", InvoiceNumber);
f.setArguments(args);
return f;
}
public String getInvoiceDate() {
return getArguments().getString("invoiceDate", "");
}
public String getInvoiceNumber() {
return getArguments().getString("invoiceNumber", "");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
RelativeLayout layout = (RelativeLayout) inflater.inflate(R.layout.fragment_invoices, container, false);
// Assign some TextView, ex: dateTextView
dateTextView.setText(getInvoiceDate());
return layout;
}
}