set up a list view in navigationmenu fragment - android

HEy i have problems to set up a list view ...
the app has an navigation drawler menu and the first fragment of this menu shoud show a list of my json array...
the query work but now : HOW I CAN DISPLAY THE RESULT....
MyTickets.java
package de.hoell.jobcontrol;
/**
* Created by Hoell on 16.10.2014.
*/
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import org.json.JSONException;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import de.hoell.jobcontrol.query.Functions;
public class MyTickets extends ListFragment {
private static final String TAG_SUCCESS = "success";
private static final String TAG_FIRMA = "Firma";
public MyTickets(){};
ArrayList<HashMap<String, String>> TheTickets = new ArrayList<HashMap<String, String>>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
new JSONMyTickets().execute();
//TODO:FIND OUT HOW TO SET UP A LISTVIEW :'D
}
private class JSONMyTickets extends AsyncTask<String, String, JSONObject> {
JSONArray Ticketliste = null;
#Override
protected JSONObject doInBackground(String... args) {
String user;
user = de.hoell.jobcontrol.Start.user;
Functions Function = new Functions();
JSONObject json = Function.MyTickets(user);
// check for login response
// check log cat fro response
Log.d("Create Response", json.toString());
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Ticketliste = json.getJSONArray("tickets");
for (int i = 0; i < Ticketliste.length(); i++) {
JSONObject c = Ticketliste.getJSONObject(i);
String Firma = c.getString("Firma");
String Ort = c.getString("Ort");
String Status = c.getString("Status");
HashMap<String, String> map = new HashMap<String, String>();
map.put("Firma", Firma);
map.put("Ort", Ort);
map.put("Status", Status);
TheTickets.add(map);
System.out.println("Abfrage" + TheTickets);
}
}
else{
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Slide Menu
MainActivity.java
package de.hoell.jobcontrol;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import de.hoell.jobcontrol.adapter.NavDrawerListAdapter;
import de.hoell.jobcontrol.model.NavDrawerItem;
public class
MainActivity extends Activity {
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 adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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
// MyTickets
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// Kalender
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// NewTickets
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
// Recycle the typed array
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, //nav menu toggle icon
R.string.title_activity_slidermenu, // nav drawer open - description for accessibility
R.string.title_activity_slidermenu // nav drawer close - description for accessibility
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().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);
}
}
/**
* Slide menu item click listener
* */
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#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_info:
Toast.makeText(getApplicationContext(), "Version 0.0.6", Toast.LENGTH_SHORT).show();
return true;
case R.id.action_search:
Toast.makeText(getApplicationContext(), "Searching...", Toast.LENGTH_SHORT).show();
return true;
case R.id.action_refresh:
Toast.makeText(getApplicationContext(), "Refresh...", Toast.LENGTH_SHORT).show();
return true;
default:
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_search).setVisible(!drawerOpen);
menu.findItem(R.id.action_refresh).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 MyTickets();
break;
case 1:
fragment = new Kalender();
break;
case 2:
fragment = new NewTickets();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
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;
getActionBar().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);
}
}
sry for my bad english:/

some sample code for simple list, simple ArrayAdapter:
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer);
drawer.setDrawerShadow(R.drawable.drawer_shadow, Gravity.START);
String[] myResArray = getResources().getStringArray(R.array.nav_draw_entries);
List<String> mArrayList = Arrays.asList(myResArray);
ListView listView = (ListView) findViewById(R.id.navView);
listView.setOnItemClickListener(this);
listView.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_nav_item, mArrayList));
where 'drawer_nav_item' is type TextView layout for the string entry to appear in.
where R.id.navView is the listView in the main layout including the support class for navBar
where R.array.nav_draw_entries is static array of strings defined in strings.xml

