startActivity in setOnClickListener onClick on fragment - android

My problem is that does not start my new activity in fragment
please help me why?
my main activity is this :
package com.slidingmenunav;
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.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.slidingmenunav.adapter.NavDrawerListAdapter;
import com.slidingmenunav.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
// 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)));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1), true, "22"));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
// What's hot, We will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));
// 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) {
// 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_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);
}
/**
* 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 FindPeopleFragment();
break;
case 2:
fragment = new PhotosFragment();
break;
case 3:
fragment = new CommunityFragment();
break;
case 4:
fragment = new PagesFragment();
break;
case 5:
fragment = new WhatsHotFragment();
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);
}
}
And my first displayView(0) fragment that have one button in it when click start new activity :
package com.slidingmenunav;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class HomeFragment extends Fragment implements View.OnClickListener {
public HomeFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
Button b1 = (Button) rootView.findViewById(R.id.button1);
b1.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), Doa.class));
}
}
And Doa.java :
package com.slidingmenunav;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
public class Doa extends Activity {
// List view
private ListView lv;
// Listview Adapter
ArrayAdapter<String> adapter;
// Doa EditText
EditText inputSearch;
// ArrayList for Listview
ArrayList<HashMap<String, String>> productList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_doa);
// Listview Data
String products[] = getResources().getStringArray(R.array.doa);
lv = (ListView) findViewById(R.id.list_view);
inputSearch = (EditText) findViewById(R.id.inputSearch);
// Adding items to listview
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.subject_name, products);
lv.setAdapter(adapter);
/**
* Enabling Doa Filter
* */
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
Doa.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
// after click
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
final String item = lv.getItemAtPosition(position).toString();
int total_number = 3;
for(int x = 1; x < total_number+1; x = x+1) {
String SubjectName = "subject_" + String.valueOf(x);
int resID = getResources().getIdentifier(SubjectName, "string", getPackageName());
String subject = getResources().getString(resID);
if(item.equals(subject)) {
String StringClass = "com.Subject_" + String.valueOf(x);
Class<?> c = null;
if(StringClass != null) {
try {
c = Class.forName(StringClass);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Intent intent = new Intent(Doa.this, c);
startActivity(intent);
}
}
}
});
}
#Override
public void onResume() {
super.onResume();
adapter.notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
}

Related

when i start the fragment in slidemenu but getting error

