代码如下:-
产品片段:
public class ProductFragment extends Fragment implements TabLayout.OnTabSelectedListener, ViewPager.OnPageChangeListener {
private static final String PRODUCT_DATA = "product_data";
private TabLayout tabLayout;
private ViewPager viewPager;
NestedScrollView nestedScrollView;
//RecyclerView listView;
//ImageView ivHeader;
ProgressDialog pd;
Bundle bundle;
ViewPager viewPager1;
private LinearLayout pager_indicator;
public String DATA = "data";
public String PRODUCTS = "products";
//public String SPRODUCTS = "sproducts";
public String ID = "id";
public String NAME = "productName";
public String IMAGEURL = "productImg1";
public String DESCRIPTION = "description";
public String PRICE = "price";
public String DELIVERYTYPE = "deliverytype";
//String url = "https://chiraggohil.000webhostapp.com/product.php";
String url = "http://www.thinkdream.in/lunchbox2/product_api/getProductList";
String sliderImageUrl = "http://www.thinkdream.in/lunchbox2/assets/images/product/2.png";
ArrayList<Product> list = new ArrayList<>();
ArrayList<Product> sliderImagesList = new ArrayList<>();
private int dotsCount = 0;
private ImageView[] dots;
private static int CURRENT_PAGE = 0;
ViewPagerSliderAdapter viewPagerSliderAdapter;
ConnectivityManager cm;
NetworkInfo activeNetwork;
boolean isConnected;
//private boolean load = false;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.fragment_product, container, false);
viewPager1 = (ViewPager) v.findViewById(R.id.viewpager);
//listView = (RecyclerView) v.findViewById(R.id.gvProducts);
nestedScrollView = (NestedScrollView) v.findViewById(R.id.nestedSV);
pager_indicator = (LinearLayout) v.findViewById(R.id.viewPagerCountDots);
//nestedScrollView.setFillViewport(true);
//ivHeader = (ImageView) v.findViewById(R.id.ivHeader);
bundle = new Bundle();
tabLayout = (TabLayout) v.findViewById(R.id.tabLayout);
viewPager = (ViewPager) v.findViewById(R.id.pager);
viewPagerSliderAdapter = new ViewPagerSliderAdapter(getActivity(), sliderImagesList);
cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
activeNetwork = cm.getActiveNetworkInfo();
isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
if (savedInstanceState != null) {
sliderImagesList = savedInstanceState.getParcelableArrayList(PRODUCT_DATA);
viewPager1.setAdapter(viewPagerSliderAdapter);
viewPagerSliderAdapter.notifyDataSetChanged();
} else {
if (isConnected) {
new GetUrlData(getActivity()).execute();
} else {
Toast.makeText(getActivity(), "You are not connected to the internet!", Toast.LENGTH_SHORT).show();
}
}
tabLayout.addTab(tabLayout.newTab().setText("Pizza"));
tabLayout.addTab(tabLayout.newTab().setText("Sandwich"));
tabLayout.addTab(tabLayout.newTab().setText("Burger"));
Pager adapter = new Pager(getChildFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(this);
viewPager1.addOnPageChangeListener(this);
return v;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(PRODUCT_DATA, sliderImagesList);
}
@Override
public void onResume() {
super.onResume();
pager_indicator.removeAllViews();
//Picasso.with(getActivity()).load(sliderImageUrl).into(ivHeader);
}
@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) {
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
for (int i = 0; i < dotsCount; i++) {
dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));
}
if (position >= dotsCount) {
dots[0].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
} else {
dots[position].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
private class GetUrlData extends AsyncTask<Void, Void, Void> {
GetUrlData(Context context) {
pd = new MyCustomProgressDialog(context, R.style.NewDialog);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pd.setCancelable(false);
pd.show();
}
@Override
protected Void doInBackground(Void... voids) {
ServiceHandler sh = new ServiceHandler();
String result = sh.Getdata(url);
//list.clear();
sliderImagesList.clear();
if (result != null) {
try {
list.clear();
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray(DATA);
//JSONArray jsonArray = jsonObject1.getJSONArray(PRODUCTS);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject2 = jsonArray.getJSONObject(i);
String id = jsonObject2.getString(ID);
String name = jsonObject2.getString(NAME);
String imgpath = jsonObject2.getString(IMAGEURL);
String desc = jsonObject2.getString(DESCRIPTION);
String price = jsonObject2.getString(PRICE);
//String deliverytype = jsonObject2.getString(DELIVERYTYPE);
Product product = new Product();
product.setId(id);
product.setProductName(name);
product.setProductImage(imgpath);
product.setProductDescription(desc);
product.setProductPrice(price);
//list.add(product);
sliderImagesList.add(product);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
pd.dismiss();
// Picasso.with(getActivity()).load(sliderImageUrl).into(ivHeader);
if(isAdded()) {
viewPagerSliderAdapter = new ViewPagerSliderAdapter(getActivity(), sliderImagesList);
Log.e("slider",sliderImagesList.toString());
viewPager1.setAdapter(viewPagerSliderAdapter);
viewPagerSliderAdapter.notifyDataSetChanged();
slider();
setUiPageViewController();
}else {
Log.e("not added","not added");
}
}
}
private void slider() {
int NUM_PAGES = sliderImagesList.size();
final android.os.Handler handler = new android.os.Handler();
final Runnable runnable = new Runnable() {
@Override
public void run() {
CURRENT_PAGE = viewPager1.getCurrentItem();
if (CURRENT_PAGE == 2) {
CURRENT_PAGE = -1;
}
viewPager1.setCurrentItem(CURRENT_PAGE + 1, true);
}
};
Timer swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
@Override
public void run() {
handler.post(runnable);
}
}, 100, 4000);
}
private void setUiPageViewController() {
dotsCount = 3;
dots = new ImageView[dotsCount];
for (int i = 0; i < dotsCount; i++) {
dots[i] = new ImageView(getActivity());
dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
params.setMargins(4, 0, 4, 0);
pager_indicator.addView(dots[i], params);
}
dots[0].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
}
}
我不知道我错在哪里。我已经搜索了错误,甚至尝试了以下链接的解决方案:
Fragment MyFragment not attached to activity
我在SO上提出问题,但没有得到响应/答案。可能有一个小错误、语法/格式问题或重复问题,但我的案例可能与其他人的不同。
因此,请提供帮助并作出答复。
谢谢。
--编辑--
家庭活动:
public class HomeActivity extends AppCompatActivity implements View.OnClickListener {
DrawerLayout drawerLayout;
NavigationView navigationView;
Toolbar toolbar;
TextView tvActionTitle;
SessionManager sessionManager;
GPSTracker gps;
int i = 0;
private FrameLayout redCircle;
private TextView countTextView;
int cartcount = 0;
Menu menu;
LunchBoxDB lunchBoxDB;
private String uid;
SharedPreferences pref;
private int totalquantity = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
toolbar = (Toolbar) findViewById(R.id.toolbar);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.navigation);
tvActionTitle = (TextView) findViewById(R.id.tvActionTitle);
Typeface custom_font = Typeface.createFromAsset(getAssets(), "fonts/Quicksand_Bold_Oblique.otf");
tvActionTitle.setTypeface(custom_font);
setSupportActionBar(toolbar);
//getSupportActionBar().setDisplayShowTitleEnabled(false);
lunchBoxDB = new LunchBoxDB(this);
pref = getSharedPreferences("loginPref", Context.MODE_PRIVATE);
uid = pref.getString("id", null);
ProductFragment pf = new ProductFragment();
getFragmentManager().beginTransaction().replace(R.id.content_frame, pf).commit();
sessionManager = new SessionManager(this);
toolbar.setNavigationIcon(R.mipmap.ic_menu_white_24dp);
toolbar.setNavigationOnClickListener(this);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem item) {
Fragment frag = null;
int itemId = item.getItemId();
if (itemId == R.id.nav_home) {
drawerLayout.closeDrawers();
Intent i = new Intent(HomeActivity.this, HomeActivity.class);
startActivity(i);
HomeActivity.this.finish();
} else if (itemId == R.id.nav_profile) {
frag = new AccountFragment();
getFragmentManager().beginTransaction().replace(R.id.content_frame, frag).addToBackStack("Account").commit();
drawerLayout.closeDrawers();
} else if (itemId == R.id.nav_order) {
drawerLayout.closeDrawers();
OrdersFragment of = new OrdersFragment();
getFragmentManager().beginTransaction().replace(R.id.content_frame, of).addToBackStack("Orders").commit();
} else if (itemId == R.id.nav_store_locator) {
Intent i = new Intent(HomeActivity.this, LocationActivity.class);
startActivity(i);
drawerLayout.closeDrawers();
} else if (itemId == R.id.nav_logout) {
drawerLayout.closeDrawers();
sessionManager.logoutUser();
} else if (itemId == R.id.nav_help) {
drawerLayout.closeDrawers();
Intent i = new Intent(Intent.ACTION_DIAL);
i.setData(Uri.parse("tel:+918460765785"));
startActivity(i);
} else if (itemId == R.id.nav_corpinquiry) {
drawerLayout.closeDrawers();
CorpInquiryFragment crpf = new CorpInquiryFragment();
getFragmentManager().beginTransaction().replace(R.id.content_frame, crpf).addToBackStack("CorpInquiry").commit();
}
return false;
}
});
}
private void setNavigationDrawer() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
drawerLayout.openDrawer(GravityCompat.START);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.nav_drawer, menu);
final MenuItem alertMenuItem = menu.findItem(R.id.shopping_bag);
FrameLayout rootView = (FrameLayout) alertMenuItem.getActionView();
redCircle = (FrameLayout) rootView.findViewById(R.id.view_alert_red_circle);
countTextView = (TextView) rootView.findViewById(R.id.view_alert_count_textview);
rootView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onOptionsItemSelected(alertMenuItem);
}
});
badgeupdate();
return super.onCreateOptionsMenu(menu);
}
void badgeupdate() {
SQLiteDatabase db = lunchBoxDB.getReadableDatabase();
String query = "select sum(quantity) from cart where uid = " + uid;
Cursor c = db.rawQuery(query, null);
if (c != null && c.moveToFirst()) {
totalquantity = c.getInt(0);
}
c.close();
cartcount = totalquantity;
countTextView.setText(String.valueOf(cartcount));
redCircle.setVisibility((cartcount > 0) ? VISIBLE : GONE);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.shopping_bag) {
SharedPreferences pref = this.getSharedPreferences("couponPref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("discount", null);
editor.apply();
CartFragment cf = new CartFragment();
getFragmentManager().beginTransaction().replace(R.id.content_frame, cf, "CartFragment").addToBackStack(null).commit();
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
}/*else if(i==0){
Toast.makeText(this, "Press back again to exit!", Toast.LENGTH_SHORT).show();
i=1;
}*/ else {
//i=0;
super.onBackPressed();
}
}
@Override
protected void onResume() {
super.onResume();
gps = new GPSTracker(this);
}
@Override
public void onClick(View view) {
setNavigationDrawer();
}
}
致命异常:主进程:com.pisac.foodrestaurant,PID:29700 java.lang.IllegalStateException:Fragment ProductFragment{13525074}未附加到Android.app.Fragment.GetResources(Fragment.java:800)(com.pisac.foodrestaurant.ProductFragment.OnPageSelected(ProductFragment.OnPageSelected(ProductFragment.Java:149)(od.invoke(本机方法)在java.lang.reflect.Method.invoke(Method.java:372)在com.android.internal.os.zygoteInit$methodandargscaller.run(zygoteInit.java:1405)在com.android.internal.os.zygoteInit.main(zygoteInit.java:1200)
你的线路有问题
pd.dismiss();
在geturldata
的OnPostExecute
中。根据您在问题中提出的问题的答案,将其放在if(isAdded())
中。您的对话框使用活动的上下文。
编辑
@Override
public void onPageSelected(int position) {
if(!isAdded ())
return;
for (int i = 0; i < dotsCount; i++) {
dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));
}
if (position >= dotsCount) {
dots[0].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
} else {
dots[position].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
}
}
我有一个片段,基本上工作良好。在onResume方法中,当用户到达活动/片段时,我执行一个api调用以获取新的数据。 这个大部分时间都很好用。但是,当用户在update ui方法完成之前导航回父活动时,我遇到了一个问题。更新ui只是设置一些文本视图。 例如。当用户导航到活动和片段时,将调用上面的onResume。用户立即返回父活动。异步调用和更新ui尚未完成,我得到: 致命异常:主进程:com.p
这是我的碎片 drawable是ok的,也检查了,数据库项目,崩溃发生有时不是每次数据库更改
我的代码: 我添加了部分来模拟下载数据。中的代码是模拟使用。 当我在横向和纵向之间快速旋转屏幕时,我在代码处得到一个异常: java.lang.IllegalStateException:片段MyFragment{410F6060}未附加到活动 我认为这是因为在此期间创建了一个新的,并且在完成之前附加到了活动。中的代码调用未附加的。
如果有人能帮我摆脱困境,请告诉我。多谢了。
我正在创建一个使用FragmentStatePagerAdapter的ViewPager活动。但当我试图旋转我的手机时,它崩溃了,并出现错误“片段尚未附加”。 这是我的适配器: 在我的活动onCreate中,我调用了SalesPagingAdapter=new SalesPagingAdapter(PreMainActivitySales.this,getSupportFragmentManage
代码:-