My problem is, that i am trying to pass
final List<PieEntry> entries = new ArrayList<>(); to another fragment, which is more or less empty until now.
My complete code is this: ( of the fragment which initiates the ArrayList)
package com.example.nextpietwo;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import java.util.ArrayList;
import java.util.List;
public class SecondFragment extends Fragment {
// Store instance variables
private String title;
private int page;
// newInstance constructor for creating fragment with arguments
public static SecondFragment newInstance(int page, String title) {
SecondFragment fragmentSecond = new SecondFragment();
Bundle args = new Bundle();
args.putInt("someInt", page);
args.putString("someTitle", title);
fragmentSecond.setArguments(args);
return fragmentSecond;
}
// Store instance variables based on arguments passed
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
page = getArguments().getInt("someInt", 0);
title = getArguments().getString("someTitle");
}
// Inflate the view for the fragment based on layout XML
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_second, container, false);
TextView tvLabel2 = (TextView) view.findViewById(R.id.textView2);
//Alle Objekte hier einfügen (wie textview tvavel2)
final List<PieEntry> entries = new ArrayList<>();
final Button button = (Button) view.findViewById(R.id.button);
final TextView textView = (TextView) view.findViewById(R.id.textView);
final TextView textView2 = (TextView) view.findViewById(R.id.textView2);
final EditText editText = (EditText) view.findViewById(R.id.editText);
final EditText editText2 = (EditText) view.findViewById(R.id.editText2);
final EditText editText3 = (EditText) view.findViewById(R.id.editText3);
button.setOnClickListener(new View.OnClickListener() {
public void onClick (View view) {
if (editText3.getText().toString().matches("")) {
Toast.makeText(getActivity(), "You did not enter a Valid Item ID", Toast.LENGTH_LONG).show();
return;
} else if (editText2.getText().toString().matches("")) {
Toast.makeText(getActivity(), "You did not enter a Valid Quantitiy", Toast.LENGTH_LONG).show();
return;
} else {
String nomen = (editText3.getText().toString());
float number = Float.parseFloat(editText2.getText().toString());
entries.add(new PieEntry(number, nomen));
Bundle args = new Bundle();
args.putStringArrayList("array", ArrayList);
FirstFragment.setArguments(args);
editText3.setText("");
editText2.setText("");
editText3.requestFocus();
}
}
});
return view;
}
}
Simple explanations are appreciated!
Thanks in advance.
First of all make the make you PieEntry Parcelable by implementing interface Parcelable
Code to writeen in first Fragemnt
SecondFragment secondfragment //where data needs to be pass
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("data", data);
secondfragment.setArguments(bundle);
data is a list of PieEntry
Code to written in second Fragemnt
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
data =getArguments().getParcelableArrayList("data");
}
}
Related
so i am trying to make an note keeping app and i have basicly 1 activity with 1 main fragment that opens a second fragment so the user can enter data, the problem is when i send the bundle from the second fragment to the first one, because if i put bundle get arguments in the first one it crashes and i understand why but im not sure how to make it so that it doesnt
Fragment 1
package app.web.fragments.secure_note;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.analytics.FirebaseAnalytics;
import java.util.List;
import app.web.markodunovic.passwordmanager.R;
import app.web.markodunovic.passwordmanager.adapter.NoteAdapter;
import app.web.markodunovic.passwordmanager.room_note.Note;
import app.web.markodunovic.passwordmanager.view_model.NoteViewModel;
public class Secure_Notes_Fragment extends Fragment {
public static final String TAG = "BACK";
private FirebaseAnalytics mFirebaseAnalytics = FirebaseAnalytics.getInstance(getActivity());
private FloatingActionButton floatingActionButton;
private NoteViewModel noteViewModel;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
if (container == null) {
return null;
}
View view = inflater.inflate(R.layout.fragment_secure_notes, container, false);
RecyclerView recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setHasFixedSize(true);
NoteAdapter noteAdapter = new NoteAdapter();
recyclerView.setAdapter(noteAdapter);
noteViewModel = new ViewModelProvider(getActivity()).get(NoteViewModel.class);
noteViewModel.getAllNotes().observe(getActivity(), new Observer<List<Note>>() {
#Override
public void onChanged(List<Note> notes) {
//update recycler view
//Toast.makeText(getActivity(), "On Changed", Toast.LENGTH_SHORT).show();
// it works yey
noteAdapter.setNotes(notes);
}
});
floatingActionButton = view.findViewById(R.id.button_add_note);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fire(mFirebaseAnalytics);
//Toast.makeText(getContext(), "I Dun Been Clicked", Toast.LENGTH_SHORT).show();
//getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new PassWord_Fragment()).commit();
newFragment();
}
});
passedData();
return view;
}
private void passedData() {
Bundle bundle = this.getArguments();
if (!bundle.isEmpty()){
String title = bundle.getString("title");
String description = bundle.getString("description");
int value = bundle.getInt("number");
Toast.makeText(getContext(), ""+title+description+value, Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getContext(), "Bundle Empty", Toast.LENGTH_SHORT).show();
}
}
private void newFragment() {
//sends data need to use bundle instead of intent in fragments
Bundle bundle = new Bundle();
bundle.putString("test","the test works");
NoteAddEditFragment noteAddEditFragment = new NoteAddEditFragment();
noteAddEditFragment.setArguments(bundle);
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager()
.beginTransaction().replace(R.id.fragment_container,noteAddEditFragment).addToBackStack(TAG);
noteAddEditFragment.setArguments(bundle);
fragmentTransaction.commit();
}
private void fire(FirebaseAnalytics mFirebaseAnalytics) {
Bundle firebaseAnalytics = new Bundle();
firebaseAnalytics.putString(FirebaseAnalytics.Param.SCREEN_NAME, "clicked fab button switched to NoteAddEditFragment");
firebaseAnalytics.putString(FirebaseAnalytics.Param.SCREEN_CLASS, "NoteAddEditFragment");
mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.SCREEN_VIEW, firebaseAnalytics);
}
}
Fragment 2
package app.web.fragments.secure_note;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.NumberPicker;
import android.widget.Toast;
import android.widget.Toolbar;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import java.util.Objects;
import app.web.markodunovic.passwordmanager.R;
public class NoteAddEditFragment extends Fragment {
private EditText editTextTitle, editTextDescription;
private NumberPicker numberPicker;
private Button buttonBack, buttonSave;
public static final String TITLE = "title";
public static final String DESCRIPTION = "description";
public static final String NUMBERPICKER = "number";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
if (container==null){
return null;
}
View view = inflater.inflate(R.layout.fragment_secure_notes_edit_update,container,false);
setButtons(view);
checkPassedVallue();
return view;
}
private void setButtons(View view) {
editTextTitle = view.findViewById(R.id.edit_text_title);
editTextDescription = view.findViewById(R.id.edit_text_description);
numberPicker = view.findViewById(R.id.number_picker_priority);
numberPicker.setMinValue(1);
numberPicker.setMaxValue(100);
buttonBack = view.findViewById(R.id.notes_back_button);
buttonBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "Note not saved", Toast.LENGTH_SHORT).show();
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager()
.beginTransaction().replace(R.id.fragment_container,new Secure_Notes_Fragment());
fragmentTransaction.commit();
}
});
buttonSave = view.findViewById(R.id.notes_save_button);
buttonSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String title = editTextTitle.getText().toString().trim();
String description = editTextDescription.getText().toString().trim();
int numberP = numberPicker.getValue();
if (!title.isEmpty() && !description.isEmpty() && numberP > 0){
//Toast.makeText(getContext(), "ok", Toast.LENGTH_SHORT).show();
Bundle bundle = new Bundle();
bundle.putString(TITLE,title);
bundle.putString(DESCRIPTION,description);
bundle.putInt(NUMBERPICKER,numberP);
Secure_Notes_Fragment secure_notes_fragment = new Secure_Notes_Fragment();
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager()
.beginTransaction().replace(R.id.fragment_container,secure_notes_fragment);
secure_notes_fragment.setArguments(bundle);
fragmentTransaction.commit();
}else{
Toast.makeText(getContext(), "Cant Be Empty", Toast.LENGTH_SHORT).show();
}
}
});
}
private void checkPassedVallue() {
Bundle bundle = this.getArguments();
String passedVallue = bundle.getString("test");
Toast.makeText(getContext(), "this is the passed vallue: " + passedVallue, Toast.LENGTH_SHORT).show();
}
}
Adding items in RecyclerView from the data that comes from an intent that brings the data from another activity not behaving as expected.
This is the Main Activity of the app:
package com.example.android.contacts;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class Main2Activity extends AppCompatActivity {
RecyclerView contactListView;
private ViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Intent intent2 = getIntent();
String nameTxt = intent2.getStringExtra("ContactName");
String phoneTxt = intent2.getStringExtra("PhoneNumber");
String emailTxt = intent2.getStringExtra("Email");
String addressTxt = intent2.getStringExtra("Address");
contactListView = (RecyclerView) findViewById(R.id.listView);
getData(nameTxt,phoneTxt,emailTxt,addressTxt);
adapter = new ViewAdapter(getApplication(), getData(nameTxt,phoneTxt,emailTxt,addressTxt));
contactListView.setAdapter(adapter);
}
public List<Contact> getData(String name, String phone, String email, String address){
List<Contact> data = new ArrayList<>();
data.add(new Contact(name,phone,email,address));
return data;
}
public void addNewContact (View view){
Intent intent = new Intent (Main2Activity.this, MainActivity.class);
startActivity(intent);
}
}
This is the Adapter :
package com.example.android.contacts;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.Collections;
import java.util.List;
public class ViewAdapter extends RecyclerView.Adapter<ViewAdapter.MyViewHolder>{
private LayoutInflater inflator;
List<Contact> data = Collections.emptyList();
public ViewAdapter (Context context, List<Contact> data){
inflator=LayoutInflater.from(context);
this.data=data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflator.inflate(R.layout.custom_row, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Contact current = data.get(position);
holder.name.setText(current.getName());
holder.phone.setText(current.getPhone());
holder.email.setText(current.getEmail());
holder.address.setText(current.getAddress());
}
#Override
public int getItemCount() {
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder{
TextView name;
TextView phone;
TextView email;
TextView address;
public MyViewHolder(View itemView) {
super(itemView);
name=(TextView) itemView.findViewById(R.id.contactName);
phone=(TextView) itemView.findViewById(R.id.phoneNumber);
email=(TextView) itemView.findViewById(R.id.emailAddress);
address=(TextView) itemView.findViewById(R.id.cAddress);
}
}
}
The activity gets the data from another activity and the data comes into the main activity utilizing an intent, and the part of data receiving to the main activity is tested and works as expected.
This is the activity that feeds the data to the main Activity:
package com.example.android.contacts;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
EditText nameTxt, phoneTxt, emailTxt, addressTxt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nameTxt = (EditText) findViewById(R.id.txtName);
phoneTxt = (EditText) findViewById(R.id.txtPhone);
emailTxt = (EditText) findViewById(R.id.txtEmail);
addressTxt = (EditText) findViewById(R.id.txtAddress);
}
public void addContact (View view){
if (nameTxt.getText().length()==0){
nameTxt.setError("Please enter the Name");
}
else if (phoneTxt.getText().length()==0){
phoneTxt.setError("Please enter the Phone Number");
}
else if (emailTxt.getText().length()==0){
emailTxt.setError("Please enter the Email");
}
else if (addressTxt.getText().length()==0){
addressTxt.setError("Please enter the Address");
}
else{
Intent intent = new Intent (this, Main2Activity.class);
intent.putExtra("ContactName",nameTxt.getText().toString());
intent.putExtra("PhoneNumber",phoneTxt.getText().toString());
intent.putExtra("Email",emailTxt.getText().toString());
intent.putExtra("Address",addressTxt.getText().toString());
startActivity(intent);
}
}
}
It´s a simple thing but I want to show you, what the problem is. I guess you are not understanding what we want to explain in the comments. No problem, everybody has started off small (like we say in Germany) :). So here is your problem:
public List<Contact> getData(String name, String phone, String email, String address){
List<Contact> data = new ArrayList<>();
//data.add(new Contact(name,phone,email,address));
return data;
}
The two slashes // means that you have commented the code out. So it is not active anymore. To add these values to your list, you have to remove that slashes. It must look like this:
public List<Contact> getData(String name, String phone, String email, String address){
List<Contact> data = new ArrayList<>();
data.add(new Contact(name,phone,email,address));
return data;
}
Do you see the difference? Also here in that post, in your example, it´s grayed out...
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
/**
* Created by jamie on 9/12/2015.
*/
public class PlayersFragment extends DialogFragment {
ListView lv;
String[] players = {"arteta", "costa", "reid", "degea", "rooney", "terry"};
int[] images = {R.drawable.arteta, R.drawable.costa, R.drawable.reid, R.drawable.degea,
R.drawable.rooney, R.drawable.terry};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.dialog, container, false);
//initialize listview
lv = (ListView) rootView.findViewById(R.id.listView1);
//set dialog title
getDialog().setTitle("Soccer SuperStars");
//create adapter obj and set list view to it
Adapter adapter = new Adapter(getActivity(), players, images);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int pos, long id) {
Toast.makeText(getActivity(), players[pos], Toast.LENGTH_SHORT).show();
}
});
return rootView;
}
}
Trying to create a ListView fragment in android studio and getting
error
cannot resolve method show(android.support.v4.app
FragmentManager,java.lang.string)
the error is on the p.show(fm,"Players Fragment) underlined in red, tried to resolve this but getting nowhere, i would really appreciate a solution to this! thank you
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.widget.Button;
public class MainActivity extends FragmentActivity {
Button showBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final FragmentManager fm =getSupportFragmentManager();
final PlayersFragment p=new PlayersFragment();
showBtn=(Button)findViewById(R.id.button1);
showBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
p.show(fm,"Players Fragment"); //error is here
}
});
}
}
I suppose you are using android.app.DialogFragment and not android.support.v4.app.DialogFragment. Just extend PlayersFragment from support library's android.support.v4.app.DialogFragment. Or, if you are not targeting old devices, you can change getSupportFragmentManager() to getFragmentManager()
You have to import android.support.v4.app.DialogFragment on the class PlayersFragment and then change getSupportFragmentManager() to getFragmentManager().
To more understand more how fragments work, I created a mainactivity its layout has one<fragment>. and I created two java classes extend fragment and each of these classes has its own layout.
In the java class that extends fragment, I initailise my views textview inside onActivityCreated(), and as shown below in the code in the same class, i created two methods setbtnclicks(int clicks) and getbtnclicks(). From the mainactivity i assign number of clicks of a button to setbtnclicks() and i try to display the number of clicks on the textview of the class that extends fragment by calling getbtnclicks from inside onActivivtyCreated(). But the problem is, this method always displays zero, as if the number of clicks are not incremented.
MainActivtity:
//global variable
private int i = 0;
...
...
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Fragment mSelectedFragment;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
switch (v.getId()) {
case R.id.btn00:
mSelectedFragment = new Fragment00();
mFragmentManager = getFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.fragment00ID, mSelectedFragment);
mFragmentTransaction.commit();
mFragment00.setBtnClicks(i);
i++;
break;
Java_Class "Fragment00"
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
Log.d(TAG, "onActivityCreated(): "+order);
order++;
mTv = (TextView) getView().findViewById(R.id.fragment00Tv00);
mTv.setText("the Button was clicked "+getBtnClicks()+ " time(s)");
Log.i(TAG, "onActivityCreated(): "+getBtnClicks());
}
Once i have implemented a more or less same program like yours.The objective was to increment the number of button clicks in both the fragments.Here is the code.Hope it helps:
MainActivity.java
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
public class MainActivity extends Activity implements OnClickListener{
Button btn1,btn2;
int click1=0,click2=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1=(Button)findViewById(R.id.btn1);
btn2=(Button)findViewById(R.id.btn2);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
}
#SuppressLint("NewApi")
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Fragment fragment = null;
if (v == btn1) {
// do stuff for button left
click1++;
Bundle bundle=new Bundle();
String clickstring1=Integer.toString(click1);
bundle.putString("name1",clickstring1 );
fragment = new FragButton1();
fragment.setArguments(bundle);
}
if (v == btn2) {
// do stuff for button right
click2++;
Bundle bundle=new Bundle();
String clickstring2=Integer.toString(click2);
bundle.putString("name2",clickstring2 );
fragment = new FragButton2();
fragment.setArguments(bundle);
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
}
else{
Log.e("MainActivity", "Error in creating fragment");
}
}
}
FragButton1.java
import android.annotation.SuppressLint;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
#SuppressLint("NewApi")
public class FragButton1 extends Fragment{
TextView tv;
public FragButton1(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragbutton1, container, false);
String strtext=getArguments().getString("name1");
tv=(TextView)rootView.findViewById(R.id.tv_times1);
tv.setText(strtext);
return rootView;
}
}
FragButton2.java
import android.annotation.SuppressLint;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
#SuppressLint("NewApi")
public class FragButton2 extends Fragment{
TextView tv2;
public FragButton2(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragbutton2, container, false);
tv2=(TextView)rootView.findViewById(R.id.tv_times2);
String strtext=getArguments().getString("name2");
tv2.setText(strtext);
return rootView;
}
}
Here there are 2 buttons and onclick of a button a new fragment will be launched and the fragment will display the number of times a button is clicked in a textview.
increment i before the fragment Transaction
switch (v.getId()) {
case R.id.btn00:
i++;
mSelectedFragment = new Fragment00();
mFragmentManager = getFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.fragment00ID, mSelectedFragment);
mFragmentTransaction.commit();
mFragment00.setBtnClicks(i);
break;
As a lot of people have been doing so far, I'm implementing the FragmentTabsPager into my app, which is using ActionBarSherlock 4.0. However, I'm lost.
Fragments, and all of Google's little ideas, plans and methods surrounding it, are confusing me. If anyone could take a look at my code and walk me through this, providing help in making it work, I would thank them a thousand times :D.
I have another project with a sort-of beginning for a ViewPager, but the Tabs just mix better, especially with them being in the ActionBar on landscape and tablets.
My code is all zipped up and ready to go over here:
http://dl.dropbox.com/u/21807195/Antonius%20College%202.zip
Thanks in advance!
I will show you my code that has a ViewPager, TabListener, and system of Fragments linked to each tab. It implements ABS, but as of yet, still crashes on Gingerbread and lower (works beautifully on ICS, though):
import java.util.ArrayList;
import library.DatabaseHandler;
import org.json.JSONObject;
import com.actionbarsherlock.R;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View.OnClickListener;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
public class Polling extends SherlockFragmentActivity {
private ViewPager mViewPager;
private TabsAdapter mTabsAdapter;
private final static String TAG = "21st Polling:";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.pager);
setContentView(mViewPager);
ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setDisplayShowTitleEnabled(false);
bar.setDisplayShowHomeEnabled(false);
mTabsAdapter = new TabsAdapter(this, mViewPager);
mTabsAdapter.addTab(bar.newTab().setText(R.string.login),
LoginFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.economics),
EconFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.elections),
ElectionsFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.politics),
PoliticsFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.science),
ScienceFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.finance),
FinanceFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.religion),
ReligionFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.military),
MilitaryFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.international),
InternationalFragment.class, null);
Log.v(TAG, (String)bar.getTabAt(0).getText());
}
public static class TabsAdapter extends FragmentPagerAdapter
implements ActionBar.TabListener, ViewPager.OnPageChangeListener {
private final Context mContext;
private final ActionBar mActionBar;
private final ViewPager mViewPager;
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
static final class TabInfo {
private final Class<?> clss;
private final Bundle args;
TabInfo(Class<?> _class, Bundle _args) {
clss = _class;
args = _args;
}
}
public TabsAdapter(SherlockFragmentActivity activity, ViewPager pager) {
super(activity.getSupportFragmentManager());
mContext = activity;
mActionBar = activity.getSupportActionBar();
mViewPager = pager;
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) {
TabInfo info = new TabInfo(clss, args);
tab.setTag(info);
tab.setTabListener(this);
mTabs.add(info);
mActionBar.addTab(tab);
notifyDataSetChanged();
}
public int getCount() {
return mTabs.size();
}
public SherlockFragment getItem(int position) {
TabInfo info = mTabs.get(position);
return (SherlockFragment)Fragment.instantiate(mContext, info.clss.getName(), info.args);
}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
public void onPageSelected(int position) {
mActionBar.setSelectedNavigationItem(position);
}
public void onPageScrollStateChanged(int state) {
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
mViewPager.setCurrentItem(tab.getPosition());
//Log.v(TAG, "clicked");
Object tag = tab.getTag();
for (int i=0; i<mTabs.size(); i++) {
if (mTabs.get(i) == tag) {
mViewPager.setCurrentItem(i);
}
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {}
public void onTabReselected(Tab tab, FragmentTransaction ft) {}
public void onTabReselected(Tab tab, android.app.FragmentTransaction ft) {}
public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) {}
}
And here is what one fragment looks like:
package com.davekelley.polling;
import com.actionbarsherlock.R;
import com.actionbarsherlock.app.SherlockFragment;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MilitaryFragment extends SherlockFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.militaryfragment, container, false);
}
}
My last note would that my code still has one other issue: individual fragments do not always reload their interface after the user press back (which results in removing the entire app from the screen, regardless which tab/fragment they are on, because I have no backStack). So that's what I'm working through now. I think once I have that sorted, I'll try to figure out why I still don't have Gingerbread execution functioning properly. Either way, I hope looking through this code helps you out.
Here is a fragment with some onClickListeners:
import com.actionbarsherlock.R;
import com.actionbarsherlock.app.SherlockFragment;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
public class LoginFragment extends SherlockFragment {
Button loginButton;
Button registerButton;
Polling activity;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.loginfragment, container, false);
return v;
}
public void onResume() {
super.onResume();
Log.d("Econ", "onresume");
loginButton = (Button) getActivity().findViewById(R.id.loginButton);
loginButton.setOnClickListener(loginListener);
registerButton = (Button) getActivity().findViewById(R.id.registerButton);
registerButton.setOnClickListener(registerListener);
}
public OnClickListener loginListener = new OnClickListener() {
#Override
public void onClick(View v) {
if(loginButton.getText().toString() == "Log Out") {
activity.loginReport(2);
loginButton.setText(R.string.login);
//Remove user from dB sqllite when I know how
}
else {
Log.v("LoginF", "onclick");
ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Logging in...");
LoginTask loginTask = new LoginTask((Polling) getActivity(), progressDialog);
loginTask.execute();
}
}
};
public OnClickListener registerListener = new OnClickListener() {
#Override
public void onClick(View v) {
Log.v("Register", "onclick");
ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Registering new user...");
RegisterTask registerTask = new RegisterTask((Polling) getActivity(), progressDialog);
registerTask.execute();
}
};
public void onAttach(Activity activity) {
super.onAttach(activity);
this.activity = (Polling) activity;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public void onStart() {
super.onStart();
Log.d("Econ", "onstart");
}
public void onPause() {
super.onPause();Log.d("Econ", "onpause");
}
public void onStop() {
super.onStop();
Log.d("Econ", "onstop");
}
public void onDestroyView() {
super.onDestroyView();
Log.d("Econ", "ondestroyview");
}
public void onDestroy() {
super.onDestroy();
Log.d("Econ", "ondestroy");
}
public void onDetach() {
super.onDetach();
Log.d("Econ", "ondetach");
}
}
The loginTask objects that you see are actually classes that extend ASyncTask - they handle connecting to my server and registering/logging in.
I thought it would be helpful to add in one bit more of code. This is another one of my fragments, like LoginFragment, but it inflates a UI a little differently. Eventually, what you see in the while loop below, will head into an ASyncTask to acquire each question from the server, rather than the dummy string array you see:
public class EconFragment extends SherlockFragment {
private TableLayout questionContainer;
int pos = 0;
private String[] titles = {"The first title ", "hallo1","hallo2", "hallo3",
"hallo4", "hallo5","hallo6", "hallo7","hallo8", "hallo9"};
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.v("Econ", "onCreateView");
View v = inflater.inflate(R.layout.econfragment, container, false);
questionContainer = (TableLayout) v.findViewById(R.id.questionContainer);
//bs
int leftMargin=5;
int topMargin=5;
int rightMargin=5;
int bottomMargin=5;
while (pos < 10) {
View question = inflater.inflate(R.layout.question, null);
question.setId(pos);
TextView title = (TextView) question.findViewById(R.id.questionTextView);
title.setText(titles[pos]);
Button charts = (Button) question.findViewById(R.id.chartsButton);
charts.setId(pos);
charts.setOnClickListener(chartsListener);
TableRow tr = (TableRow) question;
TableLayout.LayoutParams trParams = new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT);
trParams.setMargins(leftMargin, topMargin, rightMargin, bottomMargin);
tr.setLayoutParams(trParams);
Log.v("econ", "while loop");
questionContainer.addView(tr);
pos++;
}
pos = 0;
return v;
}
I have ported the FragmentTabsPager Activity and associated Fragments from "Support4Demos" (Android Support library sample) to use ActionBarSherlock and true ActionBar Tabs. The sample includes an Activity that uses both a ViewPager and Tabs to switch between Fragments. The Fragments contain three kinds of ListViews. I've tested it from ICS down to Eclair (2.1). You can browse or download the code at http://code.google.com/p/sherlock-demo/.