i am a newbie in android development. I am now seeking a solution on how i can pass a value from main activity to different fragments. My apps have a main activity and 5 fragments. I would like to do xml parsing in my main and then pass processed data to different fragments so that i can draw different pages at the same time. My main has set a new fragment adapter
mAdapter = new FragmentAdapter(getSupportFragmentManager());
And then in my FragmentAdapter (which extend FragmentPagerAdapter and implements IconPagerAdapter), i have overwrite the getItem method so that i can create 5 fragment to handle 5 different pages.
#Override
public Fragment getItem(int position) {
Fragment fragment = new Fragment1();
switch(position){
case 0:
fragment = new Fragment1();
break;
case 1:
fragment = new Fragment2();
break;
case 2:
fragment = new Fragment3();
break;
case 3:
fragment = new Fragment4();
break;
case 4:
fragment = new Fragment5();
break;
}
return fragment;
}
My question is how i can pass some value from my main to the newly generated fragments.For e.g i would like to pass a value "A" from my main to fragment 1. How can i do this task? Tks in advance for your help!~
You can have a look at this article: http://developer.android.com/training/basics/fragments/communicating.html
Tony, in the link http://developer.android.com/training/basics/fragments/communicating.html
ArticleFragment newFragment = new ArticleFragment();
Bundle args = new Bundle();
args.putInt(ArticleFragment.ARG_POSITION, position);
newFragment.setArguments(args);
The above code snippet allows the MainActivity to pass an int data to the ArticleFragment class.
ArticleFragment class then can use code snippet below to read the int data in say its onCreate method.
int position = getArguments().getInt(ARG_POSITION);
Related
I create Android Project in Xamarin plugin for Visual Studio Community 2015. I have in my application 4 fragments and I switch in them by ViewPager which is navigated in ActionBar. In second and third tab, there are few fields (for second tab -> Name, Surname, Mail, Phone and for third -> description field). These fields are EditText. On last fragment there are fields (TextView) and I need to pass data from 2nd, 3rd to 4th fragment. These data is only string value.
I try to use this code:
public void OnTabSelected(ActionBar.Tab tab, FragmentTransaction ft)
{
viewPager.CurrentItem = tab.Position;
if (tab.Position == 0)
{
actionBar.SetTitle(Resource.String.GalleryTab);
} else if (tab.Position == 1)
{
actionBar.SetTitle(Resource.String.DescriptionTab);
} else if (tab.Position == 2)
{
actionBar.SetTitle(Resource.String.ContactInfoTab);
} else if (tab.Position == 3)
{
actionBar.SetTitle(Resource.String.SummaryTab);
nameContact.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) =>
{
nameSummary.Text = e.Text.ToString();
};
}
nameContact and nameSummary are properly initialized.
var nameContact = FindViewById<EditText>(Resource.Id.nameContactText);
var surnameContact = FindViewById<EditText>(Resource.Id.surnameContactText);
var nameSummary = FindViewById<TextView>(Resource.Id.nameSummary);
var surnameSummary = FindViewById<TextView>(Resource.Id.surnameSummary);
Can someone explain me how to send data between fragments. Thank you for answer.
UPDATE
I just do something like this.
var nameContact = FindViewById<EditText>(Resource.Id.nameContactText);
nameContactText = nameContact.Text.ToString();
var nameContactSummary = FindViewById<TextView>(Resource.Id.nameSummary);
nameContactSummary.Text = nameContactText;
A way to do it is to store data you need to transfer in parent activity (assuming that both fragments are hosted in the same activity) so every fragment will have access to this data using (Activity as yourActivityType).YourPropertyName in every fragment.
More details on Communicating with the Activity from Fragment can be found here:http://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity
When registering a custom language service extension, Visual Studio creates a new options entry for the language within the Text Editor node (in the Visual Studio options dialog). Beneath that node two default nodes are created named General and Tabs, whereby the General tab contains statement completion and display settings...
In the Dispay group there are three options; one of them is the Navigation Bar checkbox (which shows/hides the editor´s navigation bar). For my custom language service, this option is disabled. Of course, it´s not implemented yet.
I would like to know, what I have to do, to provide a navigation bar for my custom editor... I guess that there is a certain interface I have to implement in the editor´s factory, or the language service package must export a certain MEF component, or, or, ...
Jon Senchyna´s answer guided me into the right direction. The OnSynchronizeDropdowns method gets never called (the SDK documentation is just wrong in that case). What did the final trick was to override at least GetComboAttributes, GetEntryAttributes and GetEntryText to get text-only items for both combo boxes...
[ComVisible(true)]
public sealed class CustomTypeAndMemberDropdownBars : TypeAndMemberDropdownBars
{
private readonly IList<string> declarations;
private readonly IList<string> members;
public CustomTypeAndMemberDropdownBars(
LanguageService languageService,
IVsTextView view)
: base(languageService)
{
// TODO: initialize declarations and members from the given text view...
this.declarations = ...
this.members = ...
}
private enum ComboIndex
{
Types = 0,
Members = 1
}
public override int GetComboAttributes(
int combo,
out uint entries,
out uint entryType,
out IntPtr imageList)
{
entries = 0;
imageList = IntPtr.Zero;
entryType = (uint)DROPDOWNENTRYTYPE.ENTRY_TEXT;
var comboType = (ComboIndex)combo;
switch (comboType)
{
case ComboIndex.Types:
entries = (uint)this.declarations.Count();
break;
case ComboIndex.Members:
entries = (uint)this.members.Count();
break;
}
return VSConstants.S_OK;
}
public override int GetEntryAttributes(
int combo,
int entry,
out uint fontAttrs)
{
fontAttrs = (uint)DROPDOWNFONTATTR.FONTATTR_PLAIN;
return VSConstants.S_OK;
}
public override int GetEntryText(
int combo,
int entry,
out string text)
{
text = null;
var comboType = (ComboIndex)combo;
switch (comboType)
{
case ComboIndex.Types:
text = this.declarations[entry];
break;
case ComboIndex.Members:
text = this.members[entry];
break;
}
return VSConstants.S_OK;
}
public override bool OnSynchronizeDropdowns(
LanguageService languageService,
IVsTextView textView,
int line,
int col,
ArrayList dropDownTypes,
ArrayList dropDownMembers,
ref int selectedType,
ref int selectedMember)
{
return false;
}
}
I believe the following steps should be what you need:
In your Package class, set the ShowDropDownOptions property to true in the ProvideLanguageService attribute
Create a class that implements TypeAndMemberDropdownBars
In your LanguageService class, implement the CreateDropDownHelper function and have it return an instance of your TypeAndMemberDropdownBars
I have 3 buttons on my menu screen and I want to link them 3 different activities. Every single button would extends different activity. How it is possible to do? I have no problem when I have 1 class and activity, but it makes problem when I have 3. Thank you.
Assuming you have three activities called MainActivity, SettingsActivity and ProfileActivity, you can do:
#Override
public boolean onOptionsItemSelected(MenuItem item){
Intent intent;
Class<?> cls;
switch(item.getItemId()){
case R.id.main:
cls = MainActivity.class;
break;
case R.id.settings:
cls = ScheduleView.class;
break;
case R.id.profile:
cls = UserPrefsActivity.class;
break;
default:
Log.d(this.getClass().getSimpleName(),"Should not happen");
return false;
}
intent = new Intent(getApplicationContext(), cls);
startActivity(intent);
return true;
}
I have a ListView which displays static data along with images (say Activity A). When I click a ListVoew Item, the data is captured and passed onto next Activity (lets call it Activity B). In Activity B, I want to pass the selected value into DB select where clause and fetch data and show relevant information pertaining to the selection. Here is my code snippet...
Activity A:
String subproduct = ((TextView) view.findViewById(R.id.product_label)).getText().toString();
// Launching new Activity on selecting single List Item
SharedPreferences sharedPreferences = getSharedPreferences("pref",MODE_WORLD_READABLE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.putString("subproduct", subproduct);
editor.commit();
Intent myIntent = new Intent(getApplicationContext(),Details.class);
startActivity(myIntent);
And here is my Activity B:enter code here
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.setContentView(R.layout.details1);
SharedPreferences myPrefs = this.getSharedPreferences("pref", MODE_WORLD_READABLE);
String subproduct = myPrefs.getString("subproduct","null");
TextView txtProduct1 = (TextView) findViewById(R.id.detail_item);
txtProduct1.setText(subproduct);
and here is my DBHelper.java. Here I want to pass the selected value. Please help me how I can acheive this...
public Cursor getData(){
//SharedPreferences myPrefs = this.getSharedPreferences("pref", 0);
//String subproduct = myPrefs.getString("subproduct","null");
Cursor c = myDataBase.rawQuery("SELECT * FROM Destmain WHERE destname= " + ? + " ", null);
while (c.moveToNext()){
DestInfo q = new DestInfo();
q.setDestination(c.getString(1));
q.setCity(c.getString(2));
q.setCountry(c.getString(3));
q.setPeriod(c.getString(4));
q.setType(c.getString(5));
q.setCurrency(c.getString(6));
q.setBriefhistory(c.getString(7));
q.setHighlights(c.getString(8));
}
c.close();
return c;
Can anyone help me how I can pass the ListView (Activity A) selected value into fetching DB data and show in Activity B? Thanks a ton.
By using method onItemcClick in Activity A you can get the Id and pass it to the second Activity B.
onItemClick(AdapterView<?> adapterView, View view, int pos, long id)
newActivity.putExtra("key", id);
then in Activity B you can use this Id to search on the Database.
Intent newActivity = getIntent();
long id = newActivity.getLongExtras("key", -1);
in some other case you can use getLunchDetails method
I've been beating my head around trying to populate a ListView with data from an SQLite database and can't seem to figure it out. I've read countless tutorials and equally countless posts here, but I'm obviously not getting something critical. Was hoping someone could give me a hint as to why the following two pieces of code aren't working together, or if I should be looking at something else entirely. Any help would be appreciated. The result I'm getting is a force close.
Method that initiates populating ListView object
public void displayNurseRoster(){
listView = (ListView) findViewById(R.id.list);
// create instance of DbCommunicator
DbCommunicator rosterView = new DbCommunicator(this);
// open instance
rosterView.open();
// instantiate SimpleCursorAdapter instance and set value
SimpleCursorAdapter cursorAdapter;
cursorAdapter = rosterView.getRosterListViewAdapter(this);
// close database instance
rosterView.close();
// set adapter to listView
listView.setAdapter(cursorAdapter);
}
Method that returns SimpleCursorAdapter:
public SimpleCursorAdapter getRosterListViewAdapter (Context context) {
// method variables
int[] to = new int[] {R.id.rosterListLname};
// used ArrayList because of unpredictability of array length
List<String> dataArray = new ArrayList<String>();
String[] columns = new String[] {KEY_NURSE_ROWID, KEY_LNAME};
// create cursor
Cursor cursor = sqldb.query(NURSE_TABLE, columns, null, null, null,
null, KEY_LNAME);
int iLname = cursor.getColumnIndex(KEY_LNAME);
cursor.moveToFirst();
String result = "";
while(!cursor.isAfterLast()){
result = result
+ cursor.getString(iLname) + "\n";
dataArray.add(result);
}
// convert ArrayList to String array for use with SimpleCursorAdapter
String [] from = (String[]) dataArray.toArray();
SimpleCursorAdapter adapter = new SimpleCursorAdapter(context,
R.layout.edit_roster, cursor, from, to);
return adapter;
}
Okay, I got it to work and wanted to share to help out anyone else struggling with this and 2) to get feedback on my fix in case anyone with more experience has a better suggestion.
I actually wanted to show three items in the list view, so here's the code that worked. One of the problems I was having was that I was extending ListActivity, but found in another StackOverflow post that that is not a good idea when there is only one list view to worry about.
package com.deadEddie.staffingmanagement;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class EditRoster extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_roster);
displayNurseRoster();
}
public void displayNurseRoster(){
ListView listView = (ListView) findViewById(R.id.list);
int[] to = new int[] {
R.id.rosterListLname,
R.id.rosterListFname,
R.id.rosterListMI };
String[] from = new String [] {
DbCommunicator.KEY_LNAME,
DbCommunicator.KEY_FNAME,
DbCommunicator.KEY_MI};
// create instance of DbCommunicator
DbCommunicator rosterView = new DbCommunicator(this);
// open instance
rosterView.open();
// get & manage cursor
Cursor cursor = rosterView.getRosterCursor(this);
startManagingCursor(cursor);
// instantiate cursor adaptor
ListAdapter adapter = new SimpleCursorAdapter(this,
R.layout.nurse_list, cursor, from, to);
cursor.moveToNext();
// set adapter to listView
listView.setAdapter(adapter);
}// displayNurseRoster()
}
Here's the method in my DbCommunicator class. What finally made the difference was that I was not creating an instance of SQLiteQueryBuilder and using that, but instead I was using sqldb.query(...), as shown above. I'm not sure what the difference is, but it finally did the trick. If anyone would like to share, please do.
public Cursor getRosterCursor (Context context) {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(NURSE_TABLE);
Cursor cursor = queryBuilder.query(sqldb, new String[] {
KEY_NURSE_ROWID,
KEY_LNAME,
KEY_FNAME,
KEY_MI},
null, null, null, null, null);
return cursor;
}
A couple other newbie lessons for anyone else out there:
1. Always use the "_id" field in the cursor. The cursor cannot function without that.
2. The while or for loop is not necessary for a simple list view. The cursor adapter handles that.
3. There is no need to call the moveToFirst() method on the cursor.
Hope that's helpful to someone.