When I try to access outer class with this code:
ImageView myView = new ImageView(Logger.this.getActivity().getApplicationContext());
it says:
The method getActivity() is undefined for the tyoe Logger
No enclosing instance of the type Logger is accessible in scope
Here is my Logger.java:
import java.util.Locale;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
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.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageSwitcher;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.ViewSwitcher.ViewFactory;
public class Logger extends FragmentActivity implements ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.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}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
static boolean isBoxOpen = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logger);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setTitle("Sosyaaal");
actionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.action_bar));
Thread connectivity = new Thread(){
public void run(){
try {
while(true)
{
while(!isBoxOpen)
{
if( !isOnline() )
{
isBoxOpen = true;
// display error
runOnUiThread(new Runnable() {
public void run() {
new AlertDialog.Builder(Logger.this)
.setTitle("Bağlantı Sorunu")
.setMessage("İnternet bağlantısını kontrol edip tekrar deneyin")
.setCancelable(false)
.setPositiveButton(R.string.yeniden, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Logger.isBoxOpen = false;// Try Again
}
})
.show();
}
});
}
}
}
} catch (Exception e) {
}
}
};
connectivity.start();
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.logger, menu);
return true;
}
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
#Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* 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) {
switch (position) {
case 0:
// Giriş fragment activity
return new GirisFragment();
case 1:
// Kayıt fragment activity
return new KayitFragment();
}
return null;
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class GirisFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public GirisFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_giris,
container, false);
return rootView;
}
}
public static class KayitFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
private ImageSwitcher cinsiyetSwitcher;
public KayitFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_kayit,
container, false);
cinsiyetSwitcher = (ImageSwitcher) getView().findViewById(R.id.cinsiyetSwitcher);
cinsiyetSwitcher.setFactory(new ViewFactory() {
#Override
public View makeView() {
ImageView myView = new ImageView(Logger.this.getActivity().getApplicationContext());
myView.setScaleType(ImageView.ScaleType.FIT_CENTER);
return myView;
}
});
return rootView;
}
}
}
*EDIT*
Changing this line:
ImageView myView = new ImageView(Logger.this.getActivity().getApplicationContext());
to this:
ImageView myView = new ImageView((Logger)getActivity().getApplicationContext());
solved the problem, but that was not what I was looking for. Thanks to Kapil Vij for correct Answer!
Do this
ImageView myView = new ImageView(getActivity());
getActivity() method is accessible in fragment class, and u r trying to access it using FragmentActivity class instance.
change to:
Logger.this.getApplicationContext()
Logger it-self is activity you call getActivity to get the reference of the activity inside a Fragment
EDIT
Saw that you are calling it inside a fragment change you code to:
ImageView myView = new ImageView(KayitFragment.this.getActivity().getApplicationContext());
Related
I recently started to write an application which let me to get information from a forum. I used JSoup library for scraping the data. My first part is going well.
When the app opens, it just gets data from the site(sub-forum names) and pass it so the listview is able to show them. When I press an item in the listview it just gets the thread list in the sub-forum. All the things are working properly excepts the listview doesn't get updated correctly.
As you can see when I press an item from the list(Just the first item in the list) then it set loadedSub to true then it gets the thread list using an async-task then in the postexecute it calls notifyDataSetChanged() on PagerAdapter. The problem is it just updates the UI perfectly, even leaving 1 tab only as I wanted, but the problem is that threadList doesn't appear in the listview. It only shows me the listview with previous data, not the threadlist.
Should I use another activity or is there something I am missing?
MainActivity.java
package com.ovnis.sscattered.elakiriunofficial;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
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.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
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}.
*/
public static SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
public static ViewPager mViewPager;
public static String[][] forumListSubForumsList = new String[13][];
public static String[][] forumListSubForumListLinks = new String[13][];
public static String[][] threadListLinks = new String[2][];
static Context context;
public String[] forumNumbers = {"1", "86", "89", "6",
"66", "79", "70", "12",
"16", "33", "42", "25",
"22"};
public static String subforumLink;
static boolean loaded = false;
static boolean loadedSub = false;
static boolean subForumMode = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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);
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();
}
});
new GetSubForumList().execute();
context = getBaseContext();
}
#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 SubForumsFrag extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
static ListView listview;
static ForumListAdapter adapter;
int pos = 0;
public SubForumsFrag() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static SubForumsFrag newInstance(int pos) {
SubForumsFrag fragment = new SubForumsFrag();
Bundle args = new Bundle();
args.putInt("poskey", pos);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.list_base, container, false);
listview = (ListView) rootView.findViewById(R.id.listview);
pos = getArguments().getInt("poskey");
if(loaded){
adapter = new ForumListAdapter(getActivity(), forumListSubForumsList[pos]);
}
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getContext(), forumListSubForumListLinks[pos][position], Toast.LENGTH_SHORT).show();
subForumMode = true;
subforumLink = forumListSubForumListLinks[pos][position];
new GetThreadList().execute();
}
});
return rootView;
}
}
public static class ThreadListFrag extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
static ListView listview;
static ForumListAdapter adapter;
int pos = 0;
public ThreadListFrag() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static ThreadListFrag newInstance() {
ThreadListFrag fragment = new ThreadListFrag();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.list_base, container, false);
listview = (ListView) rootView.findViewById(R.id.listview);
if(loadedSub){
adapter = new ForumListAdapter(getActivity(), threadListLinks[0]);
}
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Toast.makeText(getContext(), forumListSubForumListLinks[pos][position], Toast.LENGTH_SHORT).show();
}
});
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 SubForumsFrag (defined as a static inner class below).
if(!subForumMode){
return SubForumsFrag.newInstance(position);
}else{
return ThreadListFrag.newInstance();
}
}
#Override
public int getCount() {
// Show 13 total pages.
if(!subForumMode){
return 13;
}else{
return 1;
}
}
#Override
public CharSequence getPageTitle(int position) {
if(!subForumMode){
switch (position) {
case 0:
return "Elakiri";
case 1:
return "Cooking";
case 2:
return "B & M";
case 3:
return "General";
case 4:
return "E. Traveler";
case 5:
return "Automobile";
case 6:
return "Motorcycles";
case 7:
return "Entertainment";
case 8:
return "C & I";
case 9:
return "S. Piyasa";
case 10:
return "Elakiri Magic";
case 11:
return "Games";
case 12:
return "Mobile";
}
}else{
return "Bitch Me";
}
return null;
}
#Override
public int getItemPosition(Object obj){
return POSITION_NONE;
}
}
class GetSubForumList extends AsyncTask<Void, Integer, String>
{
String TAG = getClass().getSimpleName();
ProgressDialog dialog;
protected void onPreExecute (){
Log.d(TAG + " PreExceute","On pre Exceute......");
dialog = new ProgressDialog(MainActivity.this);
dialog.setTitle("Loading...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
protected String doInBackground(Void...arg0){
Log.d(TAG + " DoINBackGround","On doInBackground...");
try {
Connection.Response response = Jsoup.connect("http://www.elakiri.com/forum/")
.execute();
Document parsedDoc = response.parse();
Element doc;
Elements doce;
for(int i = 0; i < forumNumbers.length; i++){
doc = parsedDoc.select("tbody#collapseobj_forumbit_" + forumNumbers[i]).first();
doce = doc.select("a[href] strong");
forumListSubForumsList[i] = new String[(doce.size()+1)/2];
forumListSubForumListLinks[i] = new String[(doce.size()+1)/2];
for(int q = 0; q < (doce.size()+1)/2; q++){
forumListSubForumsList[i][q] = doce.get(q*2).text();
forumListSubForumListLinks[i][q] = doce.get(q*2).parent().absUrl("href");
}
}
} catch (IOException e) {
e.printStackTrace();
}
return "Shot";
}
protected void onProgressUpdate(Integer...a){
Log.d(TAG + " onProgressUpdate", "You are in progress update ... " + a[0]);
}
protected void onPostExecute(String result) {
Log.d(TAG + " onPostExecute", "" + result);
loaded = true;
mViewPager.invalidate();
mSectionsPagerAdapter.notifyDataSetChanged();
dialog.dismiss();
}
}
static class GetThreadList extends AsyncTask<Void, Integer, String>
{
String TAG = getClass().getSimpleName();
ProgressDialog dialog;
protected void onPreExecute (){
Log.d(TAG + " PreExceute","On pre Exceute......");
dialog = new ProgressDialog(context);
dialog.setTitle("Loading...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
// dialog.show();
}
protected String doInBackground(Void...arg0){
Log.d(TAG + " DoINBackGround","On doInBackground...");
try {
Connection.Response response = Jsoup.connect(subforumLink)
.execute();
Element doc = response.parse().select("tbody#threadbits_forum_2").first();
Elements doce = doc.select("a[id^=thread_title_]");
threadListLinks[0] = new String[doce.size()];
threadListLinks[1] = new String[doce.size()];
for(int i = 0; i < doce.size(); i++){
threadListLinks[0][i] = doce.get(i).text();
threadListLinks[1][i] = doce.get(i).absUrl("href");
}
} catch (IOException e) {
e.printStackTrace();
}
return "Shot";
}
protected void onProgressUpdate(Integer...a){
Log.d(TAG + " onProgressUpdate", "You are in progress update ... " + a[0]);
}
protected void onPostExecute(String result) {
Log.d(TAG + " onPostExecute", "" + result);
loadedSub = true;
mViewPager.invalidate();
mSectionsPagerAdapter.notifyDataSetChanged();
}
}
}
ForumListAdapter.java
public class ForumListAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public ForumListAdapter(Context context, String[] values) {
super(context, R.layout.main_adapter ,values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.main_adapter, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.firstLine);
textView.setText(values[position]);
return rowView;
}
}
Alright, I got it solved using FragmentStatePageAdapter instead of using FragmentPageAdapter
I know there has been a question similar to this, but I have a slightly different problem.
I created the default tabbed activity for android and am using it as is given by Android Studio. I was wondering what the behavior of the onCreateView() function for the Placeholder Fragment is and whether I would be able to change it so that, at the beginning of the activity, it calls the onCreateView() for all three of the Placeholder Fragments, and never calls this function again?
Thanks in advance.
Here is the default tabbed activity for reference:
package com.example.myname.myproject;
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 SampleActivity 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_sample);
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);
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_sample, 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_sample, 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;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
case 2:
return "SECTION 3";
}
return null;
}
}
}
Sorry, I should have done some more research: mViewPager.setOffscreenPageLimit(3); works
I am new at android development and just trying to learn along the way!
I am creating an android app that I would like to show different views, one for weight, weather, and hydration (are what I have called them for now). Although when I run my app I only get my one view displayed.
What code do I have to add/modify in order to display the other two layouts in the tabbed view?
Here is my code in MainActivity.java
package com.oxinc.android.drate;
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.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int quantity = 0;
String outcome = "";
int required = 0;
int height = 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;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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);
//Tabbed Layout
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
//Floating Action Button
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Are you hydrated?", 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_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 static PlaceholderFragment fragment_main() {
PlaceholderFragment fragment = new PlaceholderFragment();
return fragment;
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment weight(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 hydration = inflater.inflate(R.layout.hydration, container, false);
return hydration;
}
}
/**
* 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.weight(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Hydration";
case 1:
return "Weigh In";
case 2:
return "Weather";
}
return null;
}
}
public void eight(View view) {
quantity = quantity + 8;
displayQuantity(quantity);
}
public void twelve(View view) {
quantity = quantity + 12;
displayQuantity(quantity);
}
public void sixteen(View view) {
quantity = quantity + 16;
displayQuantity(quantity);
}
public void thirty_two(View view) {
quantity = quantity + 32;
displayQuantity(quantity);
}
public void sixty_four(View view) {
quantity = quantity + 64;
displayQuantity(quantity);
}
//Reset Button
public void reset(View view) {
quantity = 0;
displayQuantity(quantity);
outcome = "";
displayOutcome(outcome);
}
//Starts the basic formula for oz. per day
public int height(int value) {
EditText height = (EditText) findViewById(R.id.height);
String height_value = height.getText().toString();
int int_height = Integer.parseInt(height_value);
if (int_height >= 60) {
required = 64;
}
return required;
}
/**
* This method is called when the check button is clicked.
*/
public String check(View view) {
height((int) height);
if (quantity >= required) {
outcome = "You have met your goal!!";
} else {
outcome = "Keep trying you are almost there";
}
displayOutcome(outcome);
return outcome;
}
//Displays the Outcome to the outcome text view
public void displayOutcome(String n) {
TextView outcomeTextView = (TextView) findViewById(
R.id.outcome_text_view);
outcomeTextView.setText(outcome);
}
/**
* This method displays the given quantity value on the screen.
*/
public void displayQuantity(int quantity) {
TextView quantityTextView = (TextView) findViewById(
R.id.quantity_text_view);
quantityTextView.setText(quantity + "");
}
}
An once I run it I just get three screens that look like this...
Inside your public Fragment getItem(int position) {
which is inside your
public class SectionsPagerAdapter extends FragmentPagerAdapter {
Implement this:
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new fragment1();
case 1:
return new fragment2();
case 2:
return new fragment3();
default:
// this should never happen
return null;
//return new Fragment();
}
}
Where "fragment1-2 and 3" are the name of the java classes you've defined to run there.
I use my "getItem" exactly this way, with nothing more inside it. So I don't know if you have to maintain your return PlaceholderFragment.weight(position + 1); there. Try commenting it out and see what happens. I don't use createview either. Best.
The problem is here
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View hydration = inflater.inflate(R.layout.hydration, container, false);
return hydration;
}
You are always inflating the hydration layout, in every fragment
I'm relatively new to both Java and the android platform and I have come across a problem in my code that is just completely beyond me. I am trying to lock onto a users location and move the camera to that location using the google maps api v2 however this is without success even with constant reading of resources and attempts.
The method requestLocationUpdates(String, long, float, LocationListener) in the type >LocationManager is not applicable for the arguments (String, int, int, LocationListener) >MainActivity.java /Loca/src/com/afrostudio/loca line 91 Java Problem
Also a very recent error has randomly occured:
R cannot be resolved to a variable
Any help would be fantastic please :)
package com.afrostudio.loca;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.MapFragment;
public class MainActivity extends Activity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
private GoogleMap map;
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
public class googleMap extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_main, container, false);
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
// Define a listener that responds to location updates
LocationListener locationListner = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
double latti = location.getLatitude();
double longi = location.getLongitude();
CameraUpdate center=
CameraUpdateFactory.newLatLng(new LatLng(latti,
longi));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(15);
map.moveCamera(center);
map.animateCamera(zoom);
}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListner);
}
#Override
public void onDestroyView()
{
super.onDestroyView();
Fragment fragment = (getFragmentManager().findFragmentById(R.id.map));
FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
ft.remove(fragment);
ft.commit();
}
}
public class MyFragment2 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_profile, container, false);
}
}
public class MyFragment3 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_settings, container, false);
}
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
Fragment fragment = new googleMap();
FragmentManager fragmentManager = getFragmentManager();
switch(position) {
case 1:
fragment = new googleMap();
break;
case 2:
fragment = new MyFragment2();
break;
case 3:
fragment = new MyFragment3();
break;
}
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
ActionBar ab = getActionBar();
ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#A4C639"));
ab.setBackgroundDrawable(colorDrawable);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* 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";
/**
* 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 onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
The R error thing has to do with your xml files (layouts) check them carefully. Try cleaning the project as well... As for the Location I sugest you to use the LocationClient, it is newer and performs better... https://developer.android.com/training/location/receive-location-updates.html
I am trying to get the selected values of first second and third screen to be used in the final fourth screen. How would I go about accessing the radio groups of the previous fragments?
I have tried to store the selected value in the onPause method of each fragment but it gets called when I slide from the first fragment to the third fragment and not from the first to the second.
I have tried to use a listener for the radiogroup but it never gets called.
I have tried to access the other three fragments from the final Tsiatista fragment but without any success.
package com.tsiatistonmyfriend;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Locale;
import net.justanotherblog.swipeview.R;
import android.os.Bundle;
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.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class MainActivity extends FragmentActivity {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
public static String funnySerious;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
OnClickListener listener = new OnClickListener()
{
#Override
public void onClick(View v)
{
RadioButton rb = (RadioButton) v;
funnySerious = (String) rb.getText();
}
};
/**
* 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)
{
Fragment fragment = new FunnySerious();
switch (position)
{
case 0:
return fragment = new FunnySerious();
case 1:
return fragment = new MaleFemale();
case 2:
return fragment = new DirtyClean();
case 3:
return fragment = new Tsiatisto();
default:
break;
}
return fragment;
}
#Override
public int getCount() {
// Show 4 total pages.
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
case 3:
return getString(R.string.title_section4).toUpperCase(l);
}
return null;
}
}
public static class FunnySerious extends Fragment
{
View v;
public FunnySerious() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.funny_serious, container, false);
v = rootView;
return rootView;
}
}
public static class MaleFemale extends Fragment
{
public MaleFemale() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.male_female, container, false);
return rootView;
}
}
public static class DirtyClean extends Fragment
{
public DirtyClean() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.dirty_clean, container, false);
return rootView;
}
}
public static class Tsiatisto extends Fragment
{
public Tsiatisto() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
//FunnySerious textFragment = (FunnySerious) this.getActivity().getSupportFragmentManager().findFragmentById(R.id.pager);
View rootView = inflater.inflate(R.layout.tsiatisto, container, false);
DataBaseHelper myDbHelper = new DataBaseHelper(this.getActivity().getApplicationContext());
try
{
myDbHelper.createDataBase();
myDbHelper.openDataBase();
}catch(IOException ioe)
{
throw new Error("Unable to create database");
}
final SQLiteDatabase db = myDbHelper.getDB();
Cursor cursor;
cursor = db.query("Tsiatista ORDER BY RANDOM() LIMIT 1", new String[] { "*" }, null, null, null, null, null);
//cursor = db.rawQuery("SELECT Verse FROM Tsiatista WHERE ID = 1", null);
if(cursor.moveToFirst())
{
String htr;
htr = (String) cursor.getString(cursor.getColumnIndex("Verse"));
EditText et = (EditText) rootView.findViewById(R.id.tsiatistoTxt);
et.setText(htr);
cursor.close();
}
return rootView;
}
}
}
Two ways,
Pass selected values as key value boolean pair in form of bundle, using setArgument method when you switch between fragment. You can then access this passed bundle and use selected values from previous fragment to drive you logic further, you can then club this values with values from current fragment and and navigate it further.
Read about shared preferences, you can always save value persistently and access it from all over your application, so using this you can save value selected by user from first three fragment, retrieve it on fourth and complete your logic.
Hope it help.