当按下后退按钮活动没有完成

时间:2017-06-28 07:36:40

标签: java android

我的应用程序包含两个活动,第一个活动使用volley从Web加载数据,成功加载数据后启动第二个活动,第二个活动包含动态选项卡和查看分页器。我的问题是当我从第二个活动按下后退按钮没有完成活动但再次重新启动第二个活动时,按下十次后退按钮即我的标签计数为10时,它将完成,任何人都可以帮我解决这个问题。

First Actvity,SplashActivity.java

public class SplashActivity extends AppCompatActivity {

private static final String HOME_URL = "http://sampleurl.com/beta/Mobile_controller";
public static ArrayList<CategoryModel> categories;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash);
    getCategories();
}

private void getCategories() {
    categories = new ArrayList<>();
    StringRequest request = new StringRequest(Request.Method.POST, HOME_URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                JSONObject object = new JSONObject(response);
                JSONArray categoryJsonArray = object.getJSONArray("category");
                for (int i = 0; i < categoryJsonArray.length(); i++) {
                    CategoryModel model = new CategoryModel();
                    JSONObject cat = categoryJsonArray.getJSONObject(i);
                    model.setCategoryID(cat.getString("category_id"));
                    model.setCategoryName(cat.getString("category_name"));
                    categories.add(model);
                    startActivity(new Intent(getApplicationContext(), MainActivity.class));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getApplicationContext(), String.valueOf("error : " + error.getMessage()),Toast.LENGTH_SHORT).show();
        }
    });
    RequestQueue queue = Volley.newRequestQueue(SplashActivity.this);
    queue.add(request);
}

}

第二项活动MainActivity.java

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

MediaController mediaController;

private ArrayList<CategoryModel> categoryList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.tb_home);
    setSupportActionBar(toolbar);

    categoryList = SplashActivity.categories;

    NavigationView navDrawer = (NavigationView) findViewById(R.id.navigation_home);
    navDrawer.setNavigationItemSelectedListener(this);
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout_home);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.app_name, R.string.app_name);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tbl_home);
    for (int i = 0; i < categoryList.size(); i++) {
        tabLayout.addTab(tabLayout.newTab().setText(categoryList.get(i).getCategoryName()));
    }
    final ViewPager viewPager = (ViewPager) findViewById(R.id.vp_home_content);
    SwipingTabsAdapter swipingTabsAdapter = new SwipingTabsAdapter(getSupportFragmentManager(), categoryList, tabLayout.getTabCount());
    viewPager.setAdapter(swipingTabsAdapter);
    viewPager.setOffscreenPageLimit(3);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    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) {

        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.menu_option_home, menu);
    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    SearchView searchView = (SearchView) menu.findItem(R.id.menu_option_search).getActionView();
    if (searchView != null) {
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                Toast.makeText(getApplicationContext(), newText, Toast.LENGTH_SHORT).show();
                return true;
            }
        });
    }
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.menu_option_account:
            Toast.makeText(getApplicationContext(), "account", Toast.LENGTH_SHORT).show();
            break;
    }
    return true;
}

@Override
public void onBackPressed() {
    super.onBackPressed();
}

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    return false;
}

}

查看寻呼机适配器

public class SwipingTabsAdapter extends FragmentStatePagerAdapter {

private int tabs;
private ArrayList<CategoryModel> categoryList;

public SwipingTabsAdapter(FragmentManager fm, ArrayList<CategoryModel> categories, int tabCounts) {
    super(fm);
    this.categoryList = categories;
    this.tabs = tabCounts;
}

@Override
public Fragment getItem(int position) {
    /*switch (position) {
        case 0:
            return new NewsCategoriesFragment();
        case 1:
            return new NewsCategoriesFragment();
        default:
            return new NewsCategoriesFragment();
    }*/
    return NewsCategoriesFragment.newInstance(Integer.parseInt(categoryList.get(position).getCategoryID()));
}

@Override
public int getCount() {
    return tabs;
}

}

