I am using a nav drawer with three items(Time sheet, claims, project) and I would like to pass ab to claims. In time sheet I have 3 activities, the ab is in the work_details activity.How can I do to achieve this?
TimeSheet has 3 activities (Information(extend to fragment),work force,work details)
Claims has 2 activities(claims(extend to fragment), cameraMain).
WorkDetails.java
Button btn1 = (Button) findViewById(R.id.button2);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
AlertDialog.Builder builder = new AlertDialog.Builder(WorkDetailsTable.this);
builder.setTitle("Data Saved");
builder.setMessage("Are you sure you want to save?");
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int ii) {
long ab = ts.insertTimeSheet(name, weather, date, status,b,i);
Bundle bundle =new Bundle();
bundle.putString("ab","ab");
Claims o=new Claims();
o.setArguments(bundle);
}
Claims.java
final Long fk=this.getArguments().getLong("ab");
Button button = (Button) claims.findViewById(R.id.button8);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent(getActivity().getApplicationContext(), CameraMain.class);
Toast.makeText(getActivity().getApplicationContext(), fk+"", Toast.LENGTH_LONG).show();
startActivity(intent);
}
});
return claims;
}
I refer from Send data from activity to fragment in android but the app crashed when I select claims item.
11-02 09:25:55.910 6116-6116/com.example.project.project
E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.project.project, PID: 6116
java.lang.NullPointerException
at com.example.project.project.Claims.onCreateView(Claims.java:59)
at android.app.Fragment.performCreateView(Fragment.java:1700)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:890)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
at android.app.BackStackRecord.run(BackStackRecord.java:684)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1453)
I think the NullPointException is came from here
fk=data.getLong("ab");
Do I need to add the parameter in MainActivity?
MainActivity.java
Some part of code snippet in mainActivity
private void selectItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment=new Information();
break;
case 1:
fragment=new Claims();
break;
case 2:
fragment=new Project();
case 3:
fragment=new Report();
case 4:
fragment=new ViewView();
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(mNavigationDrawerItemTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
Log.e("MainActivity", "Error in creating fragment");
}
EDITED
Button btn1 = (Button) findViewById(R.id.button2);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
AlertDialog.Builder builder = new AlertDialog.Builder(WorkDetailsTable.this);
builder.setTitle("Data Saved");
builder.setMessage("Are you sure you want to save?");
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int ii) {
long ab = ts.insertTimeSheet(name, weather, date, status,b,i);
Bundle bundle =new Bundle();
bundle.putLong("ab",ab);
Claims o=new Claims();
o.setArguments(bundle);
}
Claims.java
Bundle bundle=this.getArguments();
fk=bundle.getLong("ab");
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity().getApplicationContext(), fk+"", Toast.LENGTH_LONG).show();
AlertDialogRadio(a1);
}
});
MainActivity
private void selectItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment=new Information();
break;
case 1:
fragment=new Claims();
break;
case 2:
fragment=new Project();
break;
case 3:
fragment=new Report();
break;
case 4:
fragment=new ViewView();
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
if(fragment instanceof Claims)
{
Bundle bundle=new Bundle();
bundle.putString("ab","ab");
fragment.setArguments(bundle);
fragment.setArguments(bundle);
}
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(mNavigationDrawerItemTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
Log.e("MainActivity", "Error in creating fragment");
}
}
}
MainActivity
private void selectItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment=new Information();
break;
case 1:
fragment=new Claims();
Bundle bundle=new Bundle();
bundle.putLong("ab",WorkDetails.ab);
fragment.setArguments(bundle);
break;
case 2:
fragment=new Project();
break;
case 3:
fragment=new Report();
break;
case 4:
fragment=new ViewView();
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(mNavigationDrawerItemTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
Log.e("MainActivity", "Error in creating fragment");
}
}
}
WorkDetails
public static long ab=-1;//this is flied ,don't put in the method
Button btn1 = (Button) findViewById(R.id.button2);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
AlertDialog.Builder builder = new AlertDialog.Builder(WorkDetailsTable.this);
builder.setTitle("Data Saved");
builder.setMessage("Are you sure you want to save?");
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int ii) {
ab = ts.insertTimeSheet(name, weather, date, status,b,i);
}
What you can just do is to place this data in your activity where fragment is placed. example is.
in your activity
long ab = 12.4;
in your fragment
long data = ((YourActivity)getActivity()).ab;
"OR"
make ab like
static long ab = value; // your Details activity
in your details activity and get the value of this
with details activity name like
long data = Details.ab //in your claims activity.
When you are instantiating your Claim Fragment , instantiate a bundle object and assign whatever data that you need to be passed in bundle and set it as argument to the fragment.
Bundle bundle = new Bundle();
bundle.putLong("ab",10L);
new Claims().setargument(bundle);
Then in your Claim fragment's onCreateView() you can access this bundle data as
Bundle bundle = getArguments();
long ab = bundle.getLong("ab");
Related
in an application , I wish I would pass a string fragment and display it in a toast.
The problem is with my code, the creation of the fragment I have a toast that appears, but empty ...
I do not understand where did my problem ( it's the first time I try to do that )
My code :
MainActivity :
public class MainActivity extends ActionBarActivity
implements NavigationDrawerCallbacks {
private NavigationDrawerFragment mNavigationDrawerFragment;
private Toolbar mToolbar;
private CharSequence mUrl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
setSupportActionBar(mToolbar);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.fragment_drawer);
// Set up the drawer.
mNavigationDrawerFragment.setup(R.id.fragment_drawer, (DrawerLayout) findViewById(R.id.drawer), mToolbar);
}
#Override
public void onNavigationDrawerItemSelected(int position) {
Fragment objFragment = null;
switch (position) {
case 0:
Intent intent = new Intent(MainActivity.this, fragment_test.class);
intent.putExtra("message", "test");
objFragment = new fragment_test();
break;
case 1:
objFragment = new menu2_Fragment();
break;
case 2:
objFragment = new menu3_Fragment();
break;
case 3:
objFragment = new menu4_Fragment();
break;
case 4:
objFragment = new menu5_Fragment();
break;
case 5:
objFragment = new menu6_Fragment();
break;
case 6:
objFragment = new menu8_Fragment();
break;
case 7:
objFragment = new menu9_Fragment();
break;
case 8:
objFragment = new menu7_Fragment();
break;
}
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, objFragment)
.commit();
}
#Override
public void onBackPressed() {
if (mNavigationDrawerFragment.isDrawerOpen())
mNavigationDrawerFragment.closeDrawer();
else
super.onBackPressed();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
return super.onCreateOptionsMenu(menu);
}
/*#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}*/}
Fragment_test :
public class fragment_test extends Fragment {
View rootview;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rootview = inflater.inflate(R.layout.xml1, container, false);
Intent intent = getActivity().getIntent();
String message = intent.getStringExtra("message");
Toast toast = Toast.makeText(getActivity(), message, Toast.LENGTH_LONG);
toast.show();
return rootview;
}}
thx in advance
ps : sorry for my english french
Your code
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.container, objFragment).commit();
Replace with
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.container, objFragment).commit();
Bundle bundle = new Bundle();
bundle.putString(key, value);
objFragment.setArguments(bundle);
Write below code in your another activity
if (getArguments() != null)
{
m_searchText = getArguments().getString(Key);
}
I am using DrawerLayout which has Listview
When I click on the Listview item , it does not responds to the click ( not launching another activity )
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//requestWindowFeature(Window.FEATURE_NO_TITLE);
final ActionBar actionBar=getActionBar();
actionBar.setIcon(null);
actionBar.setTitle("");
setContentView(R.layout.main_activity);
// Custom ActionBar initializations.
getActionBar().setCustomView(R.layout.action_bar_custom);
getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_HOME_AS_UP);
getActionBar().setDisplayUseLogoEnabled(true);
getActionBar().setDisplayShowHomeEnabled(true);
getActionBar().setDisplayShowCustomEnabled(true);
//getActionBar().setIcon(R.drawable.ic_drawer);
// Remember me.
sharedPref=getSharedPreferences("myPref", MODE_PRIVATE);
editor=sharedPref.edit();
//Listview
mDrwawerList=(ListView)findViewById(R.id.list_slidermenu);
listDataHeader = new ArrayList<HashMap<String,String>>();
listDataHeader_temp = new ArrayList<String>();
navigational_adapter=new NavigationListAdapter(MainActivity.this, new ArrayList<HashMap<String,String>>());
mDrawerLayout=(DrawerLayout)findViewById(R.id.drawer_layout);
mDrawerToggle=new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.nav_btn,0, 0){
public void onDrawerClosed(View drawerView){
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrwawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
TextView txtCategoryName=(TextView)view.findViewById(R.id.txt_category);
String category_name=txtCategoryName.getText().toString();
Log.e("category_name", "karjeevcategory_name "+category_name);
if (category_name.equals("Home")) {
}
else if (category_name.equals("Diamond of the Week")) {
}
else if (category_name.equals("About Us")) {
}
else if (category_name.equals("FAQ")) {
Intent intent=new Intent(MainActivity.this,FAQActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
else if (category_name.equals("Press & Download")) {
}
else if (category_name.equals("Contact Us")) {
}
}
});
new PerformGetCategory().execute();
}
Replace your existing code with this,and create a Intent inside particular position case of listview, if FAQ item is at 5th position, create Intent inside case 4:
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
displayView(position);
}
});
And inside displayView(int position) keep this:
private void displayView(int position) {
switch (position) {
case 0:
break;
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
Intent intent=new Intent(MainActivity.this,FAQActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
break;
case 5:
break;
case 6:
break;
default:
break;
}
}
Hope this solves your problem.
I solved my problem from my end ...
There was layout issues , due to which the listview was not able to handle the click ..
I pasted my litsview code to bottom of the other layout code which was inside DrawerLayout
I'm trying to get view from Fragment dynamically added to Activity.
MainActivity.java
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
myDrawerList.setOnItemClickListener(new DrawerItemClickListener());
handleIntent(getIntent());
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(
AdapterView<?> parent, View view, int position, long id
) {
// display view for selected nav drawer item
displayView(position);
}
}
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
String userToken = UserTokenStorageFactory.instance().getStorage().get();
switch (position) {
case 0:
fragment = new AllCategories();
break;
case 1:
fragment = new Subscription();
break;
case 2:
if( userToken != null && !userToken.equals( "" ) ){
Intent myIntent1 = new Intent(this, PrivateOffice.class);
this.startActivity(myIntent1);
break;
}
else {
Intent myIntent1 = new Intent(this, LogIn.class);
this.startActivity(myIntent1);
break;
}
case 3:
if( userToken != null && !userToken.equals( "" ) ){
Intent myIntent1 = new Intent(this, Create_action.class);
this.startActivity(myIntent1);
break;
}
else {
Intent myIntent1 = new Intent(this, LogIn.class);
this.startActivity(myIntent1);
break;
}
case 4:
AlertDialog dialog = onCreateDialog(DIALOG_CHOOSE_CATEGORY);
dialog.show();
break;
default:
break;
}
if (fragment != null) {
android.app.FragmentManager fragmentManager = getFragmentManager();
fTrans = fragmentManager.beginTransaction();
fTrans.replace(R.id.content_frame, fragment);
fTrans.commit();
// update selected item and title, then close the drawer
myDrawerList.setItemChecked(position, true);
myDrawerList.setSelection(position);
setTitle(viewsNames[position]);
myDrawerLayout.closeDrawer(mDrawer);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
I need to get view (LinearLayout listv) from layout of AllCategories.java. I tried using getView() with findViewById, but it returns NullPointerException. What shall I do?
I m using drawer list for my android application.
Got a issue.
When I click randomly (very fast) then I get forcestop and java.lang.IllegalStateException: Content view not yet created showing in Log.
I m using fragments
I m also getting the following Runtime error
at android.support.v4.app.ListFragment.ensureList(ListFragment.java:32
Here is a part of my code in selecting from drawer list and
Fragment home = new Home();
Fragment feeds = new Feeds_ListView();
.....
private void selectItem(int position)
{
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
switch (position)
{
case 0:
setTitle(title[position]);
ft.replace(R.id.content_frame, feeds);
break;
case 1:
setTitle(title[position]);
ft.replace(R.id.content_frame, NewPostFragment);
break;
case 2:
setTitle(title[position]);
ft.replace(R.id.content_frame, SearchDetailsFragment);
break;
case 3:
setTitle(title[position]);
ft.replace(R.id.content_frame, feeds1);
break;
case 4:
setTitle(title[position]);
ft.replace(R.id.content_frame, UserDetailsFragment);
break;
case 5:
setTitle(title[position]);
ft.replace(R.id.content_frame, FBActivity);
break;
}
ft.commit();
mDrawerList.setItemChecked(position, true);
setTitle(title[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
protected void onPostCreate(Bundle savedInstanceState)
{
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void setTitle(CharSequence title)
{
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
Here is the part of Feeds_ListView();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
context=container.getContext();
rootView = inflater.inflate(R.layout.feeds_listview_layout, container, false);
list = (ListView) rootView.findViewById(android.R.id.list);
mRelativeLayout=rootView.findViewById(R.id.mRelativeLayout);
saveProgress =(ProgressBar) rootView.findViewById(R.id.loadpost);
saveProgress.setVisibility(View.INVISIBLE);
userAdapter = new CustomListAdapter(getActivity(), R.layout.feeds_listview_item,userArray);
mRelativeLayout.setVisibility(View.GONE);
list.setItemsCanFocus(false);
list.setAdapter(userAdapter);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
SharedPreferences settings =getActivity().getSharedPreferences("newdatabase",0);
String user_id=settings.getString("user_id", "--");
if(user_id.equals("--") || user_id.equals(""))
{ FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, FBActivity);
ft.commit();
}else{
new Onscrollasync().execute();
((PullToRefresh_Master) getListView()).setOnRefreshListener(new OnRefreshListener()
{
#Override
public void onRefresh()
{
new Onscrollasync().execute();
}
});
}
}
The problem is with the code in the Fragment Home that you wrote in the onCreateView. Move the code in your onCreateView() to either onActivityCreated() or onViewCreated(). There are several similar question on StackOverlfow like here.
Try this instead of inflating a container,try to inflate your view without the container ie
rootView = inflater.inflate(R.layout.feeds_listview_layout,null);
Let me know if this works.
Are android fragments reusable - i mean if i could use code like below:
class MyTabActivity extends FragmentActivity implements OnClickListener {
Fragment[] tabs = new Fragment[3];
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.settings_activity);
findViewById(R.id.button1).setOnClickListener(this);
findViewById(R.id.button2).setOnClickListener(this);
findViewById(R.id.button3).setOnClickListener(this);
//first xml-defined fragment, it is inside
//FrameLayout with id R.id.loadTarget -> see openTab()
tabs[0] = getSupportFragmentManager().findFragmentById(
R.id.firstFragment);
}
private void openTab(int i) {
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.loadTarget, getTabFragment(i));
ft.addToBackStack(null);
ft.commit();
}
private Fragment getTabFragment(int i) {
if(tabs[i] == null) {
switch(i) {
//0-tab fragment has been allready
//retrieved in onCreate
case 1:
tabs[1] = new MySecondTabFragment();
break;
case 2:
tabs[2] = new MyThirdTabFragment();
break;
}
}
return tabs[i];
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.button1:
openTab(0);
break;
case R.id.button2:
openTab(1);
break;
case R.id.button3:
openTab(2);
break;
}
}
}
Yes fragments are reusable you can attach/detach a fragment to an activity several times. As you can see in the documentation after being detached the fragment is destroyed and then created again when it is added to another activity.