How to use onOptionsItemSelected with Single Activity having multiple fragments - android

The problem i am facing is as i set setDisplayHomeUpAsEnabled(true), on clicking back button onOptionsItemSelected dosent not get called.I doubt if my manifest file is correct.Below i am putting my manifest file.Please suggest .Thank you.
MANIFEST FILE
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.propelbit.jaydeepsaress">
<uses-permission android:name="android.permission.INTERNET" />
<!-- Include following permission if you want to cache images on SD card -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:name="com.propelbit.jaydeepsaress.JaydeepSarees"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".ui.activity.HomeActivity"
android:parentActivityName=".ui.activity.HomeActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.propelbit.jaydeepsaress.ui.activity.HomeActivity"/>
</activity>
</application>
</manifest>
Home Activity
package com.propelbit.jaydeepsaress.ui.activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.propelbit.jaydeepsaress.R;
import com.propelbit.jaydeepsaress.ui.fragment.HomeFragment;
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
public ActionBarDrawerToggle toggle;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
if (savedInstanceState == null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
toggle.setDrawerIndicatorEnabled(true);
ft.replace(R.id.content_frame, new HomeFragment());
ft.commit();
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
FragmentManager fm = getSupportFragmentManager();
int backStackEntryCount = fm.getBackStackEntryCount();
Log.d("BSEC",backStackEntryCount+"");
if (backStackEntryCount > 0) {
fm.popBackStack();
if (fm.getBackStackEntryCount() > 0) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toggle.setDrawerIndicatorEnabled(false);
} else {
//drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
// Display the Drawer Icon
toggle.setDrawerIndicatorEnabled(true);
}
} else {
//drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
// Display the Drawer Icon
toggle.setDrawerIndicatorEnabled(true);
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
toggle.onConfigurationChanged(newConfig);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
toggle.syncState();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d("TAG",item.getItemId()+"");
switch (item.getItemId()) {
case android.R.id.home:
// Do nothing handled by fragment.
return false;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Home Fragment
package com.propelbit.jaydeepsaress.ui.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import com.propelbit.jaydeepsaress.R;
import com.propelbit.jaydeepsaress.ui.activity.HomeActivity;
/**
* Created by ankit on 05/09/16.
*/
public class HomeFragment extends Fragment implements View.OnClickListener {
private Button btnDyedWork, btnFancyPrint, btnBridalcollection, btnBlouse;
private LinearLayout linearTypeDyedWork, linearTypeFancyPrint;
private boolean flagDyedWork = false;
private boolean flagFancyPrint = false;
private Button btnDyedWorkCatalogue;
CoordinatorLayout.Behavior behavior;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View vi = inflater.inflate(R.layout.fragment_home, container, false);
btnDyedWork = (Button) vi.findViewById(R.id.btn_dyed_work);
btnFancyPrint = (Button) vi.findViewById(R.id.btn_fancy_print);
btnDyedWork.setOnClickListener(this);
linearTypeDyedWork = (LinearLayout) vi.findViewById(R.id.type_dyed_work);
linearTypeFancyPrint = (LinearLayout) vi.findViewById(R.id.type_fancy_print);
btnDyedWorkCatalogue = (Button) vi.findViewById(R.id.btn_dyed_work_catalogue);
btnDyedWorkCatalogue.setOnClickListener(this);
return vi; }
public void onClick (View v){
switch (v. getId()){
case R.id.btn_dyed_work:
if(!flagDyedWork){
linearTypeDyedWork.setVisibility(View.VISIBLE);
linearTypeFancyPrint.setVisibility(View.GONE);
flagDyedWork=true;
flagFancyPrint=false;
btnDyedWork.setCompoundDrawablesWithIntrinsicBounds(null,null,getResources().getDrawable(R.drawable.ic_keyboard_arrow_up),null);
}else{
linearTypeDyedWork.setVisibility(View.GONE);
linearTypeFancyPrint.setVisibility(View.GONE);
flagDyedWork=false;
flagFancyPrint=false;
btnDyedWork.setCompoundDrawablesWithIntrinsicBounds(null,null,getResources().getDrawable(R.drawable.ic_keyboard_arrow_down),null);
}
break;
case R.id.btn_fancy_print:
if(!flagFancyPrint){
linearTypeDyedWork.setVisibility(View.VISIBLE);
linearTypeFancyPrint.setVisibility(View.GONE);
flagFancyPrint=true;
flagDyedWork=false;
btnFancyPrint.setCompoundDrawablesWithIntrinsicBounds(null,null,getResources().getDrawable(R.drawable.ic_keyboard_arrow_up),null);
}else{
linearTypeDyedWork.setVisibility(View.GONE);
linearTypeFancyPrint.setVisibility(View.GONE);
flagFancyPrint=false;
flagDyedWork=false;
btnFancyPrint.setCompoundDrawablesWithIntrinsicBounds(null,null,getResources().getDrawable(R.drawable.ic_keyboard_arrow_down),null);
}
break;
case R.id.btn_dyed_work_catalogue:
Bundle bundle=new Bundle();
bundle.putString("category_id","1");
CatalogueFragment cf=new CatalogueFragment();
cf.setArguments(bundle);
FragmentManager fm=getActivity().getSupportFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
ft.replace(R.id.content_frame,cf,"catalogue_fragment");
//ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
break;
}
}
}
Catalogue Fragment
package com.propelbit.jaydeepsaress.ui.fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.TextView;
import com.propelbit.jaydeepsaress.R;
import com.propelbit.jaydeepsaress.core.cons.Constants;
import com.propelbit.jaydeepsaress.core.parser.JsonParser;
import com.propelbit.jaydeepsaress.core.pojo.CatalogueDetails;
import com.propelbit.jaydeepsaress.ui.activity.HomeActivity;
import com.propelbit.jaydeepsaress.ui.adapter.AdapterCatalogue;
import org.json.JSONException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* Created by ankit on 07/09/16.
*/
public class CatalogueFragment extends Fragment {
String categoryId;
String serverResponse;
GridView gridview;
TextView noDataFound;
ArrayList<CatalogueDetails> listCatalogue;
AdapterCatalogue adapter;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
((HomeActivity) getActivity()).toggle.setDrawerIndicatorEnabled(false);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View vi = inflater.inflate(R.layout.fragment_catalogue, container, false);
if (this.getArguments() != null) {
categoryId = this.getArguments().getString("category_id");
}
listCatalogue=new ArrayList<CatalogueDetails>();
adapter=new AdapterCatalogue(getActivity(),listCatalogue);
gridview = (GridView) vi.findViewById(R.id.gridview);
noDataFound = (TextView) vi.findViewById(R.id.no_data_found);
gridview.setAdapter(adapter);
new GetCatalogueDetails().execute(Constants.BASE_URL+"getCatalogueDetails");
return vi;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d("TAG",item.getItemId()+"");
switch (item.getItemId()) {
case android.R.id.home:
Log.d("Called","Back Button");
getActivity().onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
private class GetCatalogueDetails extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
try {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.readTimeout(60, TimeUnit.SECONDS);
Log.d("CatalogueF",categoryId);
OkHttpClient client = builder.build();
RequestBody formBody = new FormBody.Builder()
.add("category_id", categoryId)
.build();
Request request = new Request.Builder()
.url(params[0])
.post(formBody)
.build();
Response response = null;
response = client.newCall(request).execute();
serverResponse = response.body().string();
Log.d("response", serverResponse);
return JsonParser.parseResponseCode(serverResponse);
} catch (IOException e) {
e.printStackTrace();
return "102";
} catch (JSONException e) {
e.printStackTrace();
return "103";
}
}
#Override
protected void onPostExecute(String responseCode) {
try {
if (responseCode.equals("100")) {
ArrayList<CatalogueDetails> temp= JsonParser.parseCatalogueDetails(serverResponse);
int size=temp.size();
Log.d("size",size+""+temp.get(0).getCatalogueName());
if(size>0){
listCatalogue.addAll(temp);
Log.d("listCatalogue",listCatalogue.size()+"");
gridview.setVisibility(View.VISIBLE);
noDataFound.setVisibility(View.GONE);
adapter.notifyDataSetChanged();
}else{
gridview.setVisibility(View.GONE);
noDataFound.setVisibility(View.VISIBLE);
noDataFound.setText("No data found");
}
}else if(responseCode.equals("101")){
gridview.setVisibility(View.GONE);
noDataFound.setVisibility(View.VISIBLE);
noDataFound.setText("SQL Exception.Please try again");
}else if(responseCode.equals("102")){
gridview.setVisibility(View.GONE);
noDataFound.setVisibility(View.VISIBLE);
noDataFound.setText("IO Exception.Please try again");
}else if(responseCode.equals("103")){
gridview.setVisibility(View.GONE);
noDataFound.setVisibility(View.VISIBLE);
noDataFound.setText("JSON Exception.Please try again.");
}
} catch (JSONException e) {
e.printStackTrace();
gridview.setVisibility(View.GONE);
noDataFound.setVisibility(View.VISIBLE);
noDataFound.setText("JSON Exception..Please try again.");
}
}
}
}