here i deletet the whole fragment and started form beginning:
here is working result :))))
TicketFragment.java
package de.hoell.jobcontrol;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.ListFragment;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
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 de.hoell.jobcontrol.query.Functions;
import de.hoell.jobcontrol.ticketlist.Tickets;
/**
* A fragment representing a list of Items.
* <p/>
* <p/>
* Activities containing this fragment MUST implement the {#link OnTicketInteractionListener}
* interface.
*/
public class TicketFragment extends ListFragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private static final String TAG_SUCCESS = "success";
private static final String TAG_FIRMA = "Firma";
ArrayList<HashMap<String, String>> TheTickets = new ArrayList<HashMap<String, String>>();
List<Tickets> ticketsList = new ArrayList<Tickets>();
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnTicketInteractionListener mListener;
// TODO: Rename and change types of parameters
public static TicketFragment newInstance(String param1, String param2) {
TicketFragment fragment = new TicketFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public TicketFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
new JSONMyTickets().execute();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnTicketInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnTicketInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
if (null != mListener) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
}
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnTicketInteractionListener {
// TODO: Update argument type and name
public void onTicketInteraction(String id);
}
public class JSONMyTickets extends AsyncTask<String, String, JSONObject> {
JSONArray Ticketliste = null;
#Override
protected JSONObject doInBackground(String... args) {
String user;
user = de.hoell.jobcontrol.Start.user;
Functions Function = new Functions();
JSONObject json = Function.MyTickets(user);
// check for login response
// check log cat fro response
Log.d("Create Response", json.toString());
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Ticketliste = json.getJSONArray("tickets");
for (int i = 0; i < Ticketliste.length(); i++) {
JSONObject c = Ticketliste.getJSONObject(i);
String Firma = c.getString("Firma");
String Ort = c.getString("Ort");
String Status = c.getString("Status");
ticketsList.add(new Tickets(Firma+ ", "+ Ort + ", "+ Status));
HashMap<String, String> map = new HashMap<String, String>();
map.put("Firma", Firma);
map.put("Ort", Ort);
map.put("Status", Status);
TheTickets.add(map);
}System.out.println("Abfrage" + TheTickets);
}
else{
}
} catch (JSONException e) {
e.printStackTrace();
}
setListAdapter(new ArrayAdapter<Tickets>(getActivity(),
android.R.layout.simple_list_item_1, android.R.id.text1, ticketsList));
}
}
}
Tickets.java
package de.hoell.jobcontrol.ticketlist;
/**
* Created by Hoell on 20.11.2014.
*/
public class Tickets {
private String id;
private String content;
public Tickets(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
#Override
public String toString(){
return id;
}
}

Related

Using Android Navigation Drawer to switch to Activity

I have succesfully implemented the navigation drawer in my MainMenu.class activity. In my navigation drawer, I have the following rows (Home, About, All reminders, Text reminders, Photo reminders, and etc). I am able to switch to their different respective activities from rows 2 onwards (e.g. from About onwards). The problem is, no matter what i do, I am unable to make the Home proceed to my intended Activity (e.g. I want to go to the MainActivity.class activity upon clicking on Home).
Here are my codes for MainMenu.class:
package sg.edu.nus.is3261proj;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.Toast;
import com.beardedhen.androidbootstrap.TypefaceProvider;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Handler;
public class MainMenu extends AppCompatActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks{
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
TypefaceProvider.registerDefaultIconSets();
db = new MyDB(this);
// get the listview
expListView = (ExpandableListView) findViewById(R.id.lvExp);
// preparing list data
prepareListData();
listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
// Listview Group click listener
expListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
// Toast.makeText(getApplicationContext(),
// "Group Clicked " + listDataHeader.get(groupPosition),
// Toast.LENGTH_SHORT).show();
return false;
}
});
// Listview Group expanded listener
expListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
Toast.makeText(getApplicationContext(),
listDataHeader.get(groupPosition) + " Expanded",
Toast.LENGTH_SHORT).show();
}
});
// Listview Group collasped listener
expListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
Toast.makeText(getApplicationContext(),
listDataHeader.get(groupPosition) + " Collapsed",
Toast.LENGTH_SHORT).show();
}
});
// Listview on child click listener
expListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
String textContain = listDataChild.get(listDataHeader.get(groupPosition)).get(childPosition);
if(textContain.contains("Date")) {
Intent i = new Intent(getBaseContext(), TextReminderDetails.class);
i.putExtra("title", listDataHeader.get(groupPosition));
i.putExtra("details", listDataChild.get(listDataHeader.get(groupPosition)).get(childPosition));
startActivity(i);
}
else {
Intent i = new Intent(getBaseContext(), PhotoReminderDetails.class);
i.putExtra("title", listDataHeader.get(groupPosition));
i.putExtra("details", listDataChild.get(listDataHeader.get(groupPosition)).get(childPosition));
startActivity(i);
}
return false;
}
});
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
/*
* Preparing the list data
*/
private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
ArrayList<String[]> records = getAllRecords();
for (int i = 0; i < records.size(); i++) {
String[] record = records.get(i);
String title = record[1];
listDataHeader.add(title);
List<String> details = new ArrayList<String>();
details.add(record[2] + "\n" + record[3]);
listDataChild.put(title,details); // Header, Child data
}
ArrayList<String[]> photoRecords = getAllPhotoRecords();
for (int i = 0; i < photoRecords.size(); i++) {
String[] record = photoRecords.get(i);
String title = record[1];
listDataHeader.add(title);
List<String> details = new ArrayList<String>();
details.add(record[3]);
listDataChild.put(title,details); // Header, Child data
}
}
public void onClick_addNewReminder(View view){
Intent intent = new Intent(this, NewReminder.class);
this.startActivity(intent);
}
MyDB db;
public ArrayList<String[]> getAllRecords(){
db.open();
Cursor c = db.getAllRecords();
ArrayList<String[]> records = new ArrayList<String[]>();
if(c.moveToFirst()){
do {
String[] record = {
c.getString(0), c.getString(1), c.getString(2), c.getString(3)};
records.add(record);
} while (c.moveToNext());
}
db.close();
return records;
}
public ArrayList<String[]> getAllPhotoRecords(){
db.open();
Cursor c = db.getAllPhotoRecords();
ArrayList<String[]> photoRecords = new ArrayList<String[]>();
if(c.moveToFirst()){
do {
String[] photoRecord = {
c.getString(0), c.getString(1), c.getString(2), c.getString(3)};
photoRecords.add(photoRecord);
} while (c.moveToNext());
}
db.close();
return photoRecords;
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
.commit();
}
public void onSectionAttached(int number) {
Intent intent;
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
intent = new Intent(this, AboutActivity.class);
startActivity(intent);
break;
case 3:
mTitle = getString(R.string.title_section3);
intent = new Intent(this, MainMenu.class);
startActivity(intent);
break;
case 4:
mTitle = getString(R.string.title_section4);
intent = new Intent(this, TextReminderMenu.class);
startActivity(intent);
break;
case 5:
mTitle = getString(R.string.title_section5);
intent = new Intent(this, PhotoReminderMenu.class);
startActivity(intent);
break;
case 6:
mTitle = getString(R.string.title_section6);
break;
case 7:
mTitle = getString(R.string.title_section7);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainMenu) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
and NavigationDrawerFragment.class:
package sg.edu.nus.is3261proj;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
/**
* Fragment used for managing interactions for and presentation of a navigation drawer.
* See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction">
* design guidelines</a> for a complete explanation of the behaviors implemented here.
*/
public class NavigationDrawerFragment extends Fragment {
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
/**
* Per the design guidelines, you should show the drawer on launch until the user manually
* expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
public NavigationDrawerFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
// Select either the default item (0) or the last selected item.
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Indicate that this fragment would like to influence the set of actions in the action bar.
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mDrawerListView = (ListView) inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
new String[]{
getString(R.string.title_section1),
getString(R.string.title_section2),
getString(R.string.title_section3),
getString(R.string.title_section4),
getString(R.string.title_section5),
getString(R.string.title_section6),
getString(R.string.title_section7),
}));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* #param fragmentId The android:id of this fragment in its activity's layout.
* #param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
// The user manually opened the drawer; store this flag to prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.global, menu);
showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(R.string.app_name);
}
private ActionBar getActionBar() {
return ((AppCompatActivity) getActivity()).getSupportActionBar();
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
public static interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
}
On click of home button write below code so you can go to main activity.
Intent main= new Intent(mContext, MainActivity.class);
main.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP|Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(main);

Android new Intent with fragment

I'm developing Android application that uses fragment. The menu list will be appear when you click the top left menu icon. After clicking a menu item, it creates a new Intent and start a new Activity that also uses fragment with the same menu order. The problem is when the new activity started, it will immediately call the Intent of the first menu item. I don't want to change the order for each activity but I want the app only switch to other activity when user click on a menu item. How to make program like that?
For example, if this is the onSectionAttached method of Activity1. It will immediately switch to MainActivity when Activity1 started. How to make the app only switch to MainActivity if user click on the menu?
Bakteri.java
package com.example.app02;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Bakteri extends Activity implements
NavigationDrawerFragment.NavigationDrawerCallbacks {
static DBHelper dbhelper;
static Cursor c=null;
static ListView list;
/**
* Fragment managing the behaviors, interactions and presentation of the
* navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in
* {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment) getFragmentManager()
.findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getFragmentManager();
fragmentManager
.beginTransaction()
.replace(R.id.container,
PlaceholderFragment.newInstance(position + 1)).commit();
Intent intent;
switch(position){
case 0:
//To start a new activity
intent = new Intent(this,MainActivity.class);
startActivity(intent);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
protected Context context;
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
//access database
dbhelper = new DBHelper(getActivity());
try {
dbhelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
dbhelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
final TextView txvMain = (TextView) rootView.findViewById(R.id.result);
txvMain.setText("Bakteri");
list = (ListView) rootView.findViewById(R.id.list);
final EditText search = (EditText) rootView.findViewById(R.id.search);
search.addTextChangedListener(new TextWatcher(){
public void onTextChanged(CharSequence s, int start, int before, int count){
ArrayList<String> list_title = new ArrayList();
ArrayList<String> list_content = new ArrayList();
if(!s.equals("")){
c=dbhelper.query("bakteri", null, "nama_ilmiah LIKE '%" + search.getText() + "%'", null, null,null, null);
String res = "";
if(c.moveToFirst())
{
do {
list_title.add(c.getString(0));
list_content.add(c.getString(1));
res += c.getString(0) + "\n" + c.getString(1) + "\n" + "\n";
} while (c.moveToNext());
}
String[] title = new String[ list_title.size() ];
list_title.toArray(title);
String[] content = new String[ list_content.size() ];
list_content.toArray(content);
CustomList adapter = new CustomList(getActivity(), title, content);
list.setAdapter(adapter);
//txvMain.setText(res);
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){
}
public void afterTextChanged(Editable s){
}
});
//set a drawable as the background of the textView
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (dbhelper != null) {
dbhelper.close();
}
}
}
NavigationDrawerFragment.java
package com.example.app02;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
/**
* Fragment used for managing interactions for and presentation of a navigation
* drawer. See the <a href=
* "https://developer.android.com/design/patterns/navigation-drawer.html#Interaction"
* > design guidelines</a> for a complete explanation of the behaviors
* implemented here.
*/
public class NavigationDrawerFragment extends Fragment {
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
/**
* Per the design guidelines, you should show the drawer on launch until the
* user manually expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
public NavigationDrawerFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read in the flag indicating whether or not the user has demonstrated
// awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState
.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
// Select either the default item (0) or the last selected item.
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Indicate that this fragment would like to influence the set of
// actions in the action bar.
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mDrawerListView = (ListView) inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
mDrawerListView
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
selectItem(position);
}
});
mDrawerListView.setAdapter(new ArrayAdapter<String>(getActionBar()
.getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1, new String[] {
getString(R.string.title_home),
getString(R.string.title_section1),
getString(R.string.title_section2),
getString(R.string.title_section3),
getString(R.string.title_section4),
getString(R.string.title_section5)}));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null
&& mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Users of this fragment must call this method to set up the navigation
* drawer interactions.
*
* #param fragmentId
* The android:id of this fragment in its activity's layout.
* #param drawerLayout
* The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer
// opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
// set up the drawer's list view with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.navigation_drawer_open, /*
* "open drawer" description for
* accessibility
*/
R.string.navigation_drawer_close /*
* "close drawer" description for
* accessibility
*/
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().invalidateOptionsMenu(); // calls
// onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
// The user manually opened the drawer; store this flag to
// prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true)
.apply();
}
getActivity().invalidateOptionsMenu(); // calls
// onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce
// them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException(
"Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar.
// See also
// showGlobalContextActionBar, which controls the top-left area of the
// action bar.
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.global, menu);
showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if (item.getItemId() == R.id.action_example) {
Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT)
.show();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to
* show the global app 'context', rather than just what's in the current
* screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(R.string.app_name);
}
private ActionBar getActionBar() {
return getActivity().getActionBar();
}
/**
* Callbacks interface that all activities using this fragment must
* implement.
*/
public static interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
}
Remove onSectionAttached logic.
And keep it only onNavigationDrawerItemSelected or whatever your callback is called.

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.

