Add existing activity to a TabActivity Android - java

Hi guys I'm adding a tab activity to an existing android app! In particular, I should add HomeActivity to TabActivity, how can I do? I read on the net that you should implement in HomeActivity fragment and then add it to the TabActivity! But if I implement Fragment in HomeActivity I have a series of errors!
Tab Activity
package xx.myapp;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class TabActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_tab, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tab, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
}
}
Home Activity:
package xx.myapp;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import xx.*;
public class HomeActivity extends AppCompatActivity {
int[] images = {R.drawable.accettato, R.drawable.fatturato, R.drawable.incorso, R.drawable.rifiutato};
ArrayList CantieriRicerca = new ArrayList();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setTitle("Home");
/* Deserializzo l'oggetto */
Intent i = getIntent();
User u = (User) i.getSerializableExtra("User");
Cantiere c = new Cantiere();
CantieriRicerca = c.RicercaCantiere("a", u);
//Listview che visulizza in cantieri con il customadapter
ListView cantieriListView = (ListView) findViewById(R.id.ListViewCantieri);
CustomAdapter cm = new CustomAdapter();
cantieriListView.setAdapter(cm);
try {
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
} catch (Exception ex) {
System.out.println("\n Errore HomeActivity.java : " + ex);
}
}
class CustomAdapter extends BaseAdapter {
#Override
public int getCount() {
return CantieriRicerca.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = getLayoutInflater().inflate(R.layout.row, null);
ImageView imageView = (ImageView) convertView.findViewById(R.id.imageview_stato);
TextView textview_nomecantiere = (TextView) convertView.findViewById(R.id.textView_NomeCantiere);
TextView textview_cliente = (TextView) convertView.findViewById(R.id.textView_Cliente);
Cantiere c = (Cantiere) CantieriRicerca.get(position);
String statoCantiere = c.GetStatoCantiere();
if (statoCantiere.equals("Chiuso")==true) {
imageView.setImageResource(images[0]);
} else if (statoCantiere.equals("InCorso")==true) {
imageView.setImageResource(images[2]);
} else if (c.GetStatoFatturazione() > 0) {
imageView.setImageResource(images[1]);
}
else{
imageView.setImageResource(images[3]);
}
textview_cliente.setText(c.c.GetRagioneSociale());
textview_nomecantiere.setText(c.GetNomeCantiere());
return convertView;
}
}
}

You should consider converting you HomeActivity to Fragment and put it inside of your TabActivity. Fragments are extremely powerful as much as their API, so there should be no problems for you.

Related

How to setOnclickListener FAB in a fragment that will add a card in a RecyclerView