First, you need to remove parenting metadata from the manifest. It's incorrect.
<activity
android:name=".ui.activity.HomeActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Now, if you want to listen to clicks on any type of NavigationIcon in your custom toolbar (be it a Hamburger or up-caret or some fancy icon) then use setToolbarNavigationClickListener().
In your HomeActivity do this :
toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* do whatever you want like popping the fragment from backstack
getSupportFragmentManager().popBackStackImmediate(); */
}
});
I had this problem too. Check this thread : Cannot listen clicks on up caret

The best way to do that is to handle back presses in the activity. In the fragments make put this or remove the onOptionsItemSelected method entirely:
case android.R.id.home:
return false;
In Your activity:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d("TAG",item.getItemId()+"");
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}

Related

Android Studio toolbar title updating error with back stack from one fragment to the another fragment

i have a fragment_home that has 6 buttons and these 6 buttons have there own link(to display something like registration form ) but i have one button from these 6 buttons which is linked to another fragment and has tabbed view with view pager the title of any other fragment will update when i press back but when i entered to the button that links to the tabbed view it makes the toolbar title constant and it won't update there the application unless i exit and open again
for more information i have added some photos with description below
shortly
when application Starts
first image
when i clicked users
second image
when i click back
third image
it updates the title correctly , when i click register own
fourth image
it updates correctly again but now when i press back
last image
it doesnt update the title
main navigation class
package com.example.arada_tech.myapplication;
import android.nfc.Tag;
import android.support.v4.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
public class Navi extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
Fragment fragment1;
DrawerLayout drawer;
Tag tag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navi);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
// fab.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
// Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
// .setAction("Action", null).show();
// }
// });
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
Displayfragment(R.id.nav_home);
}
boolean doubleBackToExitPressedOnce=false;
// #Override
// public void onBackPressed() {
//
// DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
// if (drawer.isDrawerOpen(GravityCompat.START)) {
// drawer.closeDrawer(GravityCompat.START);
//
// } else {
// if (getFragmentManager().getBackStackEntryCount() > 1) {
// getFragmentManager().popBackStack();
// } else if (!doubleBackToExitPressedOnce) {
// this.doubleBackToExitPressedOnce = true;
// Toast.makeText(this,"Please click BACK again to exit.", Toast.LENGTH_SHORT).show();
// new Handler().postDelayed(new Runnable() {
// #Override
// public void run() {
// doubleBackToExitPressedOnce = false;
// }
// }, 2000);
// }
// else {
// System.exit(1);
//// super.onBackPressed();
// }
//
// }
// }
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.navi, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void Displayfragment(int id)
{
Fragment fragment=null;
switch(id) {
case R.id.nav_home:
fragment = new Fragment_Home();
break;
case R.id.nav_addbirr:
// fragment = new Fragment_addbirr();
break;
case R.id.nav_adduser:
fragment = new Fragment_addusers();
break;
case R.id.nav_followorders:
// fragment = new Fragment_followorders();
break;
case R.id.nav_Deleteusers:
// fragment = new Fragment_deleteusers();
break;
case R.id.nav_setings:
// fragment = new Fragment_settings();
Intent tin=new Intent(getApplicationContext(),Menus.class);
startActivity(tin);
break;
}
if(fragment!=null)
{
FragmentManager fragmentManager=getSupportFragmentManager();
FragmentTransaction ft= fragmentManager.beginTransaction();
fragment1=fragmentManager.findFragmentById(R.id.nav_home);
ft.replace(R.id.myframelayout,fragment);
// ft.addToBackStack(fragment.getClass().getName());
ft.addToBackStack(fragment.getClass().getName());
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
Displayfragment(item.getItemId());
return true;
}
public void setActionBarTitle(String title) {
getSupportActionBar().setTitle(title);
}
}
my Fragment_home
package com.example.arada_tech.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
public class Fragment_Home extends Fragment implements View.OnClickListener {
CardView im,in,du,ro;
Fragment fragment=null;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
getActivity().setTitle("home");
return inflater.inflate(R.layout.mukera,container,false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
im= (CardView) view.findViewById(R.id.card_user);
ro= (CardView) view.findViewById(R.id.card_registerown);
im.setOnClickListener(this);
ro.setOnClickListener(this);
in= (CardView) view.findViewById(R.id.card_order);
in.setOnClickListener(this);
du= (CardView) view.findViewById(R.id.card_deleteuser);
du.setOnClickListener(this);
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onClick(View v) {
if(v==im){
fragment = new Fragment_addusers();
FragManager();
}
else if (v==in)
{
// fragment = new Fragment_followorders();
FragManager();
}
else if (v==du)
{
// fragment = new Fragment_deleteusers();
FragManager();
}
else if (v==ro)
{
fragment = new Fragment_registerown();
FragManager();
}
}
public void FragManager()
{
if(fragment!=null)
{
FragmentManager fragmentManager=getFragmentManager();
FragmentTransaction ft= fragmentManager.beginTransaction();
ft.replace(R.id.myframelayout,fragment);
ft.addToBackStack(null);
ft.commit();
}
}
}
and my registerown fragment
package com.example.arada_tech.myapplication;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
public class Fragment_registerown extends Fragment {
Context context;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
getActivity().setTitle("register Own");
setHasOptionsMenu(true);
return inflater.inflate(R.layout.mainslide,container,false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("View"));
tabLayout.addTab(tabLayout.newTab().setText("Create"));
tabLayout.addTab(tabLayout.newTab().setText("Edit"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) view.findViewById(R.id.pager);
final ViewAdapter adapter = new ViewAdapter(((FragmentActivity) getContext()).getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
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 onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
// super.onViewCreated(view, savedInstanceState);
}
for any help thanks in advance
you just need to debug and check
public void setActionBarTitle(String title) {
getSupportActionBar().setTitle(title);
}
method is call or not on the back event of register own fragment.you are not mentions the code line where you called setActionBarTitle() method in the code.
It works when i delete the first two lines of code in registerown_fragment in onviewcreated method Thank you for your help

OnOptionsItemSelected Method not called on click of back button android.R.id.home

I have an app with single activity (HomeActivity) and 3 fragments . When i traverse from Home Fragment to Second Fragment , i replace Hammburger icon with Back button by(setDisplayHomeAsUpEnabled(true)).But when i press back button it does nothing and even onOptionsItemSelected() method is not called.I have spend my entire day behind this error.Please help
Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.propelbit.jaydeepsaress">
<uses-permission android:name="android.permission.INTERNET" />
<!-- Include following permission if you want to cache images on SD card -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:name="com.propelbit.jaydeepsaress.JaydeepSarees"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".ui.activity.HomeActivity"
android:parentActivityName=".ui.activity.HomeActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.propelbit.jaydeepsaress.ui.activity.HomeActivity"/>
</activity>
</application>
</manifest>
HomeActivity
package com.propelbit.jaydeepsaress.ui.activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.propelbit.jaydeepsaress.R;
import com.propelbit.jaydeepsaress.ui.fragment.HomeFragment;
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
public ActionBarDrawerToggle toggle;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
if (savedInstanceState == null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
toggle.setDrawerIndicatorEnabled(true);
ft.replace(R.id.content_frame, new HomeFragment());
ft.commit();
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
FragmentManager fm = getSupportFragmentManager();
int backStackEntryCount = fm.getBackStackEntryCount();
Log.d("BSEC",backStackEntryCount+"");
if (backStackEntryCount > 0) {
fm.popBackStack();
if (fm.getBackStackEntryCount() > 0) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toggle.setDrawerIndicatorEnabled(false);
} else {
//drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
// Display the Drawer Icon
toggle.setDrawerIndicatorEnabled(true);
}
} else {
//drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
// Display the Drawer Icon
toggle.setDrawerIndicatorEnabled(true);
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
toggle.onConfigurationChanged(newConfig);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
toggle.syncState();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d("TAG",item.getItemId()+"");
switch (item.getItemId()) {
case android.R.id.home:
// Do nothing handled by fragment.
return false;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
HomeFragment
package com.propelbit.jaydeepsaress.ui.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import com.propelbit.jaydeepsaress.R;
import com.propelbit.jaydeepsaress.ui.activity.HomeActivity;
/**
* Created by ankit on 05/09/16.
*/
public class HomeFragment extends Fragment implements View.OnClickListener {
private Button btnDyedWork, btnFancyPrint, btnBridalcollection, btnBlouse;
private LinearLayout linearTypeDyedWork, linearTypeFancyPrint;
private boolean flagDyedWork = false;
private boolean flagFancyPrint = false;
private Button btnDyedWorkCatalogue;
CoordinatorLayout.Behavior behavior;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View vi = inflater.inflate(R.layout.fragment_home, container, false);
btnDyedWork = (Button) vi.findViewById(R.id.btn_dyed_work);
btnFancyPrint = (Button) vi.findViewById(R.id.btn_fancy_print);
btnDyedWork.setOnClickListener(this);
linearTypeDyedWork = (LinearLayout) vi.findViewById(R.id.type_dyed_work);
linearTypeFancyPrint = (LinearLayout) vi.findViewById(R.id.type_fancy_print);
btnDyedWorkCatalogue = (Button) vi.findViewById(R.id.btn_dyed_work_catalogue);
btnDyedWorkCatalogue.setOnClickListener(this);
return vi; }
public void onClick (View v){
switch (v. getId()){
case R.id.btn_dyed_work:
if(!flagDyedWork){
linearTypeDyedWork.setVisibility(View.VISIBLE);
linearTypeFancyPrint.setVisibility(View.GONE);
flagDyedWork=true;
flagFancyPrint=false;
btnDyedWork.setCompoundDrawablesWithIntrinsicBounds(null,null,getResources().getDrawable(R.drawable.ic_keyboard_arrow_up),null);
}else{
linearTypeDyedWork.setVisibility(View.GONE);
linearTypeFancyPrint.setVisibility(View.GONE);
flagDyedWork=false;
flagFancyPrint=false;
btnDyedWork.setCompoundDrawablesWithIntrinsicBounds(null,null,getResources().getDrawable(R.drawable.ic_keyboard_arrow_down),null);
}
break;
case R.id.btn_fancy_print:
if(!flagFancyPrint){
linearTypeDyedWork.setVisibility(View.VISIBLE);
linearTypeFancyPrint.setVisibility(View.GONE);
flagFancyPrint=true;
flagDyedWork=false;
btnFancyPrint.setCompoundDrawablesWithIntrinsicBounds(null,null,getResources().getDrawable(R.drawable.ic_keyboard_arrow_up),null);
}else{
linearTypeDyedWork.setVisibility(View.GONE);
linearTypeFancyPrint.setVisibility(View.GONE);
flagFancyPrint=false;
flagDyedWork=false;
btnFancyPrint.setCompoundDrawablesWithIntrinsicBounds(null,null,getResources().getDrawable(R.drawable.ic_keyboard_arrow_down),null);
}
break;
case R.id.btn_dyed_work_catalogue:
Bundle bundle=new Bundle();
bundle.putString("category_id","1");
CatalogueFragment cf=new CatalogueFragment();
cf.setArguments(bundle);
FragmentManager fm=getActivity().getSupportFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
ft.replace(R.id.content_frame,cf,"catalogue_fragment");
//ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
break;
}
}
}
CatalogueFragment
package com.propelbit.jaydeepsaress.ui.fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.TextView;
import com.propelbit.jaydeepsaress.R;
import com.propelbit.jaydeepsaress.core.cons.Constants;
import com.propelbit.jaydeepsaress.core.parser.JsonParser;
import com.propelbit.jaydeepsaress.core.pojo.CatalogueDetails;
import com.propelbit.jaydeepsaress.ui.activity.HomeActivity;
import com.propelbit.jaydeepsaress.ui.adapter.AdapterCatalogue;
import org.json.JSONException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* Created by ankit on 07/09/16.
*/
public class CatalogueFragment extends Fragment {
String categoryId;
String serverResponse;
GridView gridview;
TextView noDataFound;
ArrayList<CatalogueDetails> listCatalogue;
AdapterCatalogue adapter;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
((HomeActivity) getActivity()).toggle.setDrawerIndicatorEnabled(false);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View vi = inflater.inflate(R.layout.fragment_catalogue, container, false);
if (this.getArguments() != null) {
categoryId = this.getArguments().getString("category_id");
}
listCatalogue=new ArrayList<CatalogueDetails>();
adapter=new AdapterCatalogue(getActivity(),listCatalogue);
gridview = (GridView) vi.findViewById(R.id.gridview);
noDataFound = (TextView) vi.findViewById(R.id.no_data_found);
gridview.setAdapter(adapter);
new GetCatalogueDetails().execute(Constants.BASE_URL+"getCatalogueDetails");
return vi;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d("TAG",item.getItemId()+"");
switch (item.getItemId()) {
case android.R.id.home:
Log.d("Called","Back Button");
getActivity().onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
private class GetCatalogueDetails extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
try {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.readTimeout(60, TimeUnit.SECONDS);
Log.d("CatalogueF",categoryId);
OkHttpClient client = builder.build();
RequestBody formBody = new FormBody.Builder()
.add("category_id", categoryId)
.build();
Request request = new Request.Builder()
.url(params[0])
.post(formBody)
.build();
Response response = null;
response = client.newCall(request).execute();
serverResponse = response.body().string();
Log.d("response", serverResponse);
return JsonParser.parseResponseCode(serverResponse);
} catch (IOException e) {
e.printStackTrace();
return "102";
} catch (JSONException e) {
e.printStackTrace();
return "103";
}
}
#Override
protected void onPostExecute(String responseCode) {
try {
if (responseCode.equals("100")) {
ArrayList<CatalogueDetails> temp= JsonParser.parseCatalogueDetails(serverResponse);
int size=temp.size();
Log.d("size",size+""+temp.get(0).getCatalogueName());
if(size>0){
listCatalogue.addAll(temp);
Log.d("listCatalogue",listCatalogue.size()+"");
gridview.setVisibility(View.VISIBLE);
noDataFound.setVisibility(View.GONE);
adapter.notifyDataSetChanged();
}else{
gridview.setVisibility(View.GONE);
noDataFound.setVisibility(View.VISIBLE);
noDataFound.setText("No data found");
}
}else if(responseCode.equals("101")){
gridview.setVisibility(View.GONE);
noDataFound.setVisibility(View.VISIBLE);
noDataFound.setText("SQL Exception.Please try again");
}else if(responseCode.equals("102")){
gridview.setVisibility(View.GONE);
noDataFound.setVisibility(View.VISIBLE);
noDataFound.setText("IO Exception.Please try again");
}else if(responseCode.equals("103")){
gridview.setVisibility(View.GONE);
noDataFound.setVisibility(View.VISIBLE);
noDataFound.setText("JSON Exception.Please try again.");
}
} catch (JSONException e) {
e.printStackTrace();
gridview.setVisibility(View.GONE);
noDataFound.setVisibility(View.VISIBLE);
noDataFound.setText("JSON Exception..Please try again.");
}
}
}
}
setHasOptionsMenu(true);
include this in fragment so that onOptionItemSelected() can be called.
Finally solved.
Now, if you want to listen to clicks on any type of NavigationIcon in your custom toolbar (be it a Hamburger or up-caret or some fancy icon) then use setToolbarNavigationClickListener(). No need to use onOptionsItemSelected Method.
Thanks Protino for suggestion
// Add the backstack listener
getSupportFragmentManager().addOnBackStackChangedListener(this);
// Handle clicks on the up arrow since this isnt handled by the
toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fm = getSupportFragmentManager();
// Pop the backstack all the way back to the initial fragment. Customize if needed
//fm.popBackStack(fm.getBackStackEntryAt(0).getName(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
if(fm.getBackStackEntryCount() > 0) {
fm.popBackStack();
toggle.setDrawerIndicatorEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
} else {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
toggle.setDrawerIndicatorEnabled(true);
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
}
}
});
/**
* Called everytime we add or remove something from the backstack
*/
#Override
public void onBackStackChanged() {
if(getSupportFragmentManager().getBackStackEntryCount() > 0) {
Log.d("Called >0","false");
toggle.setDrawerIndicatorEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
} else {
Log.d("Called <0","true");
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
toggle.setDrawerIndicatorEnabled(true);
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
}
}
/**
* If you need to move backwards inside the app using the back button, and want to override the
* the default behaviour which could take you outside the app before you've popped the entire stack
*/
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStackImmediate();
} else {
super.onBackPressed();
}
}
Well to call the activity method, you should use something like this
((YourActivityName)getActivity()).onBackPressed();
and for the log to work you need to include the tag too.
Log.d(TAG, "Your message");