Action bar Icon menu issue on Fragment

well just when I solved an issue another one is comming right there, and I don't know if I'm violating any rule of this forum posting everything I got an issue, I hope not, but here I go again, I'm trying to add an Icon menu to the Action bar within my fragment, on my parent activity I don't know have action bar menu, so I don't trying to replace the menu on my fragment, because I just use a DrawerLayout to drawer a list menu and it's all, but in some specific Fragments I want to show some action bar icon menu, I've search in the forum before posting but I didn't find something than can help me, because I'm not sure what is going on, I did the two stepts to show and action bar menu on fragments read on others post, I even tried using the default menu.xml created by android studio, in two differents fragment, but for some reason the menu is not being showing on fragments Action bar, I'm not sure if I have to do something on my parent Activity first, but here are my both code Activity and Fragmen
Parent Activity code which is declared the DrawerLayout menu list
import java.util.ArrayList
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
private String[] titulos;
private DrawerLayout NavDrawerLayout;
private ListView NavList;
private ArrayList<Item_objct> NavItms;
private TypedArray NavIcons;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
Fragment ventas;
NavigationAdapter NavAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity__main);
NavDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavList = (ListView) findViewById(R.id.lista);
View header = getLayoutInflater().inflate(R.layout.header, null);
NavList.addHeaderView(header);
NavIcons = getResources().obtainTypedArray(R.array.navigation_iconos);
titulos = getResources().getStringArray(R.array.nav_options);
NavItms = new ArrayList<Item_objct>();
NavItms.add(new Item_objct(titulos[0], NavIcons.getResourceId(0, -1)));
NavItms.add(new Item_objct(titulos[1], NavIcons.getResourceId(1, -1)));
NavItms.add(new Item_objct(titulos[2], NavIcons.getResourceId(2, -1)));
NavItms.add(new Item_objct(titulos[3], NavIcons.getResourceId(3, -1)));
NavItms.add(new Item_objct(titulos[4], NavIcons.getResourceId(4, -1)));
NavItms.add(new Item_objct(titulos[5], NavIcons.getResourceId(5, -1)));
NavAdapter= new NavigationAdapter(this,NavItms);
NavList.setAdapter(NavAdapter);
mTitle = mDrawerTitle = getTitle();
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
NavDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* Icono de navegacion*/
R.string.app_name, /* "open drawer" description */
R.string.hello_world /* "close drawer" description */
) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
Log.e("Cerrado completo", "!!");
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
Log.e("Apertura completa", "!!");
}
};
NavDrawerLayout.setDrawerListener(mDrawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
NavList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
MostrarFragment(position);
}
});
ventas = new VentasFragment();
}
private void MostrarFragment(int position) {
Fragment fragment = null;
switch (position) {
case 0:
//fragment = new HomeFragment();
break;
case 1:
fragment = ventas;
break;
case 4:
fragment = new customerFragment();
break;
default:
//si no esta la opcion mostrara un toast y nos mandara a Home
Toast.makeText(getApplicationContext(),"Opcion "+titulos[position-1]+"no disponible!", Toast.LENGTH_SHORT).show();
// fragment = new HomeFragment();
position=1;
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
NavList.setItemChecked(position, true);
NavList.setSelection(position);
if(position > 0)
setTitle(titulos[position-1]);
else
setTitle("Balance General");
NavDrawerLayout.closeDrawer(NavList);
} else {
Log.e("Error ", "MostrarFragment"+position);
}
}
#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);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Pass the event to ActionBarDrawerToggle, if it returns
// true, then it has handled the app icon touch event
if (mDrawerToggle.onOptionsItemSelected(item)) {
Log.e("mDrawerToggle pushed", "x");
return true;
}
// Handle your other action bar items...
return super.onOptionsItemSelected(item);
}
}
Fragment Code where I want to implement the action bar menu
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.ToggleButton;
public class customerFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public static customerFragment newInstance(String param1, String param2) {
customerFragment fragment = new customerFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public customerFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_customer, container, false);
// Inflate the layout for this fragment
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
//mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
//super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.main, menu);
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
As you see on Fragment Code, I call setHasOptionMenu(true); whithin onCreat() in the last line, and I inflate my menu.xml whithin onCreateOptionMenu(), but I doesn't showing anything anyways, I'm not pretty sure about what is going on, why It doesn't work anyways.
Thank you so much beforehand, and sorry if the issue is quickly obvious, I'm beginner yet and I don't understand a lot of things of Methods Overriding and Callings.
What if you try to add items programmatically instead of inflater.inflate(R.menu.main, menu), like this:
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.add(0, R.id.your_id, 0,
getResources().getString(R.string.your_string))
.setIcon(R.drawable.your_icon)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
}
That's working for me.

