I have an EditText view in my MainActivity that the user can input a url. This MainActivity also contains a fragment which will hold a WebView.
I have it set up so that when the fragment is displayed the url will load in the WebView. However I don't know how I can pass the String to the Fragment?
Below is the Main Activity code:
public class MainActivity extends FragmentActivity {
Button goBtn;
EditText urlInput;
String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
goBtn = (Button)findViewById(R.id.button1);
urlInput = (EditText)findViewById(R.id.editText1);
goBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
url = "http://"+urlInput.getText().toString(); //THIS TO FRAGMENT!
Toast.makeText(v.getContext(), "Search:" + url, Toast.LENGTH_SHORT).show();
}
});
and this is the fragment code:
WebView webDisplay;
String url;
AsyncHttpClient client;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.frag1_layout, container, false);
urlDisplay = (TextView)v.findViewById(R.id.textView1);
webDisplay = (WebView)v.findViewById(R.id.webView1);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//url = "http://"+this.getActivity() ???
client = new AsyncHttpClient();
client.get(url, new AsyncHttpResponseHandler(){
#Override
public void onSuccess(String response) {
Toast.makeText(getActivity(), "Success!", Toast.LENGTH_SHORT).show();
webDisplay.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}});
webDisplay.loadUrl(url);
}
});
The value I am concerned about it the String URL variable in MainActivity.java.
The transaction of the fragments is controlled by a class TabFragment.
public class TabFragment extends Fragment {
private static final int TAB1_STATE = 0x1;
private static final int TAB2_STATE = 0x2;
private int mTabState;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_tab, container, false);
//References to buttons in layout file
Button tabBtn1 = (Button)v.findViewById(R.id.tabBtn1);
Button tabBtn2 = (Button)v.findViewById(R.id.tabBtn2);
//add listener to buttons
tabBtn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
//Action to perform when Tab 1 clicked...
goToTab1View();
}
});
tabBtn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Action to perform when Tab 2 clicked...
goToTab2View();
}
});
return v;
}
//Tab action functions.
protected void goToTab1View() {
if(mTabState != TAB1_STATE){
mTabState = TAB1_STATE;
FragmentManager fm = getFragmentManager();
if(fm!= null){
//Perform fragment transaction
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment_content, new FragTab1());
ft.commit();
}
}
}
protected void goToTab2View() {
if(mTabState != TAB2_STATE){
mTabState = TAB2_STATE;
FragmentManager fm = getFragmentManager();
if(fm!= null){
//Perform fragment transaction
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment_content, new FragTab2());
ft.commit();
}
}
}
Or create Bundle and set it using method fragment.setArguments(myBundle);
This answer is in case the fragment already exists
You can define a public method in your fragment. Something like:
public void setString(final String str) { //... }
After that make your activity to implement OnClickListener interfave. And when the button is pressed just type something like that:
public void onClick(View view) {
// Form url...
((YourWebViewFragment) getFragmentManager().findFragmentById(fragments_id)).setString(url);
}
Related
I am trying to do restoring the fragment view state values(text view,..etc) when back from second fragment in android bottom navigation view.
MyActivity.java
public class LandingPage extends AppCompatActivity implements ProductFragment.AddToCart {
Fragment fragment;
TextView txtCart;
Button btnCart;
ItemData itemData;
ArrayList<ItemData> itemDataList;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
fragment = new ProductFragment();
loadFragment(fragment);
return true;
case R.id.nav_profile:
fragment = new ReportsFragment();
loadFragment(fragment);
return true;
case R.id.nav_logout:
LogOut();
return true;
}
return true;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_landing_page);
txtCart = findViewById(R.id.txt_cart);
btnCart = findViewById(R.id.btn_cartImg);
itemDataList = new ArrayList<>();
BottomNavigationView bottomNavigationView = findViewById(R.id.navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
loadFragment(new ProductFragment());
}
private void loadFragment(Fragment fragment) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.commit();
}
}
ProductFragment.java
public class ProductFragment extends Fragment {
private OnFragmentInteractionListener mListener;
Button btnCart1,btnCart2,btnCart3;
AddToCart addToCart;
TextView txtItem1Des,txtItem1Price,txtItem2Des,txtItem2Price,txtItem3Des,txtItem3Price;
Button btnCart1Inc,btnCart1Dec,btnCart2Inc,btnCart2Dec,btnCart3Inc,btnCart3Dec;
TextView cart1txt,cart2txt,cart3txt;
String itemDes,itemPrice,itemImg,itemCount;
int quantity1,quantity2,quantity3;
public ProductFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_product, container, false);
btnCart1 = view.findViewById(R.id.cart1);
txtItem1Des = view.findViewById(R.id.cart1_desc);
txtItem1Price = view.findViewById(R.id.cart1_price);
btnCart1Inc = view.findViewById(R.id.cart1Inc);
btnCart1Dec = view.findViewById(R.id.cart1Dec);
cart1txt = view.findViewById(R.id.cart1txt);
btnCart2 = view.findViewById(R.id.cart2);
txtItem2Des = view.findViewById(R.id.cart2_desc);
txtItem2Price = view.findViewById(R.id.cart2_price);
btnCart2Inc = view.findViewById(R.id.cart2Inc);
btnCart2Dec = view.findViewById(R.id.cart2Dec);
cart2txt = view.findViewById(R.id.cart2txt);
btnCart3 = view.findViewById(R.id.cart3);
txtItem3Des = view.findViewById(R.id.cart3_desc);
txtItem3Price = view.findViewById(R.id.cart3_price);
btnCart3Inc = view.findViewById(R.id.cart3Inc);
btnCart3Dec = view.findViewById(R.id.cart3Dec);
cart3txt = view.findViewById(R.id.cart3txt);
quantity1 = Integer.parseInt(cart1txt.getText().toString());
quantity2 = Integer.parseInt(cart2txt.getText().toString());
quantity3 = Integer.parseInt(cart3txt.getText().toString());
buttonInitialization();
addingToCart();
return view;
}
private void addingToCart() {
btnCart1Dec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(quantity1 <= 1){
btnCart1.setVisibility(View.VISIBLE);
btnCart1Dec.setVisibility(View.INVISIBLE);
btnCart1Inc.setVisibility(View.INVISIBLE);
cart1txt.setVisibility(View.INVISIBLE);
addToCart.removeItemFromCart(1);
}else {
quantity1 = quantity1-1;
cart1txt.setText(String.valueOf(quantity1));
addToCart.itemCount(cart1txt.getText().toString(),"1");
}
}
});
btnCart1Inc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
quantity1 = quantity1+1;
cart1txt.setText(String.valueOf(quantity1));
addToCart.itemCount(cart1txt.getText().toString(),"1");
}
});
btnCart2Dec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(quantity2 <= 1){
btnCart2.setVisibility(View.VISIBLE);
btnCart2Dec.setVisibility(View.INVISIBLE);
btnCart2Inc.setVisibility(View.INVISIBLE);
cart2txt.setVisibility(View.INVISIBLE);
addToCart.removeItemFromCart(2);
}else {
quantity2 = quantity2-1;
cart2txt.setText(String.valueOf(quantity2));
addToCart.itemCount(cart2txt.getText().toString(),"2");
}
}
});
btnCart2Inc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
quantity2 = quantity2+1;
cart2txt.setText(String.valueOf(quantity2));
addToCart.itemCount(cart2txt.getText().toString(),"2");
}
});
btnCart3Dec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(quantity3 <= 1){
btnCart3.setVisibility(View.VISIBLE);
btnCart3Dec.setVisibility(View.INVISIBLE);
btnCart3Inc.setVisibility(View.INVISIBLE);
cart3txt.setVisibility(View.INVISIBLE);
addToCart.removeItemFromCart(3);
}else {
quantity3 = quantity3-1;
cart3txt.setText(String.valueOf(quantity3));
addToCart.itemCount(cart3txt.getText().toString(),"3");
}
}
});
btnCart3Inc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
quantity3 = quantity3+1;
cart3txt.setText(String.valueOf(quantity3));
addToCart.itemCount(cart3txt.getText().toString(),"3");
}
});
}
private void buttonInitialization() {
btnCart1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemImg = "";
itemPrice = txtItem1Price.getText().toString().trim();
itemDes = txtItem1Des.getText().toString().trim();
itemCount = cart1txt.getText().toString().trim();
addToCart.cartCount("",itemPrice,itemDes,itemCount,"1");
btnCart1.setVisibility(View.INVISIBLE);
btnCart1Dec.setVisibility(View.VISIBLE);
btnCart1Inc.setVisibility(View.VISIBLE);
cart1txt.setVisibility(View.VISIBLE);
}
});
btnCart2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemImg = "";
itemPrice = txtItem2Price.getText().toString().trim();
itemDes = txtItem2Des.getText().toString().trim();
itemCount = cart2txt.getText().toString().trim();
addToCart.cartCount("",itemPrice,itemDes,itemCount,"2");
btnCart2.setVisibility(View.INVISIBLE);
btnCart2Dec.setVisibility(View.VISIBLE);
btnCart2Inc.setVisibility(View.VISIBLE);
cart2txt.setVisibility(View.VISIBLE);
}
});
btnCart3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemImg = "";
itemPrice = txtItem3Price.getText().toString().trim();
itemDes = txtItem3Des.getText().toString().trim();
itemCount = cart3txt.getText().toString().trim();
addToCart.cartCount("",itemPrice,itemDes,itemCount,"3");
btnCart3.setVisibility(View.INVISIBLE);
btnCart3Dec.setVisibility(View.VISIBLE);
btnCart3Inc.setVisibility(View.VISIBLE);
cart3txt.setVisibility(View.VISIBLE);
}
});
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
addToCart = (AddToCart) context;
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
public interface AddToCart{
void cartCount(String item_img,String item_price,String item_desc,String item_count,String item_pos);
void removeItemFromCart(int removeItem);
void itemCount(String itemCount,String position);
}
}
Here in ProductFragment iam going to add values to text view. When i was coming from ReportFragment the view values are going to be cleared in ProductFragment.
I would consider doing that in two steps:
save fragment instance instead of re-creating a new one every time
private ProductFragment productFragment;
private ReportsFragment reportsFragment;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
if(productFragment == null)
productFragment = new ProductFragment();
loadFragment(productFragment);
break;
case R.id.nav_profile:
if(reportsFragment == null)
reportsFragment = new ReportsFragment();
loadFragment(reportsFragment);
break;
case R.id.nav_logout:
LogOut();
return true;
}
return true;
}
};
referring to this question/answer, you should implement in your fragment both void onSaveInstanceState(final Bundle outState) and void onActivityCreated(Bundle savedInstanceState)
In that way you will surely keep the instance of your fragment instead of creating a new one every time (new MyFragment() will always re-create it). In addition, saving your views state in onSaveInstanceState and restoring it in your onActivityCreate, will allow you to keep your views/values.
I wrote that by hand without a compiler, so it might not be perfect.
let me know if you need further information.
Good luck
I am using this solution and it works for me.
You should see my detailed answer to a similar question. I hope it will solve your problem.
I have an activity "MainActivity" that contains two fragments. Fragment1 has a EditText and a button. When the user presses the button the text inside the EditText will be sent to Fragment2 which only has a TextView. But I can't quite figureout how to send the text from EditText in Fragment1 to TextView in Fragment2. If someone could help? Appreciated. Thanks
Fragment1
package org.pctechtips.myfragmentapp;
/**
* Created by george on 5/16/17.
*/
public class ButtonFragment extends Fragment {
Button bt;
EditText editText;
TextView txtView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.button_fragment,
container, false);
txtView = (TextView) view.findViewById(R.id.textView_fragment1);
editText = (EditText) view.findViewById(R.id.editText_fragment1);
bt = (Button) view.findViewById(R.id.button_fragment1);
bt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
buttonClicked(v);
}
});
return view;
}
public void buttonClicked (View view) {
.onButtonClick(edittext.getText().toString());
}
}
MainActivity
package org.pctechtips.myfragmentapp;
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*fragments 1 section*/
FragmentManager fm1 = getFragmentManager();
FragmentTransaction ft1 = fm1.beginTransaction();
ButtonFragment bf = new ButtonFragment();
ft1.add(R.id.button_fragment1, bf);
ft1.commit();
/*Fragment 2 section*/
FragmentManager fm2 = getFragmentManager();
FragmentTransaction ft2 = fm2.beginTransaction();
TextviewFragment tf = new TextviewFragment();
ft2.add(R.id.textView_fragment2, tf);
ft2.commit();
}
}
Fragment2
public class TextviewFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.text_fragment, container, false);
}
}
The quick and easy answer is to call getView().findViewById() from the activity (as shown below). The more proper approach is to give your fragments an interface that gets and retrieves the text. Below is the code for the quick and easy method, but when you create a fragment in Android studio it shows you how to do the more proper interface approach.
package org.pctechtips.myfragmentapp;
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*fragments 1 section*/
FragmentManager fm1 = getFragmentManager();
FragmentTransaction ft1 = fm1.beginTransaction();
ButtonFragment bf = new ButtonFragment();
ft1.add(R.id.button_fragment1, bf);
ft1.commit();
/*Fragment 2 section*/
FragmentManager fm2 = getFragmentManager();
FragmentTransaction ft2 = fm2.beginTransaction();
TextviewFragment tf = new TextviewFragment();
ft2.add(R.id.textView_fragment2, tf);
ft2.commit();
EditText et = (EditText) ft1.getView().findViewById(YOUR_EDITTEXT_ID);
Button button = (Button) ft1.getView().findViewById(YOUR_BUTTON_ID);
TextView tv = (TextView) ft2.getView().findViewById(YOUR_TEXTVIEW_ID);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tv.setText(et.getText();)
}
});
}
You can do it by several ways. For example via Activity like in Official Docs. But, I'm prefer send broadcast messages via LocalBroadcastManager like in this answer of war_Hero:
In Sending Fragment(Fragment B - Your ButtonFragment)
public class FragmentB {
private void sendMessage() {
Intent intent = new Intent("custom-event-name");
intent.putExtra("message", "your message");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}
And in the Message to be Received Fragment(FRAGMENT A - Your TextviewFragment)
public class FragmentA {
#Override
public void onCreate(Bundle savedInstanceState) {
...
// Register receiver
LocalBroadcastManager.getInstance(this).registerReceiver(receiver,
new IntentFilter("custom-event-name"));
}
// This will be called whenever an Intent with an action named "custom-event-name" is broadcasted.
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("message");
}
};
}
And don't forget to unregister receiver:
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
}
I wanted to pass data from Activity to Currently loaded fragment on button click.
For that i created Interface and define into activity and implement in interface but couldn't get response in fragment.
I Needed output whenever button clicks fire in Activity.
Here is my code. Please help me to resolve this.
Inteface
public interface Click {
void onClick(String msg);
}
Main Actvity
public class MainActivity extends FragmentActivity {
DrawerLayout dlMain;
Button btnClick;
Click click;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentOne fragmentOne = new FragmentOne();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.flContainer, fragmentOne,"FragmentOne");
ft.commit();
click = (Click) getSupportFragmentManager().findFragmentByTag("FragmentOne").;
dlMain = (DrawerLayout) findViewById(R.id.dlMain);
btnClick = (Button) findViewById(R.id.btnClick);
btnClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("Btn Click", "click");
click.onClick("Button Clicked!");
}
});
}
}
FragmentOne
public class FragmentOne extends Fragment implements Click {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
return view;
}
#Override
public void onClick(String msg) {
Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
}
}
But there i am getting error in MainActivity
This is my Error Logs.
05-09 10:30:49.092 19101-19101/com.psk.interfacetest
E/Btn Click: click
05-09 10:30:49.095 19101-19101/com.psk.interfacetest E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.psk.interfacetest, PID: 19101
java.lang.NullPointerException
at com.psk.interfacetest.MainActivity$1.onClick(MainActivity.java:37)
at android.view.View.performClick(View.java:4471)
at android.view.View$PerformClick.run(View.java:18778)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5345)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
Your case, fragment replacing can not finish. So you should register interface from fragment.You can examine this code.
public class AActivity extends FragmentActivity {
Click click;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentOne fragmentOne = new FragmentOne();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.flContainer, fragmentOne,"FragmentOne");
ft.commit();
DrawerLayout dlMain = (DrawerLayout)findViewById(R.id.dlMain);
Button btnClick = (Button) findViewById(R.id.btnClick);
btnClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("Btn Click", "click");
click.onClick("Button Clicked!");
}
});
}
public void setCallback(Click callback) {
this.click=callback;
}
public interface Click {
void onClick(String msg);
}
}
public class AFragment extends Fragment implements AActivity.Click {
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (getActivity() != null) {
((AActivity)getActivity()).setCallback(this);
}
}
#Override
public void onClick(String msg) {
}
}
try this
public class MainActivity extends FragmentActivity {
DrawerLayout dlMain;
Button btnClick;
Click click;
private FragmentOne fragmentOne;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentOne = new FragmentOne();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.imageTitleTextView, fragmentOne, "FragmentOne");
ft.commit();
//click = (Click) getSupportFragmentManager().findFragmentByTag("FragmentOne");
dlMain = (DrawerLayout) findViewById(R.id.dlMain);
btnClick = (Button) findViewById(R.id.btnClick);
btnClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("Btn Click", "click");
fragmentOne.listener.onClick("Button Clicked!");
}
});
}
}
public class FragmentOne extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
return view;
}
Click listener = new Click() {
#Override
public void onClick(String msg) {
Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
}
};
}
I want to know how to stop running thread and asyncTask of fragment safely on android.
here is my code:
public class MainActivity extends FragmentActivity {
public Fragment mFragment;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
Button btn_next = (Button) findViewById(R.id.button_next);
btn_next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
((FragmentOne)mFragment).infoThread.interrupt();
}
});
Intent intent = getIntent();
String start_fragment = intent.getStringExtra("start_fragment");
onShowFragment(start_fragment);
}
public void onShowFragment(String select_fragment) {
Fragment fr = null;
switch (select_fragment) {
case "fragment1":
fr = new FragmentOne();
break;
case "gragment2":
fr = new FragmentTwo();
break;
}
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_place, fr);
ft.commit();
}
}
public class FragmentOne extends Fragment {
public Thread infoThread;
public View view_one;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view_one = inflater.inflate(R.layout.fragment_one, container, false);
onGetInfo();
return view_one;
}
public void onGetInfo() {
infoThread= new Thread(new Runnable() {
#Override
public void run() {
String response_info = HTTPUtils.HTTPPost(Global.USER_URL,
"name", "abc",
"password", "1234");
processGetInfo(response_info);
}
});
infoThread.start();
}
}
in here, when click btn_next button, FATAL EXCEPTION ERROR occur.
please help me.
try to use:
infoThread.stop()
instead of:
infoThread.interrupt();
You are never initialising mFragment with a value.
Add mFragment = fr; to onShowFragment
But, you're going to have a whole load of different issues if you carry on down this path. You should consider a more robust framework than performing http requests in threads spawned from a Fragment's onCreateView method.
I'm new to programming .
I make an app that contains 3 Tabs with viewpager. 1st tab is a list of Button with their respective link. 2nd Tab is a WebView that will load url passed from the 1st tab when the users clicked on the link. 3rd tab is my Download Manager.
This is my MainActivity:
public class MainActivity extends SherlockFragmentActivity{
ActionBar mActionBar;
Button button;
ViewPager mPager;
Tab tab;
String TabFragmentB;
public void setTabFragmentB(String t){
TabFragmentB = t;
}
public String getTabFragmentB(){
return TabFragmentB;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mActionBar = getSupportActionBar();
// Hide Actionbar Icon
mActionBar.setDisplayShowHomeEnabled(false);
// Hide Actionbar Title
mActionBar.setDisplayShowTitleEnabled(false);
// Create Actionbar Tabs
mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
//For ViewPager
mPager = (ViewPager) findViewById(R.id.pager);
//Activate FragmentManger
FragmentManager fm= getSupportFragmentManager();
ViewPager.SimpleOnPageChangeListener ViewPagerListener = new ViewPager.SimpleOnPageChangeListener(){
#Override
public void onPageSelected(int position){
super.onPageSelected(position);
mActionBar.setSelectedNavigationItem(position);//find the viewPager Potision
}
};
mPager.setOnPageChangeListener(ViewPagerListener);
// Locate the adapter class called ViewPagerAdapter.java
ViewPagerAdapter viewpageradapter = new ViewPagerAdapter(fm);
// Set the View Pager Adapter into ViewPager
mPager.setAdapter(viewpageradapter);
// Capture tab button clicks
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// Pass the position on tab click to ViewPager
mPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
};
// Create first Tab
tab = mActionBar.newTab().setIcon(R.drawable.button_home).setTabListener(tabListener);
mActionBar.addTab(tab);
// Create second Tab
tab = mActionBar.newTab().setIcon(R.drawable.button_browse).setTabListener(tabListener);
mActionBar.addTab(tab);
// Create third Tab
tab = mActionBar.newTab().setIcon(R.drawable.button_downloads).setTabListener(tabListener);
mActionBar.addTab(tab);
}
}
My FragmentTab1:
public class FragmentTab1 extends SherlockFragment implements OnClickListener{
FragmentTab2 fTab2;
ViewPager viewPager;
WebView webview;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.home, container, false);
viewPager = (ViewPager) getActivity().findViewById(R.id.pager);
webview = (WebView) view.findViewById(R.id.webView1);
view.findViewById(R.id.Button01).setOnClickListener(this);
view.findViewById(R.id.Button02).setOnClickListener(this);
view.findViewById(R.id.Button03).setOnClickListener(this);
view.findViewById(R.id.Button04).setOnClickListener(this);
view.findViewById(R.id.Button05).setOnClickListener(this);
return view;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
setUserVisibleHint(true);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.Button01:
String urlToBeSend = " http://google.com";
String TabOfFragmentB = ((MainActivity)getActivity()).getTabFragmentB();
FragmentTab2 fragmentB = (FragmentTab2)getActivity().getSupportFragmentManager().findFragmentByTag(TabOfFragmentB);
fragmentB.b_updateText(urlToBeSend);
Toast.makeText(getSherlockActivity(), "url to be send = " +urlToBeSend, Toast.LENGTH_LONG).show();
viewPager.setCurrentItem(1);
break;
case R.id.Button02:
String urlToBeSend2 = " http://facebook.com";
String TabOfFragmentB2 = ((MainActivity)getActivity()).getTabFragmentB();
FragmentTab2 fragmentB2 = (FragmentTab2)getActivity().getSupportFragmentManager().findFragmentByTag(TabOfFragmentB2);
fragmentB2.b_updateText(urlToBeSend2);
Toast.makeText(getSherlockActivity(), "url to be send = " +urlToBeSend2, Toast.LENGTH_LONG).show();
viewPager.setCurrentItem(1);
break;
case R.id.Button03:
viewPager.setCurrentItem(1);
break;
case R.id.Button04:
viewPager.setCurrentItem(1);
break;
case R.id.Button05:
viewPager.setCurrentItem(1);
break;
default:
break;
}
}
}
For My FragmentTab2:
public class FragmentTab2 extends SherlockFragment {
private static WebView webview;
private ProgressBar progress;
String homeUrl="http://new3gpmovies.com/";
private int urlIndex=0;
String a_url;
TextView b_received;
ViewPager viewpager;
public void b_updateText(String t){
b_received.setText(t);
a_url = t;
}
public FragmentTab2(){
}
#SuppressLint("SetJavaScriptEnabled")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.webview, container, false);
String myTag = getTag();
((MainActivity)getActivity()).setTabFragmentB(myTag);
b_received = (TextView) view.findViewById(R.id.textView1);
ImageView backward = (ImageView) view.findViewById(R.id.backward);
ImageView forward = (ImageView) view.findViewById(R.id.forward);
backward.setOnClickListener(new OnClickListener(){
public void onClick(View view){
if (webview.canGoBack()){
webview.goBack();
}
}
});
forward.setOnClickListener(new OnClickListener(){
public void onClick(View view){
if (webview.canGoForward()){
webview.goForward();
}
}
});
webview = (WebView) view.findViewById(R.id.webView1);
webview.setWebChromeClient(new MyWebChromeClient());
webview.setWebViewClient(new MyWebViewClient());
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
progress = (ProgressBar) view.findViewById(R.id.progressBar1);
progress.setMax(100);
if (a_url != null){
webview.loadUrl(a_url);
}else if (a_url == null){
webview.loadUrl(homeUrl);
}
if (progress.getProgress() == 100){
FragmentTab2.this.progress.setProgress(0);
}
return view;
}
private class MyWebViewClient extends WebViewClient{
#SuppressLint({ "InlinedApi", "NewApi" })
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
boolean value = true;
if (url.endsWith(".3gp") || url.endsWith(".mp4")){
Intent downloadIntent = new Intent("com.nanoidea.download.services.IDownloadService");
downloadIntent.putExtra(MyIntents.TYPE, MyIntents.Types.ADD);
downloadIntent.putExtra(MyIntents.URL, Utils.url[urlIndex]);
getActivity().startService(downloadIntent);
urlIndex++;
if (urlIndex >= Utils.url.length) {
urlIndex = 0;
}
value=false;
}
if(value){
view.loadUrl(url);
}
return value;
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
webview.loadUrl("file:///android_asset/failedPage.html");
}
}
public String getFileName(String url) {
String filenameWithoutExtension = "";
if (url.endsWith("3gp")){
filenameWithoutExtension = String.valueOf(System.currentTimeMillis()
+ ".3gp");
}else if (url.endsWith(".mp4")){
filenameWithoutExtension = String.valueOf(System.currentTimeMillis()
+ ".mp4");
}
return filenameWithoutExtension;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
setUserVisibleHint(true);
}
private class MyWebChromeClient extends WebChromeClient{
#Override
public void onProgressChanged(WebView view, int newProgress){
FragmentTab2.this.setValue(newProgress);
super.onProgressChanged(view, newProgress);
}
}
public void setValue(int progress){
this.progress.setProgress(progress);
}
public static boolean canGoBack(){
return webview.canGoBack();
}
public static void goBack(){
webview.goBack();
}
}
Question:
Why when i click on the link from the 1st tab the second tab doesn't change? even if the 2nd tab received the string url from the 1st tab? any idea? Please guide me.