custom adapter and object cannot found - android

I have a MainActivity that has a navigation drawer that calls a fragment to load a ListView. That ListView calls an xml to be the layout of the listitem. I am fetching the data from a webservice and wants to display 4 data on each list item. I created a CustomAdapter as mentioned in some tutorial to display data. My problem is I store the data to a String array and don't know how to put it in the object I created then pass to the Adapter then display
MAIN ACTIVITY
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
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// Find People
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// Photos
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
// Recycle the typed array
navMenuIcons.recycle();
// 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.app_name, // nav drawer open - description for accessibility
R.string.app_name // 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);
}
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
}
#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_settings:
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_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#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);
}
/**
* 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);
}
}
/**
* 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 SearchFragment();
break;
case 2:
fragment = new SignInFragment();
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");
}
}
}
HOME FRAGMENT that calls the xml with the listview
public class HomeFragment extends Fragment {
/*Layout Variables*/
protected ProgressBar mProgressBar;
protected JSONArray blogPostData;
protected TextView mTextView;
/*Variables to be displayed*/
protected String[] blogPostTitle;
protected String[] blogPostDate;
protected String[] blogPostAuthor;
/*System Variables*/
private ListView listView;
private View rootView;
articleListObject object;
public HomeFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_home, container, false);
listView = (ListView) rootView.findViewById(R.id.article_list);
mProgressBar = (ProgressBar) rootView.findViewById(R.id.progressBarHome);
mTextView = (TextView) rootView.findViewById(R.id.networkCheck);
mTextView.setText("Please Wait while we load the data!");
mProgressBar.setVisibility(View.VISIBLE);
ArticleController articleController = new ArticleController(mListener);
articleController.execute();
return rootView;
}
public MyListener mListener = new MyListener(){
#Override
public void onComplete(JSONArray result)
{
blogPostData = result;
updateArticleList();
mProgressBar.setVisibility(View.INVISIBLE);
mTextView.setVisibility(View.INVISIBLE);
/*List<String> stringList = new ArrayList<String>(Arrays.asList(blogPostTitle));
ArrayAdapter<String> arrayAdapter1 = new ArrayAdapter<String>(getActivity(), R.layout.layout_listview_article, R.id.titleTV, stringList);
listView.setAdapter(arrayAdapter1);*/
ArrayList<articleListObject> objects = new ArrayList<articleListObject>();
articleListAdapter articleAdapter = new articleListAdapter(objects);
listView.setAdapter(articleAdapter);
}
};
protected void updateArticleList()
{
try
{
blogPostTitle = new String[blogPostData.length()];
blogPostDate = new String[blogPostData.length()];
blogPostAuthor = 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();
String date = jsonObject.getString("created_at");
date = Html.fromHtml(date).toString();
String author = jsonObject.getString("author");
author = Html.fromHtml(author).toString();
blogPostTitle[i] = title;
blogPostDate[i] = date;
blogPostAuthor[i] = author;
}
} catch (JSONException e)
{
e.printStackTrace();
}
}
}
This is the background async
public class ArticleController extends AsyncTask<Object, Void, JSONArray> {
MyListener mListener;
public ArticleController(MyListener listenr) {
mListener = listenr;
}
#Override
protected JSONArray doInBackground(Object... arg0)
{
String result = "No data available";
JSONArray jsonResponse = null;
try
{
HttpClient httpclient = new DefaultHttpClient();
//TODO: URL ADDRESS for Articles.
HttpPost httpPost = new HttpPost("http://localhost/****/public/webservices/post");
/*httpPost.setHeader("Content-type", "application/json");*/
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);
nameValuePair.add(new BasicNameValuePair("page", "1"));
nameValuePair.add(new BasicNameValuePair("limit","10"));
nameValuePair.add(new BasicNameValuePair("category","0"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
/*InputStream inputStream = null;*/
HttpResponse response = httpclient.execute(httpPost);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
result = sb.toString();
jsonResponse = new JSONArray(result);
Log.d("RESULT: ", result);
}
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)
{
HomeFragment homeFragment = new HomeFragment();
homeFragment.blogPostData = result;
mListener.onComplete(result);
}
}
MY CustomAdapter
public class articleListAdapter extends BaseAdapter {
private LayoutInflater inflater;
private ArrayList<articleListObject> objects;
private class ViewHolder {
TextView textView1;
TextView textView2;
TextView textView3;
}
public articleListAdapter(Context context, ArrayList<articleListObject> objects) {
inflater = LayoutInflater.from(context);
this.objects = objects;
}
public int getCount() {
return objects.size();
}
public articleListObject getItem(int position) {
return objects.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.layout_listview_article, null);
holder.textView1 = (TextView) convertView.findViewById(R.id.titleTV);
holder.textView2 = (TextView) convertView.findViewById(R.id.dateTV);
holder.textView3 = (TextView) convertView.findViewById(R.id.authorTV);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textView1.setText(objects.get(position).getPostTitle());
holder.textView2.setText(objects.get(position).getPostDate());
holder.textView3.setText(objects.get(position).getPostAuthor());
return convertView;
}
}
my constructor
public class articleListObject {
/*Variables to be displayed*/
protected String postTitle;
protected String postDate;
protected String postAuthor;
public articleListObject(String postTitle, String postDate, String postAuthor) {
this.postTitle = postTitle;
this.postDate = postDate;
this.postAuthor = postAuthor;
}
public String getPostTitle() {
return postTitle;
}
public String getPostDate() {
return postDate;
}
public String getPostAuthor() {
return postAuthor;
}
}

