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.
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I'm trying to put my NestedScrollView on my MapFragment, but when I'm trying to, this error appears :
Attempt to invoke virtual method 'android.view.View android.support.v4.widget.NestedScrollView.findViewById(int)' on a null object reference
Here is my MapFragment.java file
package com.example.alexandre.list.fragments;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.alexandre.list.MainActivity;
import com.example.alexandre.list.R;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link OnMapClickListener} interface
* to handle interaction events.
* Use the {#link MapFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class MapFragment extends Fragment implements OnMapReadyCallback {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private GoogleMap mGoogleMap;
private MapView mMapView;
private OnMapClickListener mListener;
public MapFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment MapFragment.
*/
// TODO: Rename and change types and number of parameters
public static MapFragment newInstance(String param1, String param2) {
MapFragment fragment = new MapFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_map, container, false);
bindViews(view, savedInstanceState);
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed() {
if (mListener != null) {
mListener.onMapClick();
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnMapClickListener) {
mListener = (OnMapClickListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnTweetListClickListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
private void bindViews(View view, Bundle savedInstanceState) {
mMapView = view.findViewById(R.id.map);
mMapView.onCreate(savedInstanceState);
mMapView.getMapAsync(this);
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
LatLng castlePos = new LatLng(45.209299, 5.659144);
LatLng treePos = new LatLng(MainActivity.posx, MainActivity.posy);
CameraPosition liberty = CameraPosition.builder().target(castlePos).zoom(17)/*.bearing(0).tilt(0)*/.build();
Marker marker = mGoogleMap.addMarker(new MarkerOptions()
.position(treePos)
.title("Test du cèdre du Liban")
.snippet("Libani"));
marker.hideInfoWindow();
mGoogleMap.setOnMarkerClickListener(
new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
((AppCompatActivity) getActivity()).getSupportActionBar().hide();
NestedScrollView nestedScrollView = null;
nestedScrollView = (NestedScrollView) nestedScrollView.findViewById(R.id.bottom_sheet);
nestedScrollView.setVisibility(View.VISIBLE);
return false;
}
}
);
mGoogleMap.moveCamera(CameraUpdateFactory.newCameraPosition(liberty));
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnMapClickListener {
void onMapClick();
}
}
It looks like R.id.nestedScrollView return NULL, but why ?
Thanks !
Move this code NestedScrollView nestedScrollView; to the top, and reference it in your onCreateView() method. Like this:
nestedScrollView = (NestedScrollView) view.findViewById(R.id.bottom_sheet);. Now you can use it in any method in the fragment including your onMarkerClick().
You're getting the NPE error because your code is telling the Dalvik Machine that it should look for NestedScrollView in a null view NestedScrollView nestedScrollView= null.
Hope it helps.
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 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
in my NavigationDrawerFragment.java
i have this code
expListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
String header = listDataHeader.get(groupPosition);
Category child = listDataChild.get(header).get(childPosition);
// child.name to get the name
// child.id to get the id
//Toast.makeText(getActivity(),"ChildNme: "+child.name+" ChildId: "+child.id, Toast.LENGTH_SHORT).show();
selectItem(1);
return false;
}
});
after i click the child, i set selectItem to 1
the selectItem(1) will go to MainActivity.java
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getFragmentManager();
// NEW STUFF
if(position == 1){
fragmentManager.beginTransaction()
.replace(R.id.container, CategoryFragment.newInstance())
.commit();
}
}
my question is how to pass the child.name and child.id from NavigationDrawerFragment.java to MainActivity.java then pass to CategoryFragment?
or any other solution to pass the child.name and child.id to CategoryFragment.
COMPLETE CODE
NavigationDrawerFragment.java
package com.example.administrator.mosbeau;
import android.app.FragmentManager;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Fragment used for managing interactions for and presentation of a navigation drawer.
* See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction">
* design guidelines</a> for a complete explanation of the behaviors implemented here.
*/
public class NavigationDrawerFragment extends Fragment {
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
/**
* Per the design guidelines, you should show the drawer on launch until the user manually
* expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
String myJSON;
private static final String TAG_RESULTS="result";
private static final String TAG_ID = "categories_id";
private static final String TAG_NAME = "categories_name";
JSONArray categories = null;
public NavigationDrawerFragment() {
}
Boolean InternetAvailable = false;
Seocnd detectconnection;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
// Select either the default item (0) or the last selected item.
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Indicate that this fragment would like to influence the set of actions in the action bar.
setHasOptionsMenu(true);
}
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<Category>> listDataChild;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View fragmentView = inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
/*mDrawerListView = (ListView) fragmentView.findViewById(R.id.listView);
//mDrawerListView = (ListView) inflater.inflate(
//R.layout.fragment_navigation_drawer, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
new String[]{
getString(R.string.title_home),
getString(R.string.title_category),
getString(R.string.title_myaccount),
getString(R.string.title_referafriend),
getString(R.string.title_about),
getString(R.string.title_privacypocity),
getString(R.string.title_shippingterms),
getString(R.string.title_contactus),
}));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);*/
// get the listview
expListView = (ExpandableListView) fragmentView.findViewById(R.id.lvExp);
// preparing list data
//prepareListData();
detectconnection = new Seocnd(getActivity());
InternetAvailable = detectconnection.InternetConnecting();
if (InternetAvailable) {
getData();
} else {
selectItem(100);
}
return fragmentView;
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://joehamirbalabadan.com/android/android/categories.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
prepareListData();
listAdapter = new ExpandableListAdapter(getActivity(), listDataHeader, listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
// Listview Group click listener
expListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
/*Toast.makeText(getActivity(),
"Group Clicked " + listDataHeader.get(groupPosition),
Toast.LENGTH_SHORT).show();*/
if(groupPosition == 1){
return false;
} else {
selectItem(groupPosition);
return true;
}
}
});
// Listview on child click listener
expListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
// TODO Auto-generated method stub
String header = listDataHeader.get(groupPosition);
Category child = listDataChild.get(header).get(childPosition);
// child.name to get the name
// child.id to get the id
Toast.makeText(getActivity(),"ChildNme: "+child.name+" ChildId: "+child.id, Toast.LENGTH_SHORT).show();
//selectItem(1);
return false;
}
});
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
protected void prepareListData(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
categories = jsonObj.getJSONArray(TAG_RESULTS);
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<Category>>();
// Adding group data
listDataHeader.add("HOME");
listDataHeader.add("CATEGORY");
listDataHeader.add("MY ACCOUNT");
listDataHeader.add("REFER A FRIEND");
listDataHeader.add("ABOUT");
listDataHeader.add("PRIVACY POLICY");
listDataHeader.add("SHIPPING TERMS");
listDataHeader.add("CONTACT US");
List<Category> CATEGORY = new ArrayList<Category>();
for(int i=0;i<categories.length();i++){
JSONObject c = categories.getJSONObject(i);
Category category = new Category();
category.name = c.getString(TAG_NAME);
category.id = c.getString(TAG_ID);
CATEGORY.add(category);
}
listDataChild.put(listDataHeader.get(1), CATEGORY); // Header, Child data
} catch (JSONException e) {
e.printStackTrace();
}
}
/*
* Preparing the list data
*/
/*private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding group data
listDataHeader.add("HOME");
listDataHeader.add("CATEGORY");
listDataHeader.add("MY ACCOUNT");
listDataHeader.add("REFER A FRIEND");
listDataHeader.add("ABOUT");
listDataHeader.add("PRIVACY POLICY");
listDataHeader.add("SHIPPING TERMS");
listDataHeader.add("CONTACT US");
// Adding child data
List<String> CATEGORY = new ArrayList<String>();
CATEGORY.add("Category 1");
CATEGORY.add("Category 2");
CATEGORY.add("Category 3");
CATEGORY.add("Category 4");
CATEGORY.add("Category 5");
listDataChild.put(listDataHeader.get(1), CATEGORY); // Header, Child data
}*/
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* #param fragmentId The android:id of this fragment in its activity's layout.
* #param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
// The user manually opened the drawer; store this flag to prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.global, menu);
showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if (item.getItemId() == R.id.action_example) {
Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(R.string.app_name);
}
private ActionBar getActionBar() {
return ((ActionBarActivity) getActivity()).getSupportActionBar();
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
public static interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
}
MainActivity.java
package com.example.administrator.mosbeau;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* 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;
Boolean InternetAvailable = false;
Seocnd detectconnection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
detectconnection = new Seocnd(this);
InternetAvailable = detectconnection.InternetConnecting();
if (InternetAvailable) {
} else {
NointernetFragment fragment = new NointernetFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getFragmentManager();
// NEW STUFF
if(position == 0){
fragmentManager.beginTransaction()
.replace(R.id.container, HomeFragment.newInstance())
.commit();
}
else if (position == 1){
fragmentManager.beginTransaction()
.replace(R.id.container, CategoryFragment.newInstance())
.commit();
}
else if (position == 2){
fragmentManager.beginTransaction()
.replace(R.id.container, AccountFragment.newInstance())
.commit();
}
else if (position == 3){
fragmentManager.beginTransaction()
.replace(R.id.container, ReferFragment.newInstance())
.commit();
}
else if (position == 4){
fragmentManager.beginTransaction()
.replace(R.id.container, AboutFragment.newInstance())
.commit();
}
else if (position == 5){
fragmentManager.beginTransaction()
.replace(R.id.container, PolicyFragment.newInstance())
.commit();
}
else if (position == 6){
fragmentManager.beginTransaction()
.replace(R.id.container, TermsFragment.newInstance())
.commit();
}
else if (position == 7){
fragmentManager.beginTransaction()
.replace(R.id.container, ContactusFragment.newInstance())
.commit();
}
else if (position == 100){
fragmentManager.beginTransaction()
.replace(R.id.container, NointernetFragment.newInstance())
.commit();
}
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_home);
break;
case 2:
mTitle = getString(R.string.title_category);
break;
case 3:
mTitle = getString(R.string.title_login);
break;
case 4:
mTitle = getString(R.string.title_register);
break;
case 5:
mTitle = getString(R.string.title_myaccount);
break;
case 6:
mTitle = getString(R.string.title_referafriend);
break;
case 7:
mTitle = getString(R.string.title_about);
break;
case 8:
mTitle = getString(R.string.title_privacypocity);
break;
case 9:
mTitle = getString(R.string.title_shippingterms);
break;
case 10:
mTitle = getString(R.string.title_contactus);
break;
case 100:
mTitle = getString(R.string.title_nointernet);
break;
}
}
#SuppressWarnings("deprecation")
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#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();
//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";
/**
* 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));
}
}
}
CategoryFragment.java
package com.example.administrator.mosbeau;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
/**
* Created by Administrator on 9/18/2015.
*/
public class CategoryFragment extends Fragment {
public static CategoryFragment newInstance() {
CategoryFragment fragment = new CategoryFragment();
return fragment;
}
public CategoryFragment () {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.categorylayout, container, false);
getActivity().invalidateOptionsMenu();
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(2);
}
}
update your selectitem() and onNavigationDrawerItemSelected methods to accept two more arguments i.e child.id and child.name
private void selectItem(int position,String id,String name) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position,id,name);
}
}
pass child.id and child.name in selectItem() method so which in turn will call onNavigationDrawerItemSelected() method implemented in MainActivity.
Now in MainActivity, pass the values to the fragment using Bundle
here
fragmentManager.beginTransaction()
.replace(R.id.container, CategoryFragment.newInstance(id,name))
.commit();
you will also need to update to CategoryFragment.newInstance(String,String) to accept the arguments
Updating code to 'setText' in 'edittext'
In your 'CategoryFragment' 'newInstance' method pass data in bundle like below
CategoryFragment categoryfragment = new CategoryFragment()
Bundle bundle = new Bundle()
bundle.putStringExtra("id",id)
bundle.putStringExtra("name",name)
categoryfragment.setArguements(bundle)
return categoryfragment
Now in onCreateView of Categoryfragment get this data like below
if(getArguments().getExtras != null) {
String catid = getArguments.getStringExtra("id");
String catname = getArguments.getStringExtra("name");
yourEditText.setText(catname);
}
Hope you got my point
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());