Activity has leaked window when show dialogprogress - android

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();
}

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

Error Occurs in implementing the Navigation drawer

I have one Login Activity if user click on login button than automatically its go to Navigation Drawer but i got an error. Please Help me out from this error.
MainActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
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.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, AdapterView.OnItemSelectedListener, AdapterView.OnItemClickListener {
private Toolbar toolbar;
private DrawerLayout drawer;
public String emailRegistration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_business);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//toolbar.setTitle("toolbar");
setSupportActionBar(toolbar);
//Set adapter to AutoCompleteTextView
// FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
// if (!emailRegistration.matches("[a-zA-Z0-9._-]+#[a-z]+.[a-z]+")) {
//
// email.setError("Invalid Email Address");
//
// }
// fab.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// Snackbar.make(v, "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.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#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.main, 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) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
setTitle("Home");
Intent i = new Intent(MainActivity.this, HomeFragment.class);
startActivity(i);
} else if (id == R.id.nav_gallery) {
setTitle("Edit Profile");
EditFragment editFragment = new EditFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment,editFragment).commit();
} else if (id == R.id.nav_slideshow) {
setTitle("Business");
BusinessFragment businessFragment = new BusinessFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment,businessFragment).commit();
} else if (id == R.id.nav_manage) {
setTitle("Message");
MessageFragment messageFragment = new MessageFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment,messageFragment).commit();
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
// TODO Auto-generated method stub
//Log.d("AutocompleteContacts", "onItemSelected() position " + position);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
InputMethodManager imm = (InputMethodManager) getSystemService(
INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
// TODO Auto-generated method stub
// Show Alert
Toast.makeText(getBaseContext(), "Position:"+i+" Country:"+adapterView.getItemAtPosition(i),
Toast.LENGTH_LONG).show();
Log.d("AutocompleteContacts", "Position:"+i+" Country:"+adapterView.getItemAtPosition(i));
}
}
LoginActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class LoginActivity extends AppCompatActivity {
public EditText email, password;
public TextView textView;
public Button login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
email = (EditText) findViewById(R.id.email);
// if( email.getText().toString().length() == 0 )
// email.setError("Email is required!" );
password = (EditText) findViewById(R.id.text_input_password_toggle);
// if( password.getText().toString().length() == 0 )
// password.setError("Password is required!" );
textView = (TextView) findViewById(R.id.text2);
login = (Button) findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
}
});
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(LoginActivity.this,signupactivity.class);
startActivity(i);
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
Error
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.widget.DrawerLayout.addDrawerListener(android.support.v4.widget.DrawerLayout$DrawerListener)' on a null object reference
SignupActivity. java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import java.util.ArrayList;
import java.util.List;
public class signupactivity extends AppCompatActivity {
public EditText firstname, lastname, email;
private AutoCompleteTextView actv;
public Button signup;
String[] languages={"Indore","Ujjain","Bhopal","Delhi","Bangalore","Chennai"};
List<CharSequence> list = new ArrayList<CharSequence>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
for (int i=0;i<20;i++){
list.add("test " + i); // Add the item in the list
}
firstname = (EditText)findViewById(R.id.firstname);
lastname = (EditText)findViewById(R.id.lastname);
actv = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
email = (EditText) findViewById(R.id.email);
signup = (Button)findViewById(R.id.signup);
ArrayAdapter adapter = new
ArrayAdapter(this,android.R.layout.simple_list_item_1,languages);
actv.setAdapter(adapter);
actv.setThreshold(1);
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(signupactivity.this, LoginActivity.class);
startActivity(i);
}
});
}
}
Image I want the blank fragment when i click on the home, edit profile but its show everywhere signup activity because my content_main framelayout id is fragment and its call in mainactivity and its my signup page too (fragmentManager.beginTransaction().replace(R.id.fragment,editFragment).commit();) So how to solve this problem
In your MainActivity.java you are using
setContentView(R.layout.fragment_business);
But your drawer is in activity_main.xml
So your drawer is a null and you cannot add a listener to a null object.
Change the setContentView to
setContentView(R.layout.activity_main);

ListView didn't showing data in Fragment at Navigation Drawer