listview findviewbyId returning null. when a layout is generated by fragment

Im trying to load a layout to a list view that is generated by fragment. after the fragment that has the listview is loaded. im calling a async to insert data in the listview generated by fragment in the mainactivity. but the listview is returning null here is my code.
Main Activity: This calls the fragment when a user choose a menu to the navigationdrawer.
package medapp.app;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends Activity
{
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mActions;
public JSONArray blogPostData;
View v;
#Override
protected void onCreate(Bundle savedInstanceState) {
ListView listView;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mActions = getResources().getStringArray(R.array.action_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// set a custom shadow that overlays the main content when the drawer opens
//mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mActions));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null)
{
selectItem(0);
}
}
//public void onItemClick(AdapterView<?> adapter, View view,int position, long id)
//{
// Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
// Toast.LENGTH_SHORT).show();
//}
public void articleList()
{
if (blogPostData == null)
{
//
}
else
{
try
{
String[] blogPostTitle = new String[blogPostData.length()];
for (int i = 0; i < blogPostData.length(); i++)
{
JSONObject jsonObject = blogPostData.getJSONObject(i);
String title = jsonObject.getString("title");
title = Html.fromHtml(title).toString();
blogPostTitle[i] = title;
}
ListView listView1 = (ListView) findViewById(R.id.article_list);
ArrayAdapter<String> arrayAdapter1 = new ArrayAdapter<String>(this, R.layout.layout_listitem, R.id.titleTV, blogPostTitle);
listView1.setAdapter(arrayAdapter1);
Log.e("MESSAGE", "JSON " + blogPostData);
} catch (JSONException e) {
Log.e("TAG", "Exception Caught: ", e);
}
}
}
public void signInClick(View v) {
//Button button = (Button) v;
//startActivity(new Intent(getApplicationContext(), PatientActivity.class));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
//boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
return super.onPrepareOptionsMenu(menu);
}
/* */
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
/* The click listener for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
int pos;
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
v = view;
}
}
private void selectItem(int position) {
// update the main content by replacing fragments
Fragment fragment = new ActionFragment();
Bundle args = new Bundle();
args.putInt(ActionFragment.ARG_ACTION1_NUMBER, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mActions[position]);
mDrawerLayout.closeDrawer(mDrawerList);
if (position == 1)
{
PostController postController = new PostController();
postController.execute();
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().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 toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
this is the fragment that calls the layout to be shown then goes back to the main activity.
package medapp.app;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ActionFragment extends Fragment
{
protected View rootView;
public static final String ARG_ACTION1_NUMBER = "Fragment_layout";
/*public JSONArray blogData;
public String[] blogPostTitle;*/
public ActionFragment() {
// Empty constructor required for fragment subclasses
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_layout, container, false);
int i = getArguments().getInt(ARG_ACTION1_NUMBER);
if (i == 0)
{
rootView = inflater.inflate(R.layout.fragment_layout, container, false);
}
else if (i == 1) {
rootView = inflater.inflate(R.layout.fragment_articles, container, false);
//ListView listView1 = (ListView) rootView.findViewById(R.id.article_list);
//ArrayAdapter<Layout> arrayAdapter1 = new ArrayAdapter<Layout>(getActivity(), R.layout.layout_listitem);
//listView1.setAdapter(arrayAdapter1);
} else if (i == 2)
{
rootView = inflater.inflate(R.layout.fragment_news, container, false);
} else if (i == 3) {
rootView = inflater.inflate(R.layout.fragment_signin, container, false);
}
return rootView;
}
}
then the main activity calls the async background to get the data.
package medapp.app;
import android.os.AsyncTask;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONArray;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
/**
* Created by MacBookPro on 5/8/14.
*/
public class PostController extends AsyncTask<Object, Void, JSONArray> {
#Override
protected JSONArray doInBackground(Object... arg0)
{
String result = "No data available";
JSONArray jsonResponse = null;
try
{
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
//TODO: URL ADDRESS for Articles.
HttpGet httpGet = new HttpGet("http://localhost/medapp/public/webservices/post");
httpGet.setHeader("Content-type", "application/json");
InputStream inputStream = null;
HttpResponse response = httpclient.execute(httpGet);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line);
}
result = sb.toString();
jsonResponse = new JSONArray(result);
// TODO: Remove log.
Log.d("TAG", String.valueOf(jsonResponse));
}
catch (MalformedURLException e)
{
Log.e("TAG", "exception caught: ", e);
}
catch (IOException e)
{
Log.e("TAG", "exception caught: ", e);
}
catch (Exception e)
{
Log.e("TAG", "exception caught: ", e);
}
return jsonResponse;
}
#Override
protected void onPostExecute(JSONArray result)
{
MainActivity mainActivity = new MainActivity();
mainActivity.blogPostData = result;
mainActivity.articleList();
}
}
Log file::
05-09 05:59:59.249 1474-1474/medapp.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: medapp.app, PID: 1474
java.lang.NullPointerException
at android.app.Activity.findViewById(Activity.java:1884)
at medapp.app.MainActivity.articleList(MainActivity.java:116)
at medapp.app.PostController.onPostExecute(PostController.java:82)
at medapp.app.PostController.onPostExecute(PostController.java:22)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)

Categories

Resources