Activity has leaked window when show dialogprogress

I am trying to generate a listview in a fragment. The code show no error but when i try to start the application, after the progressdialog show then the application crashed.below is my show_fish.java file. Please help. I'm a newbie in android development.
show_fish.java
package com.rapier.tehranbargh;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.telecom.Connection;
import android.util.Log;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import layout.Ghabz;
import layout.SoratHesabFragment;
import layout.info;
import layout.masaref;
import layout.news;
public class Show_fish extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private ProgressDialog progressDialog;
JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> hashMaps;
JSONArray jsonArray = null;
private final String url = "http://192.168.1.106:8080/ghabz.php";
ListView listview;
TextView EmailView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_fish);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
listview = (ListView) findViewById(R.id.listView);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
if (savedInstanceState == null) {
// on first time to display view for first navigation item based on the number
displayView(1); // 2 is your fragment's number for "CollectionFragment"
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.content_frame, new news());
tx.commit();
}
new newse().execute();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.show_fish, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
displayView(item.getItemId());
return true;
}
public void displayView(int viewId) {
Fragment fragment = null;
String title = getString(R.string.rapier);
switch (viewId) {
case R.id.nav_news:
fragment = new news();
title = " اخبار ";
break;
case R.id.nav_info:
fragment = new info();
title = " اطلاعات عمومی ";
break;
case R.id.nav_billam:
fragment = new SoratHesabFragment();
title = " صورت حساب ها ";
break;
case R.id.nav_use:
fragment = new masaref();
title = " مصارف ";
break;
case R.id.nav_ghabz:
fragment = new Ghabz();
title = " قبض ";
break;
}
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
// set the toolbar title
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle(title);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
class newse extends AsyncTask<String,String,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog =new ProgressDialog(Show_fish.this);
progressDialog.setMessage("Loading");
progressDialog.show();
}
#Override
protected String doInBackground(String... strings) {
List<NameValuePair> params= new ArrayList<>();
JSONObject json=jsonParser.makeHttpRequest(url,"GET",params);
try {
int t=json.getInt("t");
if(t==1){
jsonArray=json.getJSONArray("news");
for (int i = 0 ;i<jsonArray.length();i++){
JSONObject c = jsonArray.getJSONObject(i);
String ID=c.getString("ID");
String TitrNews=c.getString("TitrNews");
String MiniMatnNews=c.getString("MiniMatnNews");
String MatnNews=c.getString("MatnNews");
String TArikh=c.getString("TArikh");
HashMap<String,String> map = new HashMap<String, String>();
map.put("ID",ID);
map.put("TitrNews",TitrNews);
map.put("MiniMatnNews",MiniMatnNews);
map.put("MatnNews",MatnNews);
map.put("TArikh",TArikh);
hashMaps.add(map);
}
}
else {
Toast.makeText(Show_fish.this," اطلاعاتی دریافت نشد ",Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressDialog.cancel();
runOnUiThread(new Runnable() {
#Override
public void run() {
ListAdapter adapter = new SimpleAdapter(Show_fish.this, hashMaps, R.id.listView, new String[]{"TitrNews", "MiniMatnNews", "TArikh"}, new int[]{R.id.titr, R.id.mtn, R.id.data});
listview.setAdapter(adapter);
}
});
}
}
}
fragment with listview
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="layout.news">
<!-- TODO: Update blank fragment layout -->
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_gravity="center_horizontal" />
</LinearLayout>
news.java java file of fragment with list view
public class news extends Fragment {
public news() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_news, container, false);
}
}
and error her
android.view.WindowLeaked: Activity com.rapier.tehranbargh.Show_fish has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{3cdf88f6 V.E..... R......D 0,0-729,232} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:363)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:261)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:298)
at com.rapier.tehranbargh.Show_fish$newse.onPreExecute(Show_fish.java:205)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.rapier.tehranbargh.Show_fish.onCreate(Show_fish.java:90)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Add check as:
if(progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}