Im trying to add a FAB that will add a card to the recycler view if clicked
FAB is located in the fragment where it contains the recyclerview
Here is my Adapter
package com.example.tmcpm;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
Context mContext ;
List<MediCard> mData;
public RecyclerViewAdapter(Context mContext, List<MediCard> mData) {
this.mContext = mContext;
this.mData = mData;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v ;
v = LayoutInflater.from(mContext).inflate(R.layout.fragment_medicard_recycler,parent,false);
MyViewHolder vHolder = new MyViewHolder(v);
return vHolder;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, final int position) {
int currentPosition = position;
final MediCard infoData = mData.get(position);
holder.tv_num.setText(mData.get(position).getMediCardNumber());
holder.buttonDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext,"Deleted Medication" , Toast.LENGTH_SHORT).show();
removeItem(infoData);
}
private void removeItem(MediCard infoData) {
int currPosition = mData.indexOf(infoData);
mData.remove(currPosition);
notifyItemRemoved(currPosition);
notifyItemRangeChanged(currPosition,mData.size());
notifyDataSetChanged();
}
});
/* holder.buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext,"ADDING", Toast.LENGTH_SHORT).show();
}
});*/
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
private TextView tv_num;
private Button buttonDelete;
public FloatingActionButton buttonAdd;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
tv_num = (TextView) itemView.findViewById(R.id.word);
buttonDelete = (Button) itemView.findViewById(R.id.buttonDelete);
buttonAdd = (FloatingActionButton) itemView.findViewById(R.id.floatButtonAdd);
}
}
}
THIS is my Tabbed Activity Java
package com.example.tmcpm;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.material.tabs.TabLayout;
import java.util.ArrayList;
import java.util.List;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;
public class Prescribe extends AppCompatActivity {
// private final LinkedList<String> mWordList = new LinkedList<>();
private RecyclerView myrecyclerview;
private List<MediCard> lstnum;
/**
* The {#link androidx.viewpager.widget.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* androidx.fragment.app.FragmentStatePagerAdapter.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prescribe);
//Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
/* for (int i = 1; i < 6; i++) {
mWordList.addLast("Medicine # " + i);
}*/
;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_prescribe, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
RecyclerView myrecyclerview;
List<MediCard> mData = new ArrayList<>();
mData.add(new MediCard("Medication 1"));
mData.add(new MediCard("Medication 2"));
mData.add(new MediCard("Medication 3"));
mData.add(new MediCard("Medication 4 "));
View rootView = null;
switch(getArguments().getInt(ARG_SECTION_NUMBER)){
case 1:
//do something
rootView = inflater.inflate(R.layout.fragment_prescribe, container, false);
break;
case 2:
//do something
rootView = inflater.inflate(R.layout.medicard_fragment,container,false);
myrecyclerview = rootView.findViewById(R.id.medicard_recyclerview);
RecyclerViewAdapter recyclerAdapter = new RecyclerViewAdapter(getContext(),mData);
myrecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
myrecyclerview.setAdapter(recyclerAdapter);
new FragmentMedicard();
break;
case 3:
rootView = inflater.inflate(R.layout.medicard_fragment, container, false);
break;
}
//TextView textView = (TextView) rootView.findViewById(R.id.section_label);
// textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
}
}
and the Fragment that holds the recyclerView Java
package com.example.tmcpm;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.List;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
public class FragmentMedicard extends Fragment implements View.OnClickListener {
View v;
private RecyclerView myrecyclerview;
private List<MediCard> mData;
FloatingActionButton fabAdd;
Context mContext;
public View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedinstanceState) {
View myView = inflater.inflate(R.layout.medicard_fragment, container, false);
fabAdd = (FloatingActionButton) myView.findViewById(R.id.floatButtonAdd);
fabAdd.setOnClickListener(this);
return myView;
}
#Override
public void onClick(View v) {
Toast.makeText(mContext,"ADDING", Toast.LENGTH_SHORT).show();
}
}
I really dont know what to do anymore
I tried putting my code for the fab in the adapter which only cause a nullpointer exception which is i think is right since its in a different fragment
Create an instance variable to hold your recyclerAdapter in your fragment. Then you can have the FAB click listener add a MediaCard to mData.
Then call
recyclerAdapter.notifyDataSetChanged();

error: incompatible types: machinemessage cannot be converted to Fragment

i didn't understand this problemm please help ....
the problem in new machinemessage().commit()
package com.example.ashraf.myapplication;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_liste:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new listemessage()).commit();
break;
case R.id.nav_machine:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new machinemessage()).commit();
break;
case R.id.nav_Listepannes:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new listedespannesmessage()).commit();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
this is the class machinemessage that i want to put in it a tabeLayout but its not working
package com.example.ashraf.myapplication;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.widget.TextView;
public class machinemessage extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_tab, menu);
return true;
}
#Override
// public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
// return inflater.inflate(R.layout.fragment_tab, container, false);
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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tab, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position){
case 0 :
fragment = new frag1();
break;
case 1:
fragment = new frag2();
break;
case 2 :
fragment = new frag3();
break;
}
return fragment;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
}
}
the problem in new machinemessage()
i need a solution please i need a solution please i need a solution please i need a solution please i need a solution please i need a solution please i need a solution please i need a solution please i need a solution please i need a solution please i need a solution please i need a solution please i need a solution please
A FragmentTransaction (getSupportFragmentManager.beginTransaction ...) only can be done with a Fragment. Check out the Fragment documentation to get further information about Fragments. Right now you are trying to add an Activity (machinemessage) as a Fragment to the MainActivity.
An example code for a Fragment:
public class ExampleFragment extends Fragment {
public ExampleFragment() {
//empty public constructor is necessary
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_example, container, false);
//Reference for a TextView in fragment_example.xml layout
TextView textView = rootView.findViewById(R.id.textView);
return rootView;
}
}
If you simply want to start a new Activity from the first Activity, use the following code: startActivity(new Intent(this, machinemessage.class));
Instead of putting like this...
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new listedespannesmessage()).commit();
I did it like this and it worked like a champ...
Intent mlistedespannesmessage = new Intent(getApplicationContext(), listedespannesmessage.class);
startActivity(mlistedespannesmessage);