please help
Submitcv.java
this is the fragment of navigation slidemenu(submitcv) but i have getting error when i execute the fragment from mainactivity.but when i used these fragment
without any code it's executed
and logcat is nothing show any error
package com.example.app.slidemenu;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import com.example.app_placement.R;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Fragment;
import android.os.Bundle;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
public class Submit_resume extends Fragment implements OnClickListener
{
// EditText name,emailid,dateofbirth,location,currentsalary,mobilenumber;
// RadioGroup gendergroup;
// RadioButton male,female;
// Button submitcv;
Spinner spinner;
String string_array[];
ArrayAdapter<String> arrayadapter;
EditText dateofbirth;
private DatePickerDialog fromDatePickerDialog;
private SimpleDateFormat dateFormatter;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.submit_resume, container, false);
// name=(EditText)container.findViewById(R.id.sname);
// emailid=(EditText)container.findViewById(R.id.sbtmail);
// dateofbirth=(EditText)container.findViewById(R.id.sdob);
// location=(EditText)container.findViewById(R.id.slocation);
// currentsalary=(EditText)container.findViewById(R.id.currentsalary);
// mobilenumber=(EditText)container.findViewById(R.id.smobile);
// gendergroup=(RadioGroup)container.findViewById(R.id.subgender);
// submitcv=(Button)container.findViewById(R.id.submitcv);
// Submit_cv();
spinner=(Spinner)container.findViewById(R.id.spinner1);
//dateofbirth=(EditText)findViewById(R.id.sdob);
string_array=getResources().getStringArray(R.array.spinner_array);
arrayadapter=new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,
string_array);
spinner.setAdapter(arrayadapter);
// Calendar c = Calendar.getInstance();
// SimpleDateFormat ss = new SimpleDateFormat("dd-MM-yyyy");
// Date date = new Date();
// String currentdate= ss.format(date);
// dob=(EditText)findViewById(R.id.sdob);
//dob.setText(currentdate);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long id) {
// TODO Auto-generated method stub
// spin_val = gender[position];//saving the value selected
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
dateFormatter = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
findViewsById();
setDateTimeField();
return rootView;
}
private void findViewsById()
{
dateofbirth = (EditText)getView().findViewById(R.id.sdob);
dateofbirth.setInputType(InputType.TYPE_NULL);
dateofbirth.requestFocus();
}
private void setDateTimeField() {
dateofbirth.setOnClickListener(this);
Calendar newCalendar = Calendar.getInstance();
fromDatePickerDialog = new DatePickerDialog(getActivity(), new OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
dateofbirth.setText(dateFormatter.format(newDate.getTime()));
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
}
public void onClick(View v)
{
// TODO Auto-generated method stub
if(v == dateofbirth) {
fromDatePickerDialog.show();
}
}
// public void Submit_cv()
// {
//
// System.out.println("value of usetname: "+name.getText().toString());
//
// final String gender = ((RadioButton)getView().findViewById(gendergroup.getCheckedRadioButtonId() )).getText().toString();
// System.out.println(gender);
// }
}
mainactivity.java
this is mainactivity in which define slider code and also define all the fragment of slider.but when used is fragment with any code except initial fragment inflate method.I'm using anything in fragment
package com.example.app_placement;
import info.androidhive.slidingmenu.adapter.NavDrawerListAdapter;
import info.androidhive.slidingmenu.model.NavDrawerItem;
import java.util.ArrayList;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.drawable.ColorDrawable;
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.*;
import com.example.app.slidemenu.*;
#SuppressLint("NewApi")
public class MainActivity extends Activity {
// Dialog choicedialog;
ShareActionProvider mshareactioprovider;
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;
private LinearLayout drawerll;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView userTextView = (TextView) findViewById(R.id.tvsideUserName);
System.out.println("value of user from db:"+Constants.USERNAME);
userTextView.setText(Constants.USERNAME);
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);
drawerll = (LinearLayout) findViewById(R.id.drawerll);
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)));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons
.getResourceId(3, -1), true, "22"));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons
.getResourceId(4, -1)));
// What's hot, We will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons
.getResourceId(5, -1), true, "50+"));
// 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.menu1, // 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);
}
}
/**
* 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);
}
}
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;
case R.id.logout:
startActivity(new Intent(this,Login_Activity.class));
return true;
case R.id.profile:
return true;
case R.id.abouts:
//startActivity(new Intent(this,About_us.class));
return true;
case R.id.changepassword:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// Inflating the current activity's menu with
getMenuInflater().inflate(R.menu.main, menu);
// getActionBar();
ActionBar b=getActionBar();
b.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.SteelBlue)));
getActionBar().setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
//two more option to set bckcolor
//bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#0000ff")));
// b.setBackgroundDrawable(new ColorDrawable(0x3366FF));
// Getting the actionprovider associated with the menu item whose id is
// share
// mshareactioprovider=(ShareActionProvider)menu.findItem(R.id.newshare).getActionProvider();
// Setting a share intent
// mshareactioprovider.setShareIntent(getDefaultShareIntent());
// Log.d("MainMenu", ",menu title0: " + menu.getItem(0).getTitle());
// returns "New Form"
// menu.addSubMenu(0, Menu.NONE, 1, "Form 1").setIcon(R.drawable.share
// );
// menu.addSubMenu(0, Menu.NONE, 2, "Form 2").setIcon(R.drawable.share);
return true;
}
private Intent getDefaultShareIntent() {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "SUBJECT");
intent.putExtra(Intent.EXTRA_TEXT, "Extra Text");
return intent;
}
/* *
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
final boolean drawerOpen = mDrawerLayout.isDrawerOpen(drawerll);
// 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 CurrentOpening();
break;
case 2:
fragment = new Client_Fragment();
break;
case 3:
System.out.println("Submit fragment is called");
fragment = new Submit_resume();
break;
case 4:
fragment = new About_us();
break;
case 5:
fragment = new Contact_us();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container1, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(drawerll);
} 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);
}
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
}
You need to change below line:
From
spinner=(Spinner)container.findViewById(R.id.spinner1);
To
spinner=(Spinner)rootView.findViewById(R.id.spinner1);
Reason: You need to bind your UI widgets with your fragment view not with Viewgroup.
Done

Refresh or Update the listadapter from a fragment in android eclipse

I have a MainActivity with some fragments to run when click on side navigation menu. In the side navigation menu there is a item Called Number of SMS that shall be updated as soon as in the other fragment you choose the desired phone number. but the problem is I do not know how to refresh the list adapter from that fragment. I defined a class called allvalues which contains all my global variables. The variable responsible for SMS count is allvalues.NumberOfLocations
here is the code of MainActivity:
package com.faraz.locatecar;
import java.util.ArrayList;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
public static 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;
public static ArrayList<NavDrawerItem> navDrawerItems;
public static NavDrawerListAdapter adapter;
String passString;
ProgressDialog mProgressDialog;
MyDb dbf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
allvalues.context = this;
if(!allvalues.setno){
Toast.makeText(allvalues.context, "Please choose a number", Toast.LENGTH_SHORT).show();
}
dbf = new MyDb(allvalues.context);
String phoneNumbers = dbf.trakersCount();
// to check if there is any phone numbers or not
if(phoneNumbers.matches("0")){
Toast.makeText(allvalues.context, "Please save a number first", Toast.LENGTH_SHORT).show();
}
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), true, allvalues.NumberOfLocations));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
// Traker number choose
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, phoneNumbers));
// add tracker number
navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons.getResourceId(6, -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) {
// 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);
}
}
/**
* 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:
new SmsBased().execute();
break;
case 2:
fragment = new OldListReader();
break;
case 3:
fragment = new ShowEveryThing();
break;
case 4:
break;
case 5:
fragment = new ChoosePhoneNumber();
break;
case 6:
fragment = new NewTrakerRegister();
break;
default:
break;
}
if (fragment != null) {
final String MyPref = "mypref";
SharedPreferences prefs = getSharedPreferences(MyPref, 0);
if(prefs.getBoolean("FirstRun", true)){
prefs.edit().putBoolean("FirstRun", false).commit();
fragment = new PasswordFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
passString = allvalues.pass;
}else{
passString = dbf.passString();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
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);
}
// Async part
private class SmsBased extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(allvalues.context);
mProgressDialog.setTitle("Please wait ");
mProgressDialog.setMessage("SMS sending is in progress");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
allvalues.send_command = SmsManager.getDefault();
String SendChangedPassword = "where," + passString + "#";
allvalues.send_command.sendTextMessage(allvalues.PhoneNumberToSend, null, SendChangedPassword, null, null);
return null;
}
#Override
protected void onPostExecute(Void result) {
// Set title into TextView
Toast.makeText(allvalues.context, "SMS sent", Toast.LENGTH_SHORT).show();
mProgressDialog.dismiss();
}
}
}
and this is the other Fragment which in this fragment, the phone numbers already user, saved are going to be showed in a list which on click of the number, first the number will be selected and then the allvalues.NumberOfLocations should be updated which equals to the number of received messages for the selected number.
package com.faraz.locatecar;
import java.util.ArrayList;
import android.app.Fragment;
import android.app.FragmentManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class ChoosePhoneNumber extends Fragment {
private static int i;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.choose_number, container, false);
allvalues.AllPhones_list = new ArrayList<String>();
MyDb phonechoose = new MyDb(allvalues.context);
phonechoose.readTrakers();
allvalues.showphones = (ListView) view.findViewById(R.id.listphone);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(allvalues.context,android.R.layout.simple_list_item_1, android.R.id.text1, allvalues.AllPhones_list);
allvalues.showphones.setAdapter(adapter);
// just added from here
allvalues.showphones.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
final String item = (String) parent.getItemAtPosition(position);
allvalues.PhoneNumberToSend = item;
Toast.makeText(allvalues.context, "شماره :" + allvalues.PhoneNumberToSend, Toast.LENGTH_SHORT).show();
allvalues.setno = true;
SMSNumbers();
Fragment fr = new HomeFragment();
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.frame_container, fr).commit();
}
});
// till up here
return view;
}
public void SMSNumbers()
{
Uri uriSms = Uri.parse("content://sms/inbox");
Cursor cursor = allvalues.context.getContentResolver().query(uriSms, new String[]{"_id", "address", "date", "body"},null,null,null);
if(cursor!=null){
cursor.moveToFirst();
while (cursor.moveToNext())
{
String address = cursor.getString(1);
if(address.equals(allvalues.PhoneNumberToSend)){
i++;
}
}
}
allvalues.NumberOfLocations = i + "";
Toast.makeText(allvalues.context, allvalues.NumberOfLocations, Toast.LENGTH_SHORT).show();
}
}
but the number in the inside the navigation drawer does not update...
I also tried to call the navigation adapter after the line:
allvalues.NumberOfLocations = i + "";
but it did not work...
please help me...
I'd suggest to create a custom listener in your fragment like this :
public interface FragmentListener {
void refreshData();
}
and declare a variable for this listener in your fragment :
private FragmentListener listener;
and in your onItemClickListener:
listener.refreshData();
now create a method in your fragment to set this listener:
public void setListener(FragmentListener listener) {
this.listener = listener;
}
finally in your activity when you create your fragment :
ChoosePhoneNumber fragment = new Fragment();
fragment.setListener(new FragmentListener() {
public void refreshData() {
//Whatever you want to do.
}
});
I achieved the goal by simply refresh the MainActivity (reload it) again from the ChoosePhoneNumber fragment by adding these two lines at the end of the Fragment:
getActivity().finish();
getActivity().startActivity(getActivity().getIntent());

Change type of X fragment to Y fragment

I want to implement a 3-Tab Activity/fragment from another activity/fragment.
I have looked in many links like this
, this one and this one too but none of them solved my problem. The problem comes in StudentProfile.java file in the code
fragment = new RandomFragment();
The error is: Type mismatch: cannot convert from RandomFragment to Fragment
StudentProfile.java
package com.nikhil.studentlife;
import java.util.ArrayList;
import android.support.v7.app.AppCompatActivity;
import com.nikhil.studentlife.adapter.NavDrawerListAdapter;
import com.nikhil.studentlife.model.NavDrawerItem;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SlidingDrawer.OnDrawerCloseListener;
import android.widget.SlidingDrawer.OnDrawerOpenListener;
import android.widget.Toast;
//import android.app.Fragment;
import android.support.v4.app.Fragment;
//import android.app.FragmentManager;
import android.support.v4.app.FragmentManager;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
public class StudentProfile extends AppCompatActivity implements
OnItemClickListener {
private DrawerLayout drawerLayout;
private ListView listView;
private String[] studProfile;
private ActionBarDrawerToggle drawerListener;
/*
* from android hive example:--
*
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;
#SuppressWarnings({ "unchecked", "rawtypes" })
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_profile);
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.studProfile);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.studProfile_icons);
navDrawerItems = new ArrayList<NavDrawerItem>();
drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
studProfile = getResources().getStringArray(R.array.studProfile);
listView = (ListView) findViewById(R.id.drawerList);
listView.setAdapter(new ArrayAdapter(this,
android.R.layout.simple_list_item_1, studProfile));
listView.setOnItemClickListener(this);
drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
drawerListener = new ActionBarDrawerToggle(this, drawerLayout,
R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerClosed(View drawerView) {
// TODO Auto-generated method stub
Toast.makeText(StudentProfile.this, "Drawer Closed",
Toast.LENGTH_SHORT).show();
}
#Override
public void onDrawerOpened(View drawerView) {
// TODO Auto-generated method stub
Toast.makeText(StudentProfile.this, "Drawer Opened",
Toast.LENGTH_SHORT).show();
}
};
drawerLayout.setDrawerListener(drawerListener);
listView.setOnItemClickListener(new SlideMenuClickListener());
/*
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
*/
// 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)));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1), true, "22"));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
// What's hot, We will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));
// Recycle the typed array
navMenuIcons.recycle();
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
listView.setAdapter(adapter);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// getActionBar().setHomeButtonEnabled(true);
// Intent intent = getIntent();
// String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
if(drawerListener.onOptionsItemSelected(item))
{
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 = drawerLayout.isDrawerOpen(listView);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
drawerListener.onConfigurationChanged(newConfig);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onPostCreate(savedInstanceState);
drawerListener.syncState();
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(this, studProfile[arg2] + " was selected",
Toast.LENGTH_SHORT).show();
selectItem(arg2);
}
public void selectItem(int arg2) {
// TODO Auto-generated method stub
listView.setItemChecked(arg2, true);
setTitle(studProfile[arg2]);
}
public void setTitle(String title) {
// TODO Auto-generated method stub
getSupportActionBar().setTitle(title);
}
/*
* #Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the
* menu; this adds items to the action bar if it is present.
* getMenuInflater().inflate(R.menu.student_profile, menu); return true; }
*
* #Override public boolean onOptionsItemSelected(MenuItem item) { // Handle
* action bar item clicks here. The action bar will // automatically handle
* clicks on the Home/Up button, so long // as you specify a parent activity
* in AndroidManifest.xml. int id = item.getItemId(); if (id ==
* R.id.action_settings) { return true; } return
* super.onOptionsItemSelected(item); }
*/
/**
* 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 ProfileFragment();
//fragment = new Fragment();
fragment = new RandomFragment();
break;
case 1:
fragment = new HomeWorkFragment();
break;
case 2:
fragment = new AssignmentsFragment();
break;
case 3:
fragment = new ProjectsFragment();
break;
case 4:
fragment = new GamesFragment();
break;
case 5:
fragment = new ActivitiesFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.mainContent, fragment).commit();
// update selected item and title, then close the drawer
listView.setItemChecked(position, true);
listView.setSelection(position);
setTitle(navMenuTitles[position]);
drawerLayout.closeDrawer(listView);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
}
RandomFragment.java
package com.nikhil.studentlife;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBar.Tab;
import android.support.v7.app.ActionBarActivity;
public class RandomFragment extends ActionBarActivity implements android.support.v7.app.ActionBar.TabListener{
private ViewPager tabsviewPager;
private ActionBar mActionBar;
private TabsAdapter mTabsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabsviewPager = (ViewPager) findViewById(R.id.pager);
mTabsAdapter = new TabsAdapter(getSupportFragmentManager());
tabsviewPager.setAdapter(mTabsAdapter);
getSupportActionBar().setHomeButtonEnabled(false);
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Tab friendstab = getSupportActionBar().newTab().setText("Friends").setTabListener(this);
Tab publicprofiletab = getSupportActionBar().newTab().setText("Public").setTabListener(this);
Tab communitytab = getSupportActionBar().newTab().setText("Community").setTabListener(this);
getSupportActionBar().addTab(friendstab);
getSupportActionBar().addTab(publicprofiletab);
getSupportActionBar().addTab(communitytab);
//This helps in providing swiping effect for v7 compat library
tabsviewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// TODO Auto-generated method stub
getSupportActionBar().setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
}
#Override
public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab selectedtab, FragmentTransaction arg1) {
// TODO Auto-generated method stub
tabsviewPager.setCurrentItem(selectedtab.getPosition()); //update tab position on tap
}
#Override
public void onTabUnselected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub
}
}

Sliding Menu, Navigation Drawer with ListFragment

I use a Sliding Menu and Navigation Drawer with Fragments but I need a ListFragment instead of Fragment. When the app starts and I click on the link to open the side with the ListFragment the programm stopped, but I don't know whats the problem.. :/
This is my MainActivity with the Sliding Menu:
package at.example.sliding_menu;
import at.example.sliding_menu.adapter.NavDrawerListAdapter;
import at.example.sliding_menu.model.NavDrawerItem;
import java.util.ArrayList;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ListFragment;
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;
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>();
// Hinzufügen der Items in das Sliding Menu
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// Glossar
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// Logout
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.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);
}
}
/**
* 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_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);
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
ListFragment listf = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
listf = new GlossarFragment();
break;
case 2:
fragment = new LogoutFragment();
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 if (listf != null) {
// do stuff if its a listfragment
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, listf).commit();
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);
}
}
And this is my GlossarFragment, which is the ListFragment I want to open, inside there should be a List with some data.
package at.example.sliding_menu;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.ListFragment;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
public class GlossarFragment extends ListFragment {
// List view
private ListView lv;
// Listview Adapter
ArrayAdapter<String> adapter;
// Search EditText
EditText inputSearch;
// ArrayList for Listview
ArrayList<HashMap<String, String>> productList;
//private ArrayList<String> product;
//private ArrayAdapter<String> productAA;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_glossar, container, false);
return rootView;
/**
lv = (ListView) getView().findViewById(R.id.list_view);
product = new ArrayList<String>();
product.clear();
product.add("test");
adapter = new ArrayAdapter<String> (this, R.layout.list_item, product );
lv.setAdapter(productAA);*/
/**
//Listview Data
String products[] = {"Text1", "Text2", "Text3"};
//lv = (ListView) findViewById(R.id.list_view);
//inputSearch = (EditText) findViewById(R.id.inputSearch);
lv = (ListView) getView().findViewById(R.id.list_view);
inputSearch = (EditText) getView().findViewById(R.id.inputSearch);
// Adding items to listview
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), R.layout.list_item, R.id.product_name, products);
setListAdapter(adapter);
/**
* Enabling Search Filter*/
/**
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
GlossarFragment.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});*/
}
}