i had problem that my string-array not showing in listview at ListFragment, i didn't get any error, just the data of string-array not display. i create a navigation drawer that show data form another fragment
here my ListFragment
import android.os.Bundle;
import android.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class FragmentFood extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_food,container,false);
String[] food = getResources().getStringArray(R.array.food_array);
ArrayAdapter adapter = new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1,food);
setListAdapter(adapter);
return rootView;
}
}
MainActivity.java
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ListFragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentActivity;
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.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends FragmentActivity
implements NavigationView.OnNavigationItemSelectedListener {
String nama;
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
Fragment fragment = null ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
Intent intent = getIntent();
nama = intent.getStringExtra("Nama");
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View headerView = navigationView.getHeaderView(0);
TextView tvNama = (TextView) headerView.findViewById(R.id.tv_name);
tvNama.setText(nama);
fragmentManager = getFragmentManager();
if (savedInstanceState == null) {
fragment = new FragmentFood();
callFragment(fragment);
}
/*FragmentFood fragmentFood = (FragmentFood) getSupportFragmentManager().findFragmentByTag("fragmentfood");
if (fragmentFood == null) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.frame_content,null,"fragmentfood");
transaction.commit();
}*/
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();
}
#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.main, 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) {
// Handle navigation view item clicks here.
ListFragment listFragment=null;
int id = item.getItemId();
if (id == R.id.nav_food) {
listFragment = new FragmentFood();
callFragment(listFragment);
} else if (id == R.id.nav_dessert) {
} else if (id == R.id.nav_drink) {
/*fragment = new FragmentDrink();
callFragment(fragment);*/
} else if (id == R.id.nav_chartpayment) {
} else if (id == R.id.nav_status) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void callFragment(Fragment fragment) {
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.remove(fragment);
fragmentTransaction.replace(R.id.frame_content, fragment);
fragmentTransaction.commit();
}
}
fragment_food.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="8dp"
android:paddingRight="8dp">
<ListView android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
/>
</LinearLayout>
i dont have any idea to show data in ListFragment at NavigationDrawer

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");

Custom Navigation Drawer doesn't show Fragment