Android: E/RecyclerView: No adapter attached; skipping layout

so i have a tabbed activity that contains 3 tabs as fragments, each tab has a RecyclerView.
I checked all the answered questions on here and on other sites, everything seems fine, yet it doesn't work!
here's my Code:
MainActivity.java:
package esprit.tn.mywaterproject;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.time.Duration;
import java.util.zip.Inflater;
public class MainActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.e("test","test log");
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new
SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new
TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new
TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Chat avec un
résponsable", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.e("frag number", "frag test number
:"+getArguments().getInt(ARG_SECTION_NUMBER));
if (getArguments().getInt(ARG_SECTION_NUMBER)==1){
Log.e("frag test1", "frag test TEST1");
new Eaux_Fragment();
return inflater.inflate(R.layout.fragment_eaux,
container,false);
}
if (getArguments().getInt(ARG_SECTION_NUMBER)==2){
Log.e("frag test2", "frag test TEST2");
return inflater.inflate(R.layout.fragment_piscine,
container,false);
}
if (getArguments().getInt(ARG_SECTION_NUMBER)==3){
Log.e("frag test3", "frag test TEST3");
return inflater.inflate(R.layout.fragment_electricite, container,false);
}
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
}
}
Here's my Adapter
ProduitAdapter.java :
package esprit.tn.mywaterproject;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import esprit.tn.mywaterproject.Entities.Produit_Eau;
public class ProduitAdapter extends
RecyclerView.Adapter<ProduitAdapter.ViewHolder> {
private Context context;
private List<Produit_Eau> list;
public ProduitAdapter( Context context, ArrayList<Produit_Eau> list) {
this.context=context;
this.list = list;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.e("LOG IN ADAPTER","TEST ADAPTER");
View v =
LayoutInflater.from(context).inflate(R.layout.single_produit_eau, parent,
false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Produit_Eau prod_eau = list.get(position);
holder.text_single_prod_nom.setText(prod_eau.getNom());
holder.text_single_prod_description.setText(prod_eau.getDescription());
}
#Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView text_single_prod_nom, text_single_prod_description;
public ViewHolder(View itemView) {
super(itemView);
text_single_prod_nom = itemView.findViewById(R.id.single_prod_nom);
text_single_prod_description =
itemView.findViewById(R.id.single_prod_description);
}
}
}
And Here's one of the fragments
Eau_Fragment.java
package esprit.tn.mywaterproject.Fragments;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import esprit.tn.mywaterproject.Entities.Produit_Eau;
import esprit.tn.mywaterproject.ProduitAdapter;
import esprit.tn.mywaterproject.R;
/**
* A simple {#link Fragment} subclass.
*/
public class Eaux_Fragment extends Fragment {
private RecyclerView recyclerList;
private LinearLayoutManager linearLayoutManager;
private ArrayList<Produit_Eau> produit_eauList;
private ProduitAdapter adapter;
private String UrlShowProducts = "http://192.168.1.7:3003/prodeau";
private LinearLayout linearLayout;
public Eaux_Fragment() {
Log.e("Test Eau Fragment","EAU FRAG TEST");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragmentd
View view = inflater.inflate(R.layout.fragment_eaux, container, false);
linearLayoutManager = new
LinearLayoutManager(getActivity().getApplicationContext());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
DividerItemDecoration(recyclerList.getContext(),
linearLayoutManager.getOrientation());
adapter = new ProduitAdapter(getActivity().getApplicationContext(),
produit_eauList);
recyclerList = getActivity().findViewById(R.id.eau_prod_list);
recyclerList.setHasFixedSize(true);
recyclerList.setLayoutManager(linearLayoutManager);
produit_eauList = new ArrayList<>();
getData();
recyclerList.setAdapter(adapter);
adapter.notifyDataSetChanged();
return view;
}
private void getData() {
JsonArrayRequest jsonArrayRequest = new
JsonArrayRequest(UrlShowProducts, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
Produit_Eau produit_eau = new Produit_Eau();
produit_eau.setNom(jsonObject.getString("name"));
produit_eau.setDescription(jsonObject.getString("description"));
produit_eauList.add(produit_eau);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
}
});
RequestQueue requestQueue =
Volley.newRequestQueue(getActivity().getApplicationContext());
requestQueue.add(jsonArrayRequest);
}
}
Edit:
The problem i'm facing here is that Eau_Fragment is not showing in the application. i've deleted every other fragment and kept only this one to test it, the fragment is displayed empty, and the only error i got is the one mentionned above.
It's only a warning but if you're concerned about it, then set the adapter before the layout manager:
recyclerList = getActivity().findViewById(R.id.eau_prod_list);
recyclerList.setAdapter(adapter);
recyclerList.setHasFixedSize(true);
recyclerList.setLayoutManager(linearLayoutManager);
Because it triggers layout update immediately when you set layout manager, which looks for the adapter eventually.
I am not sure what is the problem you are facing, but one thing I noticed, is that you are not using Eaux_Fragment in your SectionsPagerAdapter so you need change :
return PlaceholderFragment.newInstance(position + 1);
to
return Eaux_Fragment(position + 1);
and do not forget to add the newInstance method to Eaux_Fragment
public static Eaux_Fragment newInstance(int position) {
Eaux_Fragment fragment = new Eaux_Fragment();
Bundle args = new Bundle();
args.putString(ARG_POSITION, position);
fragment.setArguments(args);
return fragment;
}