我的片段

public class NewsCategoriesFragment extends Fragment {

private ArrayList<SliderModel> sliderNews;
private SliderNewsAdapter sliderNewsAdapter;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_new_categories, container, false);
    Button button = (Button) view.findViewById(R.id.button);
    Bundle bundle = getArguments();
    int id = bundle.getInt("id");
    getNews(id);
    ViewPager viewPager = (ViewPager) view.findViewById(R.id.vp_slider_news);
    sliderNewsAdapter = new SliderNewsAdapter(getContext(), sliderNews);
    viewPager.setAdapter(sliderNewsAdapter);
    button.setText(String.valueOf(id));
    return view;
}


public static Fragment newInstance(int id) {
    NewsCategoriesFragment fragment = new NewsCategoriesFragment();
    Bundle bundle = new Bundle();
    bundle.putInt("id", id);
    fragment.setArguments(bundle);
    return fragment;
}

private void getNews(final int categoryId) {
    sliderNews = new ArrayList<>();
    StringRequest request = new StringRequest(Request.Method.POST, NEWS_URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                JSONObject object = new JSONObject(response);
                JSONArray sliderNewsJsonArray = object.getJSONArray("slider_news");
                for (int i = 0; i < sliderNewsJsonArray.length(); i++) {
                    SliderModel model = new SliderModel();
                    JSONObject data = sliderNewsJsonArray.getJSONObject(i);
                    model.setNewsThumbImg(data.getString("news_thump_image"));
                    sliderNews.add(model);
                }
                sliderNewsAdapter.notifyDataSetChanged();
            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(getContext(), "JSON Exception", Toast.LENGTH_SHORT).show();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getContext(), String.valueOf("error "+ error.getMessage()), Toast.LENGTH_SHORT).show();
        }
    }){

        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> data = new HashMap<>();
            data.put("id", String.valueOf(categoryId));
            return data;
        }
    };
    RequestQueue queue = Volley.newRequestQueue(getContext());
    queue.add(request);
}

}

3 个答案:

答案 0 :(得分:0)

问题是你把你的startActivity放在for循环中,把启动活动放在Splashactiivty getCategories中的for循环之后,它会正常工作

改变这一点,

try {
                JSONObject object = new JSONObject(response);
                JSONArray categoryJsonArray = object.getJSONArray("category");
                for (int i = 0; i < categoryJsonArray.length(); i++) {
                    CategoryModel model = new CategoryModel();
                    JSONObject cat = categoryJsonArray.getJSONObject(i);
                    model.setCategoryID(cat.getString("category_id"));
                    model.setCategoryName(cat.getString("category_name"));
                    categories.add(model);
                    startActivity(new Intent(getApplicationContext(), MainActivity.class));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

try {
                JSONObject object = new JSONObject(response);
                JSONArray categoryJsonArray = object.getJSONArray("category");
                for (int i = 0; i < categoryJsonArray.length(); i++) {
                    CategoryModel model = new CategoryModel();
                    JSONObject cat = categoryJsonArray.getJSONObject(i);
                    model.setCategoryID(cat.getString("category_id"));
                    model.setCategoryName(cat.getString("category_name"));
                    categories.add(model);

                }
startActivity(new Intent(getApplicationContext(), MainActivity.class));
            } catch (JSONException e) {
                e.printStackTrace();
            }

答案 1 :(得分:0)

在第二个活动中覆盖为
    @覆盖     public void onBackPressed(){        完();     }

答案 2 :(得分:0)

您实际上不需要启动之前活动的意图。 Android有一个名为 Back Stack 的东西,它包含以前在堆栈数据结构中启动的活动。你可以重写onBackPressed()方法来完成它。

@Override
public void onBackPressed(){
        this.finish();
}

还要注意启动意图,因为 NewTask 可以帮助您摆脱现有的Backstack并拥有自己的Backstack。