How to load the MainActivity on pressing the Back button of the Phone

I have a MainActivity that has a NavigationDrawer in it.In the menu of the drawer each item starts a new activity.Now when i press the Back button from any of these activities i end up in a blank page,when i press it again it goes to main activity.What i want is to go directly to the main activity.
my MainActivity.java:
package com.defcomm.invento;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.defcomm.invento.NavigationDrawerActivity;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class INVENTO extends AppCompatActivity {
private Toolbar toolbar;
private CoordinatorLayout mCoordinator;
private CollapsingToolbarLayout mCollapsableLayout;
private NestedScrollView nestedScrollView;
private ViewPager mPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new);
mCoordinator= (CoordinatorLayout) findViewById(R.id.coordinator_layout);
mCollapsableLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
toolbar= (Toolbar) findViewById(R.id.appbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
mCollapsableLayout.setTitle(getResources().getString(R.string.app_name));
nestedScrollView= (NestedScrollView) findViewById(R.id.rvToDoList);
mCollapsableLayout.setExpandedTitleTextAppearance(R.style.ExpandedTitleTextAppearence);
mCollapsableLayout.setCollapsedTitleTextColor(getResources().getColor(R.color.textColor));
NavigationDrawerActivity drawerFragment= (NavigationDrawerActivity) getSupportFragmentManager().
findFragmentById(R.id.navigation_drawer);
drawerFragment.setUp(R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawerlayout), toolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_invento, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
my NavigationDrawer.java1:
package com.defcomm.invento;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.support.design.widget.CollapsingToolbarLayout;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import java.util.ArrayList;
import java.util.List;
public class NavigationDrawerActivity extends Fragment implements MyAdapter.clickListener {
private ActionBarDrawerToggle mdrawerToggle;
private DrawerLayout mdrawerLayout;
private boolean mUserLearnedState;
private MyAdapter adapter;
private CoordinatorLayout mcoordinator;
private RecyclerView recyclerView;
private CollapsingToolbarLayout collapsingToolbarLayout;
View containerId;
public static final String file_pref_name = "Testpef";
public static final String KEY_USER_VALUE = "user_learned_drawer";
private boolean mfromSavedInstanceState;
public NavigationDrawerActivity() {
// Required empty public constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUserLearnedState = Boolean.valueOf(readPreference(getActivity(), KEY_USER_VALUE, "false"));
if (savedInstanceState != null) {
mfromSavedInstanceState = true;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View layout=inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
recyclerView= (RecyclerView) layout.findViewById(R.id.recycler);
adapter=new MyAdapter(getActivity(),getdata());
adapter.setClicklistener(this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return layout;
}
public static List<ListItems> getdata(){
List<ListItems> nav_data=new ArrayList<>();
int[] icons={R.drawable.variable,R.drawable.ignore};
String[] texts={"Coding","Hacking"};
for(int i=0;i<icons.length&&i<icons.length;i++){
ListItems current=new ListItems();
current.iconId=icons[i];
current.IconName=texts[i];
nav_data.add(current);
}
return nav_data;
}
public void setUp(final int fragmentId, DrawerLayout drawerlayout, final Toolbar toolbar) {
mdrawerLayout = drawerlayout;
containerId = getActivity().findViewById(fragmentId);
mdrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerlayout, toolbar,
R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!mUserLearnedState) {
mUserLearnedState = true;
saveToPreference(getActivity(), KEY_USER_VALUE, mUserLearnedState + "");
}
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
if (slideOffset < 0.5f) {
toolbar.setAlpha(1 - slideOffset);
}
}
};
if (!mUserLearnedState && !mfromSavedInstanceState) {
mdrawerLayout.openDrawer(containerId);
}
mdrawerLayout.setDrawerListener(mdrawerToggle);
mdrawerLayout.post(new Runnable() {
#Override
public void run() {
mdrawerToggle.syncState();
}
});
}
public static void saveToPreference(Context context, String preferenceName, String preferenceValue) {
SharedPreferences shared = context.getSharedPreferences(file_pref_name, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
editor.putString(preferenceName, preferenceValue);
editor.apply();
}
public static String readPreference(Context context, String preferenceName, String defaultValue) {
SharedPreferences share = context.getSharedPreferences(file_pref_name, Context.MODE_PRIVATE);
return share.getString(preferenceName, defaultValue);
}
#Override
public void ItemCLick(View view, int position) {
if(position==0){
startActivity(new Intent(getActivity(),Coding.class));
}
if(position==1){
startActivity(new Intent(getActivity(),Hacking.class));
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.defcomm.invento" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".INVENTO"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Coding"
android:label="#string/title_activity_coding" >
</activity>
<activity
android:name=".Hacking"
android:label="#string/title_activity_hacking" >
</activity>
</application>
you can try this.
#Override
public void onBackPressed() {
startActivity(new Intent(this,MainActivity.class));
this.finish();
}
Try this
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
This will close all other activities and start MainActivity
This will close the drawer when it's open and back is pressed rather than taking you back to the previous activity (or exiting).
DrawerLayout drawer...
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
if(drawer.isDrawerOpen(Gravity.LEFT)){
drawer.closeDrawer(Gravity.LEFT);
startActivity(new Intent(CurrentActivity.this , MainActivity.class))
finish();
}else{
super.onBackPressed();
}
}

Android - ActionBarSherlock Navigation Drawer and Fragments with Activities

I am trying to understand how to implement the ActionBarSherlock Navigation Drawer into a project. I have one working with the official Android implementation but I would like it to run at 2.2+ so I am looking into ActionBarSherlock. I have an error under the selectItem(int position) section of the code. I will paste it here:
package com.rufflez.absnavdrawer;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends SherlockFragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mFragmentTitles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mFragmentTitles = getResources().getStringArray(R.array.fragments);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer);
mDrawerList = (ListView)findViewById(R.id.drawer_list);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mFragmentTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this,
mDrawerLayout,
R.drawable.ic_drawer,
R.string.drawer_open,
R.string.drawer_close){
public void onDrawerClosed(View v){
getSupportActionBar().setTitle(mTitle);
supportInvalidateOptionsMenu();
}
public void onDrawerOpened(View v){
getSupportActionBar().setTitle(mDrawerTitle);
supportInvalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null){
selectItem(0);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu){
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getSupportMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case android.R.id.home:
if (mDrawerLayout.isDrawerOpen(mDrawerList)){
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
return true;
case R.id.action_settings:
Intent i = new Intent(MainActivity.this, Sources.class);
startActivity(i);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private class DrawerItemClickListener implements ListView.OnItemClickListener{
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id){
selectItem(position);
}
}
private void selectItem(int position){
Fragment newFragment = new Fragment_1();
FragmentManager fm = getSupportFragmentManager();
switch(position){
case 0:
newFragment = new Fragment_1();
break;
case 1:
newFragment = new Fragment_2();
break;
case 2:
newFragment = new Fragment_3();
break;
case 3:
newFragment = new Fragment_4();
break;
case 4:
newFragment = new Fragment_5();
break;
}
fm.beginTransaction()
.replace(R.id.content_frame, newFragment)
.commit();
mDrawerList.setItemChecked(position, true);
setTitle(mFragmentTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title){
mTitle = title;
getSupportActionBar().setTitle(title);
}
#Override
protected void onPostCreate(Bundle savedInstanceState){
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
As I said above, the error is under selectItem and specifically error under new Fragment_1(); and again at new Fragment_1();. The eclipse message is Type mismatch: cannot convert from Fragment_1 to Fragment.
This is Fragment_1.java:
package com.rufflez.absnavdrawer;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class Fragment_1 extends FragmentActivity{
WebView webview;
private String url;
ProgressBar pd = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// pd = (ProgressBar) findViewById(R.id.web_view_progress_bar);
// webview = (WebView) findViewById(R.id.WebView);
webview.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int progress) {
if(progress < 100 && pd.getVisibility() == View.GONE){
pd.setVisibility(View.VISIBLE);
}
pd.setProgress(progress);
if(progress == 100) {
pd.setVisibility(View.GONE);
}
}
});
webview.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
// do your handling codes here, which url is the requested url
// probably you need to open that url rather than redirect:
if (url.startsWith("tel:")) {
startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
} else if (url.startsWith("mailto:")) {
url = url.replaceFirst("mailto:", "");
url = url.trim();
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("plain/text").putExtra(Intent.EXTRA_EMAIL, new String[]{url});
startActivity(i);
} else {
view.loadUrl(url);
}
return true;
// then it is not handled by default action
}
});
webview.loadUrl("file:///android_asset/about.html");
}
#Override
public void onBackPressed()
{
if(webview.canGoBack())
webview.goBack();
else
super.onBackPressed();
}
public void setUrl(String url) {
this.url = url;
}
public String getUrl() {
return url;
}
}
I think you are missing a cast, since new Fragment_1() will return class Fragment_1, and not Fragment.
Oh! Fragment_1() is FragmentActivity Which is an Activity different from Fragment!
see it
Dilemma: when to use Fragments vs Activities:
Your fragment isn't a fragment.
Change onCreate to onCreateView and do this code;
public class Fragment_1 extends SherlockFragment{
i think that is the error.
if not, try rebuilding your fragment in this one
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.actionbarsherlock.app.SherlockFragment;
public class Fragment_1 extends SherlockFragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
return inflater.inflate(R.layout.frag1, container, false);
//change frag1 to corresponding XML
}
}

Categories

Resources