ListFragment in a Tabbed Layout not populating from a SQLite DB

I'm trying to populate 3 ListFragments that are in a Tabbed ViewPager Layout. (Using one of the templates in Android Studio.)
I have been able to successfully put items into the SQLite DB, but I'm having a hard time populating the ListView(s). It would be easy if things weren't static, but the static-ness simply adds to the complexity.
package com.example.listapp;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ListFragment;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import static com.example.listapp.ItemData.Items.ORDERB;
import static com.example.listapp.ItemData.Items.TABLE_NAME;
import static com.example.listapp.ItemData.Items.TYPE;
import static com.example.listapp.ItemData.Items.LIST_TEXT;
public class MainActivity extends AppCompatActivity {
private ItemData ItemsDb;
String listText = null;
public static String[] FROM = { LIST_TEXT };
public static int[] TO = { R.id.list_text };
public static final Uri CONTENT_URI = Uri.parse("content://"
+ "com.example.listapp" + "/" + TABLE_NAME);
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ItemsDb = new ListData(getApplicationContext());
Intent saveIntent = getIntent();
listText = saveIntent.getStringExtra(ItemCreate.EXTRA_MESSAGE);
if (rlistText != null) {
SQLiteDatabase db = ItemsDb.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ORDERB, System.currentTimeMillis());
values.put(ITEM_TEXT, listText);
db.insertOrThrow(TABLE_NAME, null, values);
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
public void createItem(View view) {
Intent intent = new Intent(this, ItemCreate.class);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "List1";
case 1:
return "List2";
case 2:
return "List3";
}
return null;
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends ListFragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Cursor cursor = getActivity().getContentResolver().query(CONTENT_URI, FROM, null, null, "_ID DESC");
ListView listItems = getListView();
ListAdapter adapter = new SimpleCursorAdapter(getContext(), R.layout.list_item, cursor, FROM, TO, 0);
listItems.setAdapter(adapter);
}
}
}
The adapter does get properly set, but I get the following error when I run the code:
E/ActivityThread: Failed to find provider info for com.example.listapp
What am I doing wrong?

Calling getView on a Fragment returns null

So as you can see in the onCreate method i call getView on the 0th fragment in the "fragments" list. It returns null. I've tried putting a timer in the code and have it run every second and check if the view is null. And on the second tick of the timer the view is NOT null. Basically
MainActivity.java
package com.axinite.standapp;
import android.graphics.Color;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.EditText;
import android.widget.NumberPicker;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;
public class MainActivity extends AppCompatActivity {
int i = 0;
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
int standUpSeconds = 4000;
List<android.support.v4.app.Fragment> fragments = new Vector<android.support.v4.app.Fragment>();
NumberPicker SUPickerH;
NumberPicker SUPickerM;
NumberPicker SUPickerS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fragments.add(Fragment.instantiate(this, BlankFragment.class.getName()));
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), fragments);
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.setSelectedTabIndicatorColor(Color.WHITE);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
final int[] ICONS = new int[] {
R.drawable.walking,
R.drawable.iris
};
for (int i=0; i < tabLayout.getTabCount(); i++)
{
tabLayout.getTabAt(i).setIcon(getDrawable(ICONS[i]));
}//endfor)
View view = ((BlankFragment) fragments.get(0)).getView();
if(view != null) {
TextView tv = (TextView) view.findViewById(R.id.glupost);
tv.setText("dasdas");
//Toast.makeText(getApplicationContext(), ((Fragment) fragments.get(0)).toString(), Toast.LENGTH_SHORT).show();
}
}
void Setup() {
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
List<Fragment> fragments;
public SectionsPagerAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
// Show 3 total pages.
return fragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return "";
}
}
}
BlankFragment.java
package com.axinite.standapp;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link BlankFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link BlankFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class BlankFragment extends Fragment {
protected View mView;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment BlankFragment.
*/
// TODO: Rename and change types and number of parameters
public static BlankFragment newInstance(String param1, String param2) {
BlankFragment fragment = new BlankFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public BlankFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_blank, container, false);
mView = view;
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}
The typical method for an Activity to communicate with its Fragments is as follows:
MyFragment frag = (MyFragment) getFragmentManager().findFragmentById(R.id.container_of_fragment);
frag.getMyTextView().setText("New text");
or (often preferred IMO)
MyFragment frag = (MyFragment) getFragmentManager().findFragmentByTag("fragment_tag_string_value");
frag.getMyTextView().setText("New text");
This is rendered more difficult with a ViewPager however, as the "id" of the container is the ViewPager itself, which contains multiple fragments. In addition, there isn't an in built adapter mechanism (that I'm aware of) to set tags to fragments.
There are two methods I can think of that circumvent this. First, you can use an EventBus, such as GreenRobot's EventBus, or LocalBroadcastManager from the Android API. GreenRobot's EventBus is also the recommended technique in the answer to this similar question.
An alternative would leverage the fact that a Fragment always has a reference to its host Activity, which means the Fragment could request the text from the Activity via an interface, which returns it to the Fragment:
public class MainActivity implements FragmentOne.Callbacks {
//...
#Override
public String requestTextViewString() {
return "Text to send to Fragment"
}
And inside your hypothetical FragmentOne:
public class FragmentOne extends Fragment {
private Callbacks mCallback;
private TextView mTextView;
public interface Callbacks {
String requestTextViewString();
}
#Override
public void onAttach(Activity activity) {
if (activity instanceof Callbacks) {
mCallback = (Callbacks) activity;
}
}
/*
*Later in your Fragment, when you want to get text from your MainActivity
* i.e. in onCreateView()
*/
mTextView.setText(mCallback.requestTextViewString());
Edit: Also keep in mind that attempting to access your Fragment from onCreate() in your Activity is likely to result in a NullPointerException. This diagram shows both lifecycles alongside each other. This shouldn't be a problem however, as anything required during the "set-up" lifecycle events of the Fragment can just be passed as an argument in the Fragment's newInstance() method:
public class FragmentOne extends Fragment {
private static final String KEY = "text_for_text_view_key";
public static FragmentOne newInstance(String textForTextView) {
Bundle args = new Bundle();
FragmentOne frag = new FragmentOne();
args.putString(KEY, textForTextView);
frag.setArguments(args);
return frag;
}
//And when required...
mTextView.setText(getArguments().getString(KEY));

Categories