Retrieving the search query from child Fragment in Android?

I have a mother Activity which contains 3-4 child Fragment. I followed the code of Fragment code of tutorial site Android Hive.
This is the Main Activity:
import java.lang.reflect.Field;
import java.util.ArrayList;
import com.nordicsoft.dilosysNewVersion.adapter.NavDrawerListAdapter;
import com.nordicsoft.dilosysNewVersion.model.NavDrawerItem;
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.view.ViewConfiguration;
import android.widget.AdapterView;
import android.widget.ListView;
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);
getOverflowMenu();
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)));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
// What's hot, We will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], 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) {
// 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_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);
}
/**
* 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 Fragment_NewsFeed();
break;
case 1:
fragment = new Fragment_Coupons();
break;
case 2:
fragment = new Fragment_Deals();
break;
case 3:
fragment = new Fragment_Events();
break;
case 4:
fragment = new Fragment_Locations();
break;
case 5:
fragment = new Fragment_Shop();
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);
}
private void getOverflowMenu() {
try {
ViewConfiguration config = ViewConfiguration.get(this);
Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
if(menuKeyField != null) {
menuKeyField.setAccessible(true);
menuKeyField.setBoolean(config, false);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
And this is one of the Child:
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment_Locations extends Fragment {
public Fragment_Locations(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_locations, container, false);
return rootView;
}
}
The Search in the Menu:
<item
android:id="#+id/action_search"
android:actionViewClass="android.widget.SearchView"
android:icon="#drawable/ic_action_search"
android:showAsAction="always"/>
Now I want to access the search (from the Action-bar which comes from the menu) query (the value that has been written in the search box) from multiple child of this Project and each will perform its own individual action. Now how to get the search query in the child Fragments?
In your Activity:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.action_bar, menu);
searchAction = menu.findItem(R.id.menu_search);
SearchView searchView = (SearchView) searchAction.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// do your stuff with query
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
// do something if needed
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
You can send a query to your fragments via simple method call from activity.

Categories

Resources