How to display other layouts? - java

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

Related

use viewpager with different fragments?

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

Tabbed Activity onCreate for each of the tabs

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

Error:(69, 20) error: method onCreate(Bundle) is already defined in class MainActivity

I am creating a simple app. I am running into one problem to finalize the app.
I am trying onclick image WebView in tabbed view.
However, only the first button opens the scanner. The second button does not do anything.
This is my current code from MainActivity.java:
package in.radioactiveenterprise.watchout;
import android.content.Intent;
import android.support.design.widget.TabLayout;
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.ImageView;
import android.widget.TextView;
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);
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);
}
private static ImageView img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
click();
}
public void click()
{
img = (ImageView)findViewById(R.id.imageViewz);
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
Intent intent = new Intent("in.radioactiveenterprise.watchoutt1.Main2Activity");
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 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) {
if (getArguments().getInt(ARG_SECTION_NUMBER) == 1)
{
View rootView = inflater.inflate(R.layout.fragment_sub_page01, container, false);
return rootView;
}
else if (getArguments().getInt(ARG_SECTION_NUMBER) == 2)
{
View rootView = inflater.inflate(R.layout.fragment_sub_page02, container, false);
return rootView;
}
else
{
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 + 3);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "FASTBOOK";
case 1:
return "TIMELINE";
case 2:
return "FARMBOOK";
}
return null;
}
}
}
In Your MainActivity remove below method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
click(); // add this into your Primary onCreate method.
}
Note: You can not use the same method with same Arguments in one class.
you can use bellow method if your activities created with
the attribute android.R.attr.persistableMode.
Same as onCreate(Bundle) but called for those activities created with
the attribute android.R.attr.persistableMode set to
persistAcrossReboots.
persistentState - if the activity is being re-initialized after
previously being shut down or powered off then this Bundle contains
the data it most recently supplied to outPersistentState in
onSaveInstanceState. Note: Otherwise it is null.
#Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
}
You have 2 onCreate():
#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);
click();
}
Remove the click() method and add into main onCreate():
REMOVE ALL:
private static ImageView img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
click(); //add this on onCreate
}

Using Bundle to pass data between class and fragment