Related

How to implements onclick listview in fragment?

I'm trying to give onClick in my listview . I'm using menu drawer here is my mainActivity
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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);
displaySelectedScreen(R.id.nav_item);
}
#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) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
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.
displaySelectedScreen(item.getItemId());
return true;
}
private void displaySelectedScreen(int itemId) {
FragmentManager fm = getSupportFragmentManager();
Fragment Fragment = null;
switch (itemId) {
case R.id.nav_item:
Fragment = new Item();
break;
case R.id.nav_do:
Fragment = new Deliveryorder();
break;
}
if (Fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, Fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
}
then here is one of my fragment
public class Item extends Fragment implements View.OnClickListener {
ListView listView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_item, container, false);
listView = (ListView) rootView.findViewById(R.id.listView1);
return rootView;
}
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "TEST", Toast.LENGTH_LONG).show();
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Menu Item");
getJSON("http://192.168.3.223:84/fppb/andro_login/fppb");
}
private void loadIntoListView(String json) throws JSONException {
List<Itemadapter> items = new ArrayList<Itemadapter>();
JSONArray jsonArray = new JSONArray(json);
String[] ba = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
String code = obj.getString("ItemCode");
String name = obj.getString("ItemName");
String photo = obj.getString("PhotoName");
items.add(new Itemadapter(code, name,photo));
}
//Toast.makeText(getActivity(), items.toString(), Toast.LENGTH_LONG).show();
ArrayAdapter<Itemadapter> mArrayAdapter = new ArrayAdapter<Itemadapter>(getActivity(),android.R.layout.simple_expandable_list_item_1,items);
listView.setAdapter(mArrayAdapter);
}
private void getJSON(final String urlWebService) {
class GetJSON extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
loadIntoListView(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(urlWebService);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetJSON getJSON = new GetJSON();
getJSON.execute();
}
}
when i run my app and open Item.java the data is showing up, but when i click one row there's nothing happen. I already add this
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "TEST", Toast.LENGTH_LONG).show();
}
How can i fix it ? thanks in advance and sorry for my english.
You need to implement a listener :
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getActivity(), "TEST", Toast.LENGTH_LONG).show();
}
});
Hello, Please check out the following link, here you get the complete guidance about how to implement listview in fragment and how to impalement click listener on listview items.

Android activity crashes when populating the listview with data from external databse in the form of JSON