I'm trying to create a favorite list in my app, for this target I used this tutorial:
http://androidopentutorials.com/android-sharedpreferences-tutorial-and-example/
but to get favorites I used NavigationDrawer instead ActionBar.
The problem is that nothing happens when I choose Favorites or Home in Drawer.
The Logcat shows only one error which not connected with my problem.
Where did I mistake?
Error:
06-30 17:41:48.530 6971-6971/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.boom.kayakapp, PID: 6971
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.widget.ImageView.getTag()' on a null object reference
at com.boom.kayakapp.activities.MainActivity$2.onItemLongClick(MainActivity.java:148)
at android.widget.AbsListView.showContextMenuForChild(AbsListView.java:3162)
at android.view.ViewGroup.showContextMenuForChild(ViewGroup.java:693)
at android.view.ViewGroup.showContextMenuForChild(ViewGroup.java:693)
at android.view.View.showContextMenu(View.java:4853)
at android.view.View.performLongClick(View.java:4822)
at android.widget.TextView.performLongClick(TextView.java:8684)
at android.view.View$CheckForLongPress.run(View.java:19840)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
--------- beginning of system
06-30 17:41:48.572 933-933/? E/EGL_emulation﹕ tid 933: eglCreateSyncKHR(1237): error 0x3004 (EGL_BAD_ATTRIBUTE)
06-30 17:41:50.823 1232-1274/system_process E/InputDispatcher﹕ channel '10153f49 com.boom.kayakapp/com.boom.kayakapp.activities.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
06-30 17:42:02.006 7546-7546/? E/memtrack﹕ Couldn't load memtrack module (No such file or directory)
06-30 17:42:02.006 7546-7546/? E/android.os.Debug﹕ failed to load memtrack module: -2
06-30 17:42:02.041 7546-7555/? E/art﹕ Thread attaching while runtime is shutting down: Binder_1
06-30 17:42:02.402 7560-7560/? E/memtrack﹕ Couldn't load memtrack module (No such file or directory)
06-30 17:42:02.402 7560-7560/? E/android.os.Debug﹕ failed to load memtrack module: -2
06-30 17:42:02.460 7560-7570/? E/art﹕ Thread attaching while runtime is shutting down: Binder_1
Main Activity:
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.boom.kayakapp.R;
import com.boom.kayakapp.adapters.AirlinesAdapter;
import com.boom.kayakapp.adapters.NavDrawerListAdapter;
import com.boom.kayakapp.controllers.AppController;
import com.boom.kayakapp.fragment.AirlinesFragment;
import com.boom.kayakapp.fragment.FavoriteFragment;
import com.boom.kayakapp.fragment.HomeFragment;
import com.boom.kayakapp.model.Airlines;
import com.boom.kayakapp.model.NavDrawerItem;
import com.boom.kayakapp.util.SharedPreference;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ActionBarActivity {
private Fragment contentFragment;
AirlinesFragment airlinesFragment;
FavoriteFragment favoriteFragment;
// JSON Node names
public static final String TAG_NAME = "name";
public static final String TAG_PHONE = "phone";
public static final String TAG_SITE = "site";
public static final String TAG_LOGO = "logoURL";
public static final String TAG_CODE = "code";
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
// Airlines json url
private static final String url = "https://www.kayak.com/h/mobileapis/directory/airlines";
public ProgressDialog pDialog;
public List<Airlines> airlinesList = new ArrayList<Airlines>();
public ListView listView;
public AirlinesAdapter adapterAirlines;
SharedPreference sharedPreference;
// DrawerLayout
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapterDrawer;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
// SharedPrefs
sharedPreference = new SharedPreference();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// Json Array
listView = (ListView) findViewById(R.id.list);
adapterAirlines = new AirlinesAdapter(this, airlinesList);
listView.setAdapter(adapterAirlines);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// Listview OnItemClickListener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String phone = ((TextView) view.findViewById(R.id.phone))
.getText().toString();
String site = ((TextView) view.findViewById(R.id.site))
.getText().toString();
String logoURL = String.valueOf(((ImageView) view.findViewById(R.id.logoURL)));
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_PHONE, phone);
in.putExtra(TAG_SITE, site);
in.putExtra(TAG_LOGO, logoURL);
startActivity(in);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
ImageView button = (ImageView) view.findViewById(R.id.favorite_button);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(MainActivity.this, airlinesList.get(position));
Toast.makeText(MainActivity.this,
MainActivity.this.getResources().getString(R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.heart_red);
} else {
sharedPreference.removeFavorite(MainActivity.this, airlinesList.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.heart_grey);
Toast.makeText(MainActivity.this,
MainActivity.this.getResources().getString(R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
return true;
}
});
// changing action bar color
getSupportActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#1b1b1b")));
// Creating volley request obj
JsonArrayRequest airlinesReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Airlines airlines = new Airlines();
airlines.setName(obj.getString("name"));
airlines.setLogoURL(obj.getString("logoURL"));
airlines.setPhone(obj.getString("phone"));
airlines.setCode(obj.getInt("code"));
airlines.setSite(obj.getString("site"));
// adding airlines to array
airlinesList.add(airlines);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapterAirlines about data changes
// so that it renders the list view with updated data
adapterAirlines.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(airlinesReq);
FragmentManager fragmentManager = getSupportFragmentManager();
/*
* This is called when orientation is changed.
*/
if (savedInstanceState != null) {
if (savedInstanceState.containsKey("content")) {
String content = savedInstanceState.getString("content");
if (content.equals(FavoriteFragment.ARG_ITEM_ID)) {
if (fragmentManager.findFragmentByTag(FavoriteFragment.ARG_ITEM_ID) != null) {
setFragmentTitle(R.string.favorites);
contentFragment = fragmentManager
.findFragmentByTag(FavoriteFragment.ARG_ITEM_ID);
}
}
}
if (fragmentManager.findFragmentByTag(AirlinesFragment.ARG_ITEM_ID) != null) {
airlinesFragment = (AirlinesFragment) fragmentManager
.findFragmentByTag(AirlinesFragment.ARG_ITEM_ID);
contentFragment = airlinesFragment;
}
} else {
airlinesFragment = new AirlinesFragment();
switchContent(airlinesFragment, AirlinesFragment.ARG_ITEM_ID);
}
/*
From this place DrawerLayout starts
*/
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// Favorites
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// Recycle the typed array
navMenuIcons.recycle();
// setting the nav drawer list adapterDrawer
adapterDrawer = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapterDrawer);
// enabling action bar app icon and behaving it as toggle button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, //nav menu toggle icon
R.string.app_name, // nav drawer open - description for accessibility
R.string.app_name // nav drawer close - description for accessibility
){
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
// if (mDrawerToggle.onOptionsItemSelected(item)) {
// return true;
// }
// Handle action bar actions click
// switch (item.getItemId()) {
// case R.id.action_settings:
// return true;
// default:
// return super.onOptionsItemSelected(item);
// }
//
switch (item.getItemId()) {
case R.id.action_settings:
setFragmentTitle(R.string.favorites);
favoriteFragment = new FavoriteFragment();
switchContent(favoriteFragment, FavoriteFragment.ARG_ITEM_ID);
return true;
}
return super.onOptionsItemSelected(item);
}
/***
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
fragment = new FavoriteFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onDestroy () {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
if (contentFragment instanceof FavoriteFragment) {
outState.putString("content", FavoriteFragment.ARG_ITEM_ID);
} else {
outState.putString("content", AirlinesFragment.ARG_ITEM_ID);
}
super.onSaveInstanceState(outState);
}
public void switchContent(Fragment fragment, String tag) {
FragmentManager fragmentManager = getSupportFragmentManager();
while (fragmentManager.popBackStackImmediate()) ;
if (fragment != null) {
FragmentTransaction transaction = fragmentManager
.beginTransaction();
transaction.replace(R.id.content_frame, fragment, tag);
//Only FavoriteFragment is added to the back stack.
if (!(fragment instanceof AirlinesFragment)) {
transaction.addToBackStack(tag);
}
transaction.commit();
contentFragment = fragment;
}
}
protected void setFragmentTitle(int resourseId) {
setTitle(resourseId);
getSupportActionBar().setTitle(resourseId);
}
/*
* We call super.onBackPressed(); when the stack entry count is > 0. if it
* is instanceof ProductListFragment or if the stack entry count is == 0, then
* we finish the activity.
* In other words, from AirlinesFragment on back press it quits the app.
*/
#Override
public void onBackPressed() {
FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
super.onBackPressed();
} else if (contentFragment instanceof AirlinesFragment
|| fm.getBackStackEntryCount() == 0) {
finish();
}
}
#Override
public void onResume() {
super.onResume();
}
}
FavoriteFragment:
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import com.boom.kayakapp.R;
import com.boom.kayakapp.adapters.AirlinesAdapter;
import com.boom.kayakapp.model.Airlines;
import com.boom.kayakapp.util.SharedPreference;
import java.util.List;
public class FavoriteFragment extends Fragment {
public static final String ARG_ITEM_ID = "favorite_list";
ListView favoriteList;
SharedPreference sharedPreference;
List<Airlines> favorites;
Activity activity;
AirlinesAdapter airlinesAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_list, container,
false);
// Get favorite items from SharedPreferences.
sharedPreference = new SharedPreference();
favorites = sharedPreference.getFavorites(activity);
if (favorites == null) {
showAlert(getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
} else {
if (favorites.size() == 0) {
showAlert(
getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
}
favoriteList = (ListView) view.findViewById(R.id.list);
if (favorites != null) {
airlinesAdapter = new AirlinesAdapter(activity, favorites);
favoriteList.setAdapter(airlinesAdapter);
favoriteList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View arg1,
int position, long arg3) {
}
});
favoriteList
.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(
AdapterView<?> parent, View view,
int position, long id) {
ImageView button = (ImageView) view
.findViewById(R.id.favorite_button);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(activity,
favorites.get(position));
Toast.makeText(
activity,
activity.getResources().getString(
R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.heart_red);
} else {
sharedPreference.removeFavorite(activity,
favorites.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.heart_grey);
airlinesAdapter.remove(favorites
.get(position));
Toast.makeText(
activity,
activity.getResources().getString(
R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
return true;
}
});
}
}
return view;
}
public void showAlert(String title, String message) {
if (activity != null && !activity.isFinishing()) {
AlertDialog alertDialog = new AlertDialog.Builder(activity)
.create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setCancelable(false);
// setting OK Button
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
// activity.finish();
getFragmentManager().popBackStackImmediate();
}
});
alertDialog.show();
}
}
#Override
public void onResume() {
getActivity().setTitle(R.string.favorites);
super.onResume();
}
}
The error looks pretty self-explaining to me.
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.Object android.widget.ImageView.getTag()' on a null object
reference
The button you are trying to find by id after a long click is returning null so you are unable to use the getTag() method on that object.
ImageView button = (ImageView) view.findViewById(R.id.favorite_button);
So you should check if the favorite list is really containing a view (button) with that ID. Try using getActivity().findViewByID() instead to test this.

Categories

Resources