I'm trying to use Bundle to pass data from the Query class (i'm "setting the arguments" in the Query class) to one of the Fragment classes (i need to "getArguments()" in this fragment class), however i have done some basic debugging using logs and have seen that the fragment is being created before the Query class is being implemented. Therefore when i "getArguments" from within the fragment class it is NULL because the arguments have not been set yet in the Query class.
I want to use the data from the Query class in the fragment class. Can anybody advise me as to what to do?
As you can probably tell i'm relatively new to Android and don't really understand Fragments either.
Context: I'm developing a Weather application. I have three fragments for today, tomorrow and seven day forecasts (inspired by the tabbed layout Google Now's weather card). I also have a Query class querying an online API for JSON data as well as of course the main activity class.
MainActivity class:
package com.example.desno.testnavtablayout;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;
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.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.support.design.widget.TabLayout;
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.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.TextView;
import org.json.JSONObject;
import java.util.concurrent.ExecutionException;
import tabFragments.SevenDayFragment;
import tabFragments.TodayFragment;
import tabFragments.TomorrowFragment;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
public Double latitude;
public Double longitude;
private static final String API_KEY = "&APPID="; // Placeholder for the openweathermaps API key
private static final String QUERY_URL = "http://api.openweathermap.org/data/2.5/weather?q="; // Placeholder for the openweathermaps URL
private static final String UNITS = "&mode=json&units=metric&cnt=7"; // Placeholder specifying the data type and unit type of this data being retrieved
/**
* 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);
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();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
// Initialise the Android location manager to get the users current location automatically:
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String provider = locationManager.getBestProvider(new Criteria(), false);
// Handle what happens if the user doesn't grant permission for location (this has been generated automatically):
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location location = locationManager.getLastKnownLocation(provider); // Get last known location of the user
latitude = location.getLatitude(); // Storage variable for the users latitude
longitude = location.getLongitude(); // Storage variable for the users logitude
Query query = new Query(); // Create a new instance of the Query class, pass it the URL with the values of the users GPS coordinates embedded and execute it
query.execute("http://api.openweathermap.org/data/2.5/weather?lat=" + String.valueOf(latitude) + "&lon=" + String.valueOf(longitude) + UNITS + API_KEY);
}
// Receives the value of searchLocationQuery and manipulates it
private JSONObject queryForRequestedLocation(String location)
{
String parsedData = ""; // Placeholder for URL with embedded search value
try
{
parsedData = new Query().execute(QUERY_URL + location + UNITS + API_KEY).get(); // Pass the URL with embedded search, units and API key to the Query class for parsing
}
catch (InterruptedException e)
{
e.printStackTrace();
}
catch (ExecutionException e)
{
e.printStackTrace();
}
return null;
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#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;
}
#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.content_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).
switch(position){
case 0 : return TodayFragment.newInstance();
case 1 : return TomorrowFragment.newInstance();
case 2 : return SevenDayFragment.newInstance();
// default: return MyFragment.newInstance();
/* It is better to use default so that it always returns a fragment and no problems would ever occur */
}
return null; //if you use default, you would not need to return null
/*// 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;
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Query class:
package com.example.desno.testnavtablayout;
/**
* Created by desno on 30/05/2016.
*/
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import org.json.JSONObject;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import tabFragments.TodayFragment;
public class Query extends AsyncTask<String, Void, String>
{
private static String locationName;
// Query for the data
#Override
protected String doInBackground(String... urls)
{
String queryResult = ""; // Storage variable for the json data
URL url; // URL is used as address to the data needed
HttpURLConnection urlConnection = null; // Make a remote request using the HttpURLConnection class
// Surround with try/catch so the application doesn't crash in the case of an exception such as no internet connection
try
{
url = new URL(urls[0]); // Create a new URL from what is supplied
urlConnection = (HttpURLConnection) url.openConnection(); // Establish a URL connection and pass it to a HttpURLConnection
InputStream inputStream = urlConnection.getInputStream(); // Get an InputStream from the HttpURLConnection
InputStreamReader inputStreamReader = new InputStreamReader(inputStream); // Create an InputStreamReader to read the InputStream
int inputStreamData = inputStreamReader.read(); // Store the data from the InputStreamReader
// Need a while loop because when InputStreamReader is finished the result is equal to -1
while (inputStreamData != -1)
{
char current = (char) inputStreamData;
queryResult += current;
inputStreamData = inputStreamReader.read();
}
return queryResult;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
// Parse the json data
#Override
protected void onPostExecute(String queryResult)
{
super.onPostExecute(queryResult);
try
{
JSONObject jsonObject = new JSONObject(queryResult); // Create a new json object and pass it the data from the queryResult string
JSONObject weatherData = new JSONObject(jsonObject.getString("main")); // Create another json object to contain more specific weather data such as all the data within the "main" braces
Double temperature = Double.parseDouble(weatherData.getString("temp")); // Grab the temperature value, which is currently stored as a string within the weatherData object, and store it as a double labeled "temperature"
locationName = jsonObject.getString("name"); // Create storage variable for the location name
Bundle args = new Bundle();
args.putString("LocationName", locationName);
TodayFragment todayFragment = new TodayFragment();
todayFragment.setArguments(args);
Log.i("Loc working in query=", args.toString());
// MainActivity.temperatureTextView.setText(temperature.toString()+ " °C"); // Set the value of the temperature TextView equal to the value of the temperature variable and add a degrees celsius symbol
// MainActivity.locationTextView.setText(locationName); // Set the value of the location TextView equal to the value of the locationName variable
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
TodayFragment class:
package tabFragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.example.desno.testnavtablayout.Query;
import com.example.desno.testnavtablayout.R;
import java.security.PublicKey;
/**
* Created by desno on 09/09/2016.
*/
public class TodayFragment extends Fragment
{
Button ClickMe;
TextView tv;
public String loc;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = this.getArguments();
if (bundle == null)
{
//loc = bundle.getString("LocationName");
Log.i("Bundle is STILL null", "TodayFrag OnCreate()");
}
}
public TodayFragment()
{
}
public static TodayFragment newInstance()
{
TodayFragment fragment = new TodayFragment();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_today, container, false);
ClickMe = (Button) rootView.findViewById(R.id.button);
tv = (TextView) rootView.findViewById(R.id.textView2);
ClickMe.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
if(tv.getText().toString().contains("Hello"))
{
tv.setText("Hi");
}
else tv.setText("Hello");
}
});
/*String strtext = getArguments().getString("LocationName");
if (strtext != null)
{
Log.i("Location=", strtext.toString());
}*/
Bundle bundle = this.getArguments();
if (bundle == null)
{
//loc = bundle.getString("LocationName");
Log.i("Bundle is null", "TodayFrag OnCreateView()");
}
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle bundle = this.getArguments();
if (bundle == null) {
//String i = bundle.getString("LocationName");
Log.i("Bundle is null", "in TodayFrag onActivityCreated()");
}
}
#Override
public void onViewStateRestored(Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
Bundle bundle = this.getArguments();
if (bundle == null)
{
//loc = bundle.getString("LocationName");
Log.i("Bundle is STILL null", "TodayFrag OnViewStateRestored()");
}
}
}
try running the Query after you know the fragments have been created. here's two ideas...
one possibility might be to pass the query parameters to the TodayFragment/TomorrowFragment/SevenDayFragment and let them invoke their own queries. something like this:
public class TodayFragment extends Fragment {
private static final String BUNDLE_KEY_SOME_PARAM = "BUNDLE_KEY_SOME_PARAM";
public static TodayFragment newInstance(String someParam) {
final Bundle creationArgs = new Bundle();
creationArgs.putString(BUNDLE_KEY_SOME_PARAM, someParam);
final TodayFragment instance = new TodayFragment();
instance.setArguments(creationArgs);
return instance;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// run the Query locally
final String someParam = getArguments().getString(BUNDLE_KEY_SOME_PARAM);
new Query().execute(someParam);
}
}
if you don't like the idea putting that type of logic your fragments, you could have them call back to MainActivity to run the query as needed. maybe something like this:
interface QueryExecutor {
void query(String someParam);
}
interface QueryResultListener {
void results(String someResult);
}
public class TodayFragment extends Fragment implements QueryResultListener {
private static final String BUNDLE_KEY_SOME_PARAM = "BUNDLE_KEY_SOME_PARAM";
public static TodayFragment newInstance(String someParam) {
final Bundle creationArgs = new Bundle();
creationArgs.putString(BUNDLE_KEY_SOME_PARAM, someParam);
final TodayFragment instance = new TodayFragment();
instance.setArguments(creationArgs);
return instance;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final QueryExecutor queryExecutor = (QueryExecutor)getActivity();
final String someParam = getArguments().getString(BUNDLE_KEY_SOME_PARAM);
queryExecutor.query(someParam);
}
#Override
public void results(String someResult) {
// handle the query results...
}
…
}
i hope that helps.
Why not simply doing the query from within the Fragment? That would be the simplest solution, I guess.

Can't access outer class from fragment class android

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());

Categories

Resources