here is the logcat error in image:
with error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.erp.navigationdrawer/com.erp.navigationdrawer.Notices}: java.lang.NullPointerException
This is my code of main activity which other activity extends to have a navigation drawer now on clicking notices in navigation drawer webservice is called and data comes but activity crashes and shows up:
ERROR AT mDrawerToggle.syncState();
Code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawer);
// if (savedInstanceState == null) {
// // on first time display view for first nav item
// // displayView(0);
// }
}
public void set(String[] navMenuTitles, TypedArray navMenuIcons) {
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items
if (navMenuIcons == null) {
for (int i = 0; i < navMenuTitles.length; i++) {
navDrawerItems.add(new NavDrawerItem(navMenuTitles[i]));
}
} else {
for (int i = 0; i < navMenuTitles.length; i++) {
navDrawerItems.add(new NavDrawerItem(navMenuTitles[i],
navMenuIcons.getResourceId(i, -1)));
}
}
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
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
// getSupportActionBar().setIcon(R.drawable.ic_drawer);
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
supportInvalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
supportInvalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
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) {
// getSupportMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
}
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) {
switch (position) {
case 0:
Intent intent = new Intent(this, Courses.class);
startActivity(intent);
finish();// finishes the current activity
break;
case 1:
Intent intent2 = new Intent(this, Notices.class);
startActivity(intent2);
finish();
break;
case 2:
Intent intent3 = new Intent(this, Placements.class);
startActivity(intent3);
finish();
break;
default:
break;
}
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
mDrawerLayout.closeDrawer(mDrawerList);
}
#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);
}
}
Below is the code for Notices activity that crashes up **AND ITS IS THE ONLY ACTIVITY AMONG NAVIGATION DRAWER TO CRASH:
private void loadservice(String url) {
// Make RESTful webservice call using AsyncHttpClient object
AsyncHttpClient client = new AsyncHttpClient();
client.get(url, null, new AsyncHttpResponseHandler() {
// When the response returned by REST has Http response
// code '200'
#Override
public void onSuccess(String response) {
try {
JSONArray obj = new JSONArray(response);
for (int i = 0; i < obj.length(); i++) {
JSONObject jsonChild = obj.getJSONObject(i);
heading = jsonChild.optString("heading").toString();
content = jsonChild.optString("content").toString();
date = jsonChild.optString("date".toString());
System.out.println(heading + content + date);
entity = new NoticeEntity();
entity.setNotice_heading(heading);
entity.setNotice_content(content);
entity.setNotice_date(date);
arraylist.add(entity);
}
} catch (JSONException e) {
System.out.println(" Exception raised : " + e.getMessage());
e.printStackTrace();
}
}
});
ListView listView = (ListView) findViewById(R.id.notice_listview);
NoticeAdapter adapter = new NoticeAdapter(this, R.layout.custom_notice,
arraylist);
listView.setAdapter(adapter);
}
Here is my **NOTICE ADAPTER ** code below:
public class NoticeAdapter extends ArrayAdapter<NoticeEntity> {
private Context context;
public NoticeAdapter(Context context, int resourceId,
ArrayList<NoticeEntity> items) {
super(context, resourceId, items);
this.context = context;
}
/* private view holder class */
private class ViewHolder {
TextView heading;
TextView content;
TextView date;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
NoticeEntity entity = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.custom_notice, null);
holder = new ViewHolder();
holder.heading = (TextView) convertView
.findViewById(R.id.txtvw_notice_heading);
holder.content = (TextView) convertView
.findViewById(R.id.txtvw_notice_content);
holder.date = (TextView) convertView
.findViewById(R.id.txtvw_notice_date);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.heading.setText(entity.getNotice_heading());
holder.content.setText(entity.getNotice_content());
holder.date.setText(entity.getNotice_date());
return convertView;
}
}
onPostCreate will be executed immediately after onCreate. You're accessing a member variable called mDrawerToggle in your onPostCreate, but it is not assigned before onPostCreate is called. It is normal convention to assign all your views to member variables during onCreate immedately after you call setContentView. In your case, it's being assigned in a method called "set" where I can't see that it's ever being called.
Try moving all the view-related code from set into onCreate.

onback pressed data not showing in fragments

I am using navigation drawer in my app,I have fragments like F1,F2 and so on..and in every fragment I am parsing data and display in listview,everything is works fine if I go through my app like F1>F2>F3 and so on..but the issue is if I go from F3 to F2,the data which I had in my F2 fragments is not showing,and display only blank page,what is the issue?Can any one help?
My F1
public class Categriesdrawers extends Fragment{
private ImageView drwr;
private SlidingDrawer sldrwr;
private ProgressDialog pDialog;
JSONArray categorylist=null;
private ListView listview;
private ArrayList<HashMap<String,String>> aList;
private static String INTEREST_ACCEPT_URL = "http:.ashx?action=category";
private static final String INTEREST_ACCEPT="categorylist";
private static final String INTERESTACCEPT_USER_ID="Id";
private static final String INTEREST_ACCEPT_NAME="categoryname";
private CustomAdapterCatagory adapter;
private TextView noacpt;
private ListView catlist;
#SuppressWarnings("deprecation")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.tests, container, false);
drwr=(ImageView)v.findViewById(R.id.handle);
sldrwr=(SlidingDrawer)v.findViewById(R.id.bottom);
sldrwr.open();
new LoadAlbums().execute();
sldrwr.setOnDrawerOpenListener(new OnDrawerOpenListener() {
#Override
public void onDrawerOpened() {
new LoadAlbums().execute();
}
});
catlist=(ListView)v.findViewById(R.id.substitute_list);
catlist.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Organization tf = new Organization();
Bundle bundle = new Bundle();
tf.setArguments(bundle);
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.mainContent, tf);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
}
});
return v;
}
class LoadAlbums extends AsyncTask<String, String, ArrayList<HashMap<String,String>>> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Categriesdrawers.this.getActivity());
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(true);
pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
pDialog.setCancelable(false);
pDialog.show();
}
protected ArrayList<HashMap<String,String>> doInBackground(String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
ArrayList<HashMap<String,String>> data = new ArrayList<HashMap<String, String>>();
String jsonStr = sh.makeServiceCall(INTEREST_ACCEPT_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
categorylist = jsonObj.getJSONArray(INTEREST_ACCEPT);
for (int i = 0; i < categorylist.length(); i++) {
JSONObject c = categorylist.getJSONObject(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(INTERESTACCEPT_USER_ID, c.getString(INTERESTACCEPT_USER_ID));
map.put(INTEREST_ACCEPT_NAME,c.getString(INTEREST_ACCEPT_NAME));
// adding HashList to ArrayList
data.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return data;
}
protected void onPostExecute(ArrayList<HashMap<String,String>> result) {
super.onPostExecute(result);
// dismiss the dialog after getting all albums
if (pDialog.isShowing())
pDialog.dismiss();
// updating UI from Background Thread
if(aList == null){
aList = new ArrayList<HashMap<String, String>>();
aList.addAll(result);
adapter = new CustomAdapterCatagory(getActivity(),result);
catlist.setAdapter(adapter);
}else{
aList.addAll(result);
adapter.notifyDataSetChanged();
}
}
}
MainActivity
public class MainActivity extends Activity {
ListView mDrawerList;
RelativeLayout mDrawerPane;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private CharSequence mTitle;
ArrayList<NavItem> mNavItems = new ArrayList<NavItem>();
private CharSequence mDrawerTitle;
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actionBar=getActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(Color.argb(255, 235, 139, 36)));
mTitle = mDrawerTitle = getTitle();
mNavItems.add(new NavItem("All Post", R.drawable.allpost));
mNavItems.add(new NavItem("Categories", R.drawable.allpost));
mNavItems.add(new NavItem("All Bloggers", R.drawable.allpost));
mNavItems.add(new NavItem("About Us", R.drawable.about));
mNavItems.add(new NavItem("Rate US", R.drawable.rates));
// DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
// Populate the Navigtion Drawer with options
mDrawerPane = (RelativeLayout) findViewById(R.id.drawerPane);
mDrawerList = (ListView) findViewById(R.id.navList);
DrawerListAdapter adapter = new DrawerListAdapter(this, mNavItems);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
selectItemFromDrawer(position);
}
});
getActionBar().setDisplayHomeAsUpEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_view, //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) {
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)
{
selectItemFromDrawer(0);
}
}
#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) {
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);
}
}
private void selectItemFromDrawer(int position) {
Fragment fragment=null;
switch (position) {
case 0:
fragment=new AllPost();
break;
case 1:
fragment=new Categriesdrawers();
break;
case 2:
fragment=new AllBloggerList();
break;
/*case 3:
fragment=new Aboutus();
break;
*/
default:
break;
}
if(fragment!=null)
{
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.mainContent, fragment)
.commit();
mDrawerList.setItemChecked(position, true);
setTitle(mNavItems.get(position).mTitle);
mDrawerLayout.closeDrawer(mDrawerPane);
}
/*Fragment fragment = new PreferencesFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.mainContent, fragment)
.commit();
mDrawerList.setItemChecked(position, true);
setTitle(mNavItems.get(position).mTitle);
// Close the drawer
mDrawerLayout.closeDrawer(mDrawerPane);*/
}
class NavItem {
String mTitle;
String mSubtitle;
int mIcon;
public NavItem(String title, int icon) {
mTitle = title;
mIcon = icon;
}
}
class DrawerListAdapter extends BaseAdapter {
Context mContext;
ArrayList<NavItem> mNavItems;
public DrawerListAdapter(Context context, ArrayList<NavItem> navItems) {
mContext = context;
mNavItems = navItems;
}
#Override
public int getCount() {
return mNavItems.size();
}
#Override
public Object getItem(int position) {
return mNavItems.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.drawer_item, null);
}
else {
view = convertView;
}
TextView titleView = (TextView) view.findViewById(R.id.title);
ImageView iconView = (ImageView) view.findViewById(R.id.icon);
titleView.setText( mNavItems.get(position).mTitle );
iconView.setImageResource(mNavItems.get(position).mIcon);
return view;
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
}
Please call addToBackStack(null) when you perform fragment transaction.
fragmentManager.beginTransaction()
.replace(R.id.mainContent, fragment)
.addToBackStack(null)
.commit();
Please update your OnCreateView() as below:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (view != null) {
if (view.getParent() != null) {
((ViewGroup)view.getParent()).removeView(view);
}
return view;
}
View v=inflater.inflate(R.layout.tests, container, false);
I hope this helps

update listview when i remove item on it

I'm very newly into this programming language can somebody help me what to do.
Here is my screenshot# http://imgur.com/hGQCHpk
the listview is not updating if i click the home fragment where listview contains
MainActivity.Java
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[] navLogout;
String[] navMenuTitles;
TypedArray navMenuIcons;
ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
#SuppressLint("NewApi")
#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_not_login);
// 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)));
// login
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons
.getResourceId(1, -1)));
// register
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons
.getResourceId(2, -1)));
// classic brownies
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons
.getResourceId(3, -1)));
// cupcakes
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons
.getResourceId(3, -1)));
// cookies
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons
.getResourceId(3, -1)));
// feedback
navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons
.getResourceId(4, -1)));
// about
navDrawerItems.add(new NavDrawerItem(navMenuTitles[7], navMenuIcons
.getResourceId(5, -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.app_name, // nav drawer open - description for
// accessibility
R.string.app_name // 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) {
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;
}
Fragment fragment = null;
Fragment newFragment = new AboutFragment();
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_search:
Toast.makeText(this, "search selected", Toast.LENGTH_SHORT).show();
break;
case R.id.action_shoppingcart:
FragmentTransaction transaction = getFragmentManager()
.beginTransaction();
transaction.replace(R.id.frame_container, newFragment,
"AboutFragment");
transaction.commit();
getActionBar().setTitle("Shopping cart");
return true;
default:
break;
}
return true;
}
/* *
* 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_shoppingcart).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 LoginFragment();
break;
case 2:
fragment = new RegisterFragment();
break;
case 3:
fragment = new ClassicBrowniesFragment();
break;
case 4:
fragment = new CupcakesFragment();
break;
case 5:
fragment = new CookiesFragment();
break;
case 6:
fragment = new FeedbackFragment();
break;
case 7:
fragment = new AboutFragment();
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);
}
}
HomeFragment.java
public class HomeFragment extends Fragment implements OnItemClickListener {
String[] member_names;
TypedArray product_icons;
String[] statues;
String[] contactType;
List<RowItem> rowItems;
ListView mylistview;
CustomAdapter myadapter;
CustomAdapter newadapter;
EditText editsearch;
public HomeFragment() {
}
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_home, container, false);
rowItems = new ArrayList<RowItem>();
member_names = getResources().getStringArray(R.array.Member_names);
product_icons = getResources().obtainTypedArray(R.array.product_icons);
statues = getResources().getStringArray(R.array.statues);
for (int i = 0; i < member_names.length; i++) {
RowItem item = new RowItem(member_names[i],
product_icons.getResourceId(i, -1), statues[i]);
rowItems.add(item);
}
mylistview = (ListView) rootView.findViewById(R.id.list);
mylistview.setItemsCanFocus(true);
//
final CustomAdapter adapter = new CustomAdapter(getActivity(), rowItems);
mylistview.setAdapter(adapter);
product_icons.recycle();
mylistview.setOnItemClickListener(this);
mylistview.setScrollingCacheEnabled(false);
mylistview.invalidateViews();
adapter.notifyDataSetChanged();
this.setRetainInstance(true);
return rootView;
}
public void updateList(List adapter) {
mylistview = (ListView) rootView.findViewById(R.id.list);
mylistview.setAdapter((ListAdapter) adapter);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String member_name = rowItems.get(position).getMember_name();
int product_icons = rowItems.get(position).getProfile_pic_id();
String status = rowItems.get(position).getStatus();
RowItem item = rowItems.get(position);
Intent intent = new Intent(getActivity(), HomeFragment.class);
intent.putExtra("member_name", member_name);
intent.putExtra("product_icons", product_icons);
intent.putExtra("status", status);
rowItems.remove(item);
newadapter = new CustomAdapter(getActivity(), rowItems);
mylistview.setAdapter(newadapter);
newadapter.notifyDataSetChanged();
Toast.makeText(getActivity().getApplicationContext(),
"Added to Cart: " + member_name, Toast.LENGTH_SHORT).show();
}
}
CustomAdapter.java
public class CustomAdapter extends BaseAdapter {
HomeFragment home = new HomeFragment();
Context context;
List<RowItem> rowItems;
public CustomAdapter(Context context, List<RowItem> rowItems) {
this.context = context;
this.rowItems = rowItems;
}
public CustomAdapter() {
// TODO Auto-generated constructor stub
}
#Override
public int getCount() {
return rowItems.size();
}
#Override
public Object getItem(int position) {
return rowItems.get(position);
}
#Override
public long getItemId(int position) {
return rowItems.indexOf(getItem(position));
}
/* private view holder class */
private class ViewHolder {
ImageView product_icons;
TextView member_name;
TextView status;
Button addtocart;
}
ViewHolder holder = null;
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.member_name = (TextView) convertView
.findViewById(R.id.member_name);
holder.product_icons = (ImageView) convertView
.findViewById(R.id.product_icons);
holder.status = (TextView) convertView.findViewById(R.id.status);
holder.addtocart = (Button) convertView
.findViewById(R.id.btnaddtocart);
RowItem row_pos = rowItems.get(position);
holder.product_icons.setImageResource(row_pos.getProfile_pic_id());
holder.member_name.setText(row_pos.getMember_name());
holder.status.setText(row_pos.getStatus());
holder.addtocart.setText(" add to cart");
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
}
RowItem.java
public class RowItem {
private String member_name;
private int profile_pic_id;
private String status;
public RowItem(String member_name, int profile_pic_id, String status) {
this.member_name = member_name;
this.profile_pic_id = profile_pic_id;
this.status = status;
}
public String getMember_name() {
return member_name;
}
public void setMember_name(String member_name) {
this.member_name = member_name;
}
public int getProfile_pic_id() {
return profile_pic_id;
}
public void setProfile_pic_id(int profile_pic_id) {
this.profile_pic_id = profile_pic_id;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
Please help me with this thing for my software engineering subject i hope anyone can help me.
It seems like you are just removing the view that holds the data and not actually changing the underlying data set. You call rowItems.remove() when you want the item removed but remember when the fragment is reloaded like when you click on the Home navigation option that the code in HomeFragment.createView() is run.
In that code you can see that the rowItems is initialized here
member_names = getResources().getStringArray(R.array.Member_names);
for (int i = 0; i < member_names.length; i++) {
RowItem item = new RowItem(member_names[i],
product_icons.getResourceId(i, -1), statues[i]);
rowItems.add(item);
}
So unless you are removing the item from the Member_names array resource when it is deleted then it will appear every time you recreate the fragment.

Recursive entry to executePendingTransactions

I have a MainDrawer to Fragment activity which has a layout for a nav drawer my and my main content where I can load new fragments into. One fragment I load in is calle StatisticsTab Fragment. This Fragment holds a tabhost which each tab is its own fragment of listview items. Once I click on a ListView item, which loads another new fragment and am no longer in the tabHost and I try to go back using the navigationdrawer to my StatisticsTab fragment I get this error:
03-03 10:32:06.884 24185-24185/com.beerportfolio.beerportfoliopro E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.IllegalStateException: Recursive entry to executePendingTransactions
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1439)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:472)
at android.support.v4.app.FragmentTabHost.onAttachedToWindow(FragmentTabHost.java:283)
at android.view.View.dispatchAttachedToWindow(View.java:12307)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2457)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2464)
at android.view.ViewGroup.addViewInner(ViewGroup.java:3567)
at android.view.ViewGroup.addView(ViewGroup.java:3399)
at android.view.ViewGroup.addView(ViewGroup.java:3344)
at android.view.ViewGroup.addView(ViewGroup.java:3320)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:938)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:440)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:5789)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:843)
at dalvik.system.NativeStart.main(Native Method)
If I do not click on any of my tabs though on the StatisticsTab fragment and navigate to another fragment via the navdrawer and then back to the StatisticsTab then it will not FC on. ALso none of the other fragments in the NavDrawer force close when I go back to them, just the one with the tabs.
MainDrawer2:
public class MainDrawer2 extends FragmentActivity
{
private static final String EXTRA_NAV_ITEM = "extraNavItem";
private static final String STATE_CURRENT_NAV = "stateCurrentNav";
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private NavDrawerListAdapter mDrawerAdapter;
private ListView mDrawerList;
private CharSequence mTitle;
private CharSequence mDrawerTitle;
private MainNavItem mCurrentNavItem;
public static Intent createLaunchFragmentIntent(Context context, MainNavItem navItem)
{
return new Intent(context, MainDrawer2.class)
.putExtra(EXTRA_NAV_ITEM, navItem.ordinal());
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mDrawerList = (ListView)findViewById(R.id.drawer);
getActionBar().setDisplayHomeAsUpEnabled(true);
enableHomeButtonIfRequired();
mDrawerAdapter = new NavDrawerListAdapter(getApplicationContext());
mDrawerList.setAdapter(mDrawerAdapter);
mDrawerList.setOnItemClickListener(new ListView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
displayNavFragment((MainNavItem)parent.getItemAtPosition(position));
}
});
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.app_name, R.string.app_name)
{
public void onDrawerClosed(View view)
{
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView)
{
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if(getIntent().hasExtra(EXTRA_NAV_ITEM)){
MainNavItem navItem = MainNavItem.values()
[getIntent().getIntExtra(EXTRA_NAV_ITEM,
MainNavItem.STATISTICS.ordinal())];
displayNavFragment(navItem);
}
else if(savedInstanceState != null){
mCurrentNavItem = MainNavItem.values()
[savedInstanceState.getInt(STATE_CURRENT_NAV)];
setCurrentNavItem(mCurrentNavItem);
}
else{
displayNavFragment(MainNavItem.STATISTICS);
}
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void enableHomeButtonIfRequired()
{
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH){
getActionBar().setHomeButtonEnabled(true);
}
}
#Override
public void setTitle(CharSequence title)
{
mTitle = title;
getActionBar().setTitle(mTitle);
}
#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);
}
#Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putInt(STATE_CURRENT_NAV, mCurrentNavItem.ordinal());
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/*
#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);
}
*/
private void displayNavFragment(MainNavItem navItem)
{
if(navItem == mCurrentNavItem){
return;
}
Fragment fragment = Fragment.instantiate(this,
navItem.getFragClass().getName());
if(fragment != null){
getSupportFragmentManager().beginTransaction()
.replace(R.id.main, fragment)
.commit();
setCurrentNavItem(navItem);
}
}
private void setCurrentNavItem(MainNavItem navItem)
{
int position = navItem.ordinal();
// If navItem is in DrawerAdapter
if(position >= 0 && position < mDrawerAdapter.getCount()){
mDrawerList.setItemChecked(position, true);
}
else{
// navItem not in DrawerAdapter, de-select current item
if(mCurrentNavItem != null){
mDrawerList.setItemChecked(mCurrentNavItem.ordinal(), false);
}
}
mDrawerLayout.closeDrawer(mDrawerList);
setTitle(navItem.getTitleResId());
mCurrentNavItem = navItem;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if(mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
}
else {
mDrawerLayout.openDrawer(mDrawerList);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void goToSearch(MenuItem item){
//go to search page
Fragment Fragment_one;
FragmentManager man= getSupportFragmentManager();
FragmentTransaction tran = man.beginTransaction();
Fragment_one = new Search();
tran.replace(R.id.main, Fragment_one);//tran.
tran.addToBackStack(null);
tran.commit();
}
}
StatisticsTab:
public class StatisticsTab extends Fragment {
private FragmentTabHost mTabHost;
//Mandatory Constructor
public StatisticsTab() {
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tabs,container, false);
mTabHost = (FragmentTabHost)rootView.findViewById(android.R.id.tabhost);
mTabHost.setup(getActivity(), getFragmentManager(), R.id.realtabcontent);
mTabHost.addTab(mTabHost.newTabSpec("Basic").setIndicator("Basic"),
StatisticsPage.class, null);
mTabHost.addTab(mTabHost.newTabSpec("Brewery").setIndicator("Brewery"),
BreweryStatistics.class, null);
mTabHost.addTab(mTabHost.newTabSpec("Style").setIndicator("Style"),
StyleStatistics.class, null);
mTabHost.addTab(mTabHost.newTabSpec("Taste").setIndicator("Taste"),
TasteStatisticsPage.class, null);
return rootView;
}
}
One of my Fragments for a tab in the tabhost which has a listview:
public class BreweryStatistics extends Fragment implements GetBreweryStatisticsJSON.OnArticleSelectedListener {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.brewery_statistics_layout, container, false);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String userName = prefs.getString("userName", null);
String userID = prefs.getString("userID", null);
String url = "myURL";
//async task to get beer taste tag percents
GetBreweryStatisticsJSON task = new GetBreweryStatisticsJSON(getActivity());
task.setOnArticleSelectedListener(this);
task.execute(url);
// Inflate the layout for this fragment
return v;
}
#Override
public void onArticleSelected(String bID){
//code to execute on click
Fragment Fragment_one;
FragmentManager man= getFragmentManager();
FragmentTransaction tran = man.beginTransaction();
Fragment_one = new BreweryPage2();
final Bundle bundle = new Bundle();
bundle.putString("breweryIDSent", bID);
Fragment_one.setArguments(bundle);
tran.replace(R.id.main, Fragment_one);//tran.
tran.addToBackStack(null);
tran.commit();
}
}
My Async task for the above fragment to load the listview:
public class GetBreweryStatisticsJSON extends AsyncTask<String, Void, String> {
Context c;
private ProgressDialog Dialog;
public GetBreweryStatisticsJSON(Context context)
{
c = context;
Dialog = new ProgressDialog(c);
}
//***************************code for on click
OnArticleSelectedListener listener;
public interface OnArticleSelectedListener{
public void onArticleSelected(String myString);
}
public void setOnArticleSelectedListener(OnArticleSelectedListener listener){
this.listener = listener;
}
//*****************************end code for onClick
protected void onPreExecute() {
Dialog.setMessage("Analyzing breweries");
Dialog.setTitle("Loading");
Dialog.setCancelable(false);
Dialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPostExecute(String result){
//decode json here
try{
JSONArray jsonArray = new JSONArray(result);
//acces listview
ListView lv = (ListView) ((Activity) c).findViewById(R.id.yourBreweryStatistics);
//make array list for beer
final List<BreweryInfo> tasteList = new ArrayList<BreweryInfo>();
for(int i = 0; i < jsonArray.length(); i++) {
String brewery = jsonArray.getJSONObject(i).getString("brewery");
String rate = jsonArray.getJSONObject(i).getString("rate");
String breweryID = jsonArray.getJSONObject(i).getString("id");
int count = i + 1;
brewery = count + ". " + brewery;
Log.d("brewery stats", brewery);
//create object
BreweryInfo tempTaste = new BreweryInfo(brewery, breweryID, rate);
//add to arraylist
tasteList.add(tempTaste);
//add items to listview
BreweryInfoAdapter adapter1 = new BreweryInfoAdapter(c ,R.layout.brewer_stats_listview, tasteList);
lv.setAdapter(adapter1);
//set up clicks
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
BreweryInfo o=(BreweryInfo)arg0.getItemAtPosition(arg2);
String bID = o.breweryID;
Log.d("breweryID" , bID);
//todo: add brewery page link
//********************* add listener
listener.onArticleSelected(bID);
}
});
}
}
catch(Exception e){
}
Dialog.dismiss();
}
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
}
You are attempting to use fragments nested within other fragments, by way of your FragmentTabHost.
In your StatisticsTab fragment, change this:
mTabHost.setup(getActivity(), getFragmentManager(), R.id.realtabcontent);
to this:
mTabHost.setup(getActivity(), getChildFragmentManager(), R.id.realtabcontent);
Then, make sure to use the parent FragmentManager to commit the main fragment change, by changing getFragmentManager() to getActivity().getSupportFragmentManager() inside BreweryStatistics.onArticleSelected().
See:
ViewPager: Recursive entry to executePendingTransactions
Nested Fragments using support library v4 revision 11

Categories

Resources