I have three classes here: Ijob, Tabbed_Activity and PlaceholderFragment. I want to pass the strings created in the Ijob class to my PlaceholderFragment onCreateView to show them as a custom page. I am yet to create a second and third fragment. Ijob is a list of jobs. Tabbed_Activity is the manager class of the fragments. PlaceholderFragment is one of the fragments. As you can see, I have tried bundle, intent and getActivity.. but none of them seems to work. I have also tried getting the data from Ijob to Tabbed_Activity first, then to PlaceholderFragment. Please help.
Ijob.java
package com.example.administrator.signin;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class Ijob extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
// private static String url = "http://0.0.00.00:xxxxx/Transporter/fetch_ffa_insp_emp.jsp?ecd=5d573aecfdc5e7a5";
// JSON Node names
private static final String TAG_CON_NO = "CONSUMER_NO";
private static final String TAG_MET_NO = "METER_NO";
private static final String TAG_REC_ON = "RECEIVED_ON";
private static final String TAG_CON_NAME = "CON_NAME";
//private static final String TAG_CON_CAT = "CON_CAT";
private static final String TAG_MET_RAT = "MET_RAT";
private static final String TAG_CON_ADD = "CON_ADD";
//private static final String TAG_CON_ACC_ADD = "CON_ACC_ADD";
private static final String TAG_COM_RSN = "COM_RSN";
public static final String TAG_M_REF = "M_REF";
private static final String TAG_M_DATE = "M_DATE";
// //private static final String TAG_CON_CAT = " ";
private static final String TAG_PREV_DATA = "PREV_DATA";
private static final String TAG_TELE_NO = "TELE_NO";
private static final String TAG_IE_DT_N_PRSNT_PREV_RDG = "IE_DT_N_PRSNT_PREV_RDG";
private static final String TAG_LCC_LRO_ROM = "LCC_LRO_ROM";
// Hashmap for ListView
ArrayList<HashMap<String, String>> jobList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ijob);
jobList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String CONSUMER_NO = ((TextView) view.findViewById(R.id.CON_NO))
.getText().toString();
String METER_NO = ((TextView) view.findViewById(R.id.MET_NO))
.getText().toString();
String MET_RAT = ((TextView) view.findViewById(R.id.MET_RAT))
.getText().toString();
String REC_ON = ((TextView) view.findViewById(R.id.REC_ON))
.getText().toString();
String CON_NAME = ((TextView) view.findViewById(R.id.CON_NAME))
.getText().toString();
String CON_ADD = ((TextView) view.findViewById(R.id.CON_ADD))
.getText().toString();
String COM_RSN = ((TextView) view.findViewById(R.id.COM_RSN))
.getText().toString();
String M_REF = ((TextView) view.findViewById(R.id.M_REF))
.getText().toString();
String M_DATE = ((TextView) view.findViewById(R.id.M_DATE))
.getText().toString();
String PREV_DATA = ((TextView) view.findViewById(R.id.PREV_DATA))
.getText().toString();
String TELE_NO = ((TextView) view.findViewById(R.id.TELE_NO))
.getText().toString();
String IE_DT_N_PRSNT_PREV_RDG = ((TextView) view.findViewById(R.id.IE_DT_N_PRSNT_PREV_RDG))
.getText().toString();
String LCC_LRO_ROM = ((TextView) view.findViewById(R.id.LCC_LRO_ROM))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(), Tabbed_Activity.class);
// Bundle bundle= new Bundle();
// bundle.putString(TAG_CON_NO, CONSUMER_NO);
// bundle.putString(TAG_MET_NO, METER_NO);
// bundle.putString(TAG_MET_RAT, MET_RAT);
// bundle.putString(TAG_REC_ON, REC_ON);
// bundle.putString(TAG_CON_NAME, CON_NAME);
// bundle.putString(TAG_CON_ADD, CON_ADD);
// bundle.putString(TAG_COM_RSN, COM_RSN);
// bundle.putString(TAG_M_REF, M_REF);
// bundle.putString(TAG_M_DATE, M_DATE);
// bundle.putString(TAG_PREV_DATA, PREV_DATA);
// bundle.putString(TAG_TELE_NO, TELE_NO);
// bundle.putString(TAG_IE_DT_N_PRSNT_PREV_RDG, IE_DT_N_PRSNT_PREV_RDG);
// bundle.putString(TAG_LCC_LRO_ROM, LCC_LRO_ROM);
// PlaceholderFragment argumentFragment = new PlaceholderFragment();//Get Fragment Instance
// argumentFragment.setArguments(bundle);//Finally set argument bundle to fragment */
// in.putExtra(TAG_CON_NO, CONSUMER_NO);
// in.putExtra(TAG_MET_NO, METER_NO);
// in.putExtra(TAG_MET_RAT, MET_RAT);
// in.putExtra(TAG_REC_ON, REC_ON);
// in.putExtra(TAG_CON_NAME, CON_NAME);
// in.putExtra(TAG_CON_ADD, CON_ADD);
// in.putExtra(TAG_COM_RSN, COM_RSN);
in.putExtra(TAG_M_REF, M_REF);
// in.putExtra(TAG_M_DATE, M_DATE);
// in.putExtra(TAG_PREV_DATA, PREV_DATA);
// in.putExtra(TAG_TELE_NO, TELE_NO);
// in.putExtra(TAG_IE_DT_N_PRSNT_PREV_RDG, IE_DT_N_PRSNT_PREV_RDG);
// in.putExtra(TAG_LCC_LRO_ROM, LCC_LRO_ROM); */
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(Ijob.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String aid = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
String url = "http://00.00.00.00:00000/Transporter/fetch_ffa_insp_emp_1.jsp?ecd=" + aid;
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
// JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray jobs = new JSONArray(jsonStr);
// Getting JSON Array node
// jobs = jsonObj.getJSONArray("");
// looping through All Contacts
for (int i = 0; i < jobs.length(); i++) {
JSONObject c = jobs.getJSONObject(i);
String CON_NO = c.getString(TAG_CON_NO);// +" - "+c.getString(TAG_CON_CAT);
String MET_NO = c.getString(TAG_MET_NO);
String MET_RAT = c.getString(TAG_MET_RAT);
String REC_ON = c.getString(TAG_REC_ON);
String CON_NAME = (i + 1) + " . " + c.getString(TAG_CON_NAME);
String CON_ADD = c.getString(TAG_CON_ADD); //+" "+c.getString(TAG_CON_ACC_ADD);
String COM_RSN = c.getString(TAG_COM_RSN);
String M_REF = c.getString(TAG_M_REF);
String M_DATE = c.getString(TAG_M_DATE);
String PREV_DATA = c.getString(TAG_PREV_DATA);
String TELE_NO = c.getString(TAG_TELE_NO);
String IE_DT_N_PRSNT_PREV_RDG = c.getString(TAG_IE_DT_N_PRSNT_PREV_RDG);
String LCC_LRO_ROM = c.getString(TAG_LCC_LRO_ROM);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_CON_NO, CON_NO);
contact.put(TAG_MET_NO, MET_NO);
contact.put(TAG_MET_RAT, MET_RAT);
contact.put(TAG_REC_ON, REC_ON);
contact.put(TAG_CON_NAME, CON_NAME);
contact.put(TAG_CON_ADD, CON_ADD);
contact.put(TAG_COM_RSN, COM_RSN);
contact.put(TAG_M_REF, M_REF);
contact.put(TAG_M_DATE, M_DATE);
contact.put(TAG_PREV_DATA, PREV_DATA);
contact.put(TAG_TELE_NO, TELE_NO);
contact.put(TAG_IE_DT_N_PRSNT_PREV_RDG, IE_DT_N_PRSNT_PREV_RDG);
contact.put(TAG_LCC_LRO_ROM, LCC_LRO_ROM);
// adding contact to contact list
jobList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
Ijob.this, jobList,
R.layout.list_item, new String[]{TAG_CON_NO, TAG_MET_NO, TAG_MET_RAT,
TAG_REC_ON, TAG_CON_NAME, TAG_CON_ADD, TAG_COM_RSN, TAG_M_REF, TAG_M_DATE, TAG_PREV_DATA, TAG_TELE_NO, TAG_IE_DT_N_PRSNT_PREV_RDG, TAG_LCC_LRO_ROM}, new int[]{R.id.CON_NO,
R.id.MET_NO, R.id.MET_RAT, R.id.REC_ON, R.id.CON_NAME, R.id.CON_ADD, R.id.COM_RSN, R.id.M_REF, R.id.M_DATE, R.id.PREV_DATA, R.id.TELE_NO, R.id.IE_DT_N_PRSNT_PREV_RDG, R.id.LCC_LRO_ROM});
setListAdapter(adapter);
}
}
}
Tabbed_Activity.java
package com.example.administrator.signin;
import android.content.Intent;
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 Tabbed_Activity extends AppCompatActivity {
public static final String TAG_M_REF = "M_REF";
/**
* 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_tabbed);
Intent in = getIntent();
String MET_REF = in.getStringExtra(TAG_M_REF);
Bundle bundle = new Bundle();
bundle.putString("edttext", MET_REF);
PlaceholderFragment argumentFragment = new PlaceholderFragment();//Get Fragment Instance
argumentFragment.setArguments(bundle);//Finally set argument bundle to fragment */
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// 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_tabbed_, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position);
}
#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;
}
}
}
PlaceholderFragment.java
package com.example.administrator.signin;
/**
* Created by Administrator on 8/26/2016.
*/
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
/**
* A placeholder fragment containing a simple view.
*/
public 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.placeholder_1, container, false);
String strtext = getArguments().getString("edttext");
TextView textView = (TextView) rootView.findViewById(R.id.m_ref);
textView.setText(strtext);
return rootView;
}
}
It seems to be your are not using the placeholder fragment that is created in activity oncreate method no where else. You set bundle only here. PlaceHolderFragments created in viewpager dont have bundle. You have to set bundle in viewpager.
Related
I'm trying to populate 3 ListFragments that are in a Tabbed ViewPager Layout. (Using one of the templates in Android Studio.)
I have been able to successfully put items into the SQLite DB, but I'm having a hard time populating the ListView(s). It would be easy if things weren't static, but the static-ness simply adds to the complexity.
package com.example.listapp;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ListFragment;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import static com.example.listapp.ItemData.Items.ORDERB;
import static com.example.listapp.ItemData.Items.TABLE_NAME;
import static com.example.listapp.ItemData.Items.TYPE;
import static com.example.listapp.ItemData.Items.LIST_TEXT;
public class MainActivity extends AppCompatActivity {
private ItemData ItemsDb;
String listText = null;
public static String[] FROM = { LIST_TEXT };
public static int[] TO = { R.id.list_text };
public static final Uri CONTENT_URI = Uri.parse("content://"
+ "com.example.listapp" + "/" + TABLE_NAME);
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ItemsDb = new ListData(getApplicationContext());
Intent saveIntent = getIntent();
listText = saveIntent.getStringExtra(ItemCreate.EXTRA_MESSAGE);
if (rlistText != null) {
SQLiteDatabase db = ItemsDb.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ORDERB, System.currentTimeMillis());
values.put(ITEM_TEXT, listText);
db.insertOrThrow(TABLE_NAME, null, values);
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
public void createItem(View view) {
Intent intent = new Intent(this, ItemCreate.class);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "List1";
case 1:
return "List2";
case 2:
return "List3";
}
return null;
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends ListFragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Cursor cursor = getActivity().getContentResolver().query(CONTENT_URI, FROM, null, null, "_ID DESC");
ListView listItems = getListView();
ListAdapter adapter = new SimpleCursorAdapter(getContext(), R.layout.list_item, cursor, FROM, TO, 0);
listItems.setAdapter(adapter);
}
}
}
The adapter does get properly set, but I get the following error when I run the code:
E/ActivityThread: Failed to find provider info for com.example.listapp
What am I doing wrong?
I am developing a podcast app and I have two pages right now. A listening page and a list of podcasts page. I placed my MainActivity at the bottom of this question with my object and singleton classes.
So my problem is when I navigate from the second page (the list of podcasts) back to the first page (Now Playing) where there will be a media player added shortly.
The code to move from Page 2 to Page 1 is:
mViewPager.setCurrentItem(0, true); // now playing
but when I call something like this directly after the above statement:
home_title.setText(app.getCurrentPodcast().getTitle());
I get a NullPointerException.
I'm confused on how to update a TextView from another fragment within a PlaceHolder class which uses a standard ViewPager object. I want to be able to update the home_title from another fragment or thread but I don't know how. Help?
Podcast Object:
package Objects;
/**
* XmlPodcastObject.java
*
* This object is designed to handle the XML content from the podcasts on the Prindle Site
*
* #author Alexander Miller, 2016
*/
public class XmlPodcastObject {
private String title;
private String podcastUrl;
private String storyUrl;
private String content;
private String summary;
private String timeOfStream;
/**
* XmlPodcastObject
*
* XmlPodcastObject contains all of the information for podcasts streamed on the app.
* #param titl String title of the podcast
* #param imageUr String image url of the podcast
* #param storyUr String url for the story of the podcast
* #param conten String all of the content explaining the podcast
* #param summar String a breif summary of the content
* #param timeOfStrea String duration of the podcast in HH:mm:ss
*/
public XmlPodcastObject(String titl, String imageUr, String storyUr, String conten, String summar, String timeOfStrea)
{
this.title = titl;
this.podcastUrl = imageUr;
this.storyUrl = storyUr;
this.content = conten;
this.summary = summar;
this.timeOfStream = timeOfStrea;
}
public XmlPodcastObject()
{
}
//=========================================================================================
// <Getters/Setters>
//=========================================================================================
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPodcastUrl() {
return podcastUrl;
}
public void setPodcastUrl(String imageUrl) {
this.podcastUrl = imageUrl;
}
public String getStoryUrl() {
return storyUrl;
}
public void setStoryUrl(String storyUrl) {
this.storyUrl = storyUrl;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getTimeOfStream() {
return timeOfStream;
}
public void setTimeOfStream(String timeOfStream) {
this.timeOfStream = timeOfStream;
}
//=========================================================================================
// </Getters/Setters>
//=========================================================================================
}
Singleton:
package Utils;
import java.util.ArrayList;
import Objects.XmlPodcastObject;
/**
* Created by depauw on 12/3/15.
*/
public class App {
private ArrayList<XmlPodcastObject> podcastArray;
private XmlPodcastObject currentPodcast;
private static App ourInstance = new App();
public static App getInstance() {
return ourInstance;
}
public App() {
}
public ArrayList<XmlPodcastObject> getPodcastArray() {
return podcastArray;
}
public int getPodcastArraySize(){
try{
return podcastArray.size();
}
catch(NullPointerException e)
{
return 0;
}
}
public void setPodcastArray(ArrayList<XmlPodcastObject> podcastArray) {
this.podcastArray = podcastArray;
}
public XmlPodcastObject getCurrentPodcast() {
return currentPodcast;
}
public void setCurrentPodcast(XmlPodcastObject currentPodcast) {
this.currentPodcast = currentPodcast;
}
}
MainActivity:
package edu.depauw.prindle.examiningethics;
import android.content.Context;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
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.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
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.TextView;
import android.widget.Toast;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import java.util.ArrayList;
import Objects.XmlPodcastObject;
import Utils.App;
import Utils.PodcastListArrayAdapter;
import Utils.XMLParser;
/*
* - hambuger icon no swipe functionality.
* - move settings to new activity, access via menu option
* - add singleton class for cache
* - once a day notification of new RSS feed object
*/
public class MainActivity extends AppCompatActivity {
private static boolean developerMode = false;
/**
* 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 static 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);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Microphone action coming soon.", 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 {#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 2 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getString(R.string.section_podcast_list);
case 1:
return getString(R.string.section_now_playing);
}
return null;
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment{
private ListView Listv;
private SwipeRefreshLayout swipeContainer;
private static App app;
private TextView home_title;
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
private PodcastListArrayAdapter podcastListArrayAdapter;
/**
* 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() {
app = new App();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = null;
if(getArguments().getInt(ARG_SECTION_NUMBER) == 1)
{
rootView = inflater.inflate(R.layout.fragment_home, container, false);
home_title = (TextView) rootView.findViewById(R.id.home_media_layout_track_title);
try
{
home_title.setText(app.getCurrentPodcast().getTitle());
}
catch (NullPointerException e)
{
e.printStackTrace();
}
if (app.getPodcastArraySize() == 0 && isNetworkAvailable())
{
new AsyncTaskParseJson(false).execute();
}
}
else {
rootView = inflater.inflate(R.layout.fragment_podcast_list, container, false);
// UI binding
swipeContainer = (SwipeRefreshLayout) rootView.findViewById(R.id.swipeContainer);
swipeContainer.setColorSchemeColors(Color.rgb(253, 221, 100), Color.rgb(0, 0, 0));
Listv = (ListView) rootView.findViewById(R.id.fragment_podcast_list_podcast_listview);
TextView textView = (TextView) rootView.findViewById(R.id.fragment_podcast_list_section_label);
// Setup refresh listener which triggers new data loading
swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
// Your code to refresh the list here.
// Make sure you call swipeContainer.setRefreshing(false)
// once the network request has completed successfully.
if (isNetworkAvailable()) {
new AsyncTaskParseJson(true).execute();
} else {
Toast.makeText(getActivity(), "No internet connection found.", Toast.LENGTH_LONG).show();
}
}
});
// Onclick listener to return to the listening page.
Listv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mViewPager.setCurrentItem(0, true); // now playing
app.setCurrentPodcast(app.getPodcastArray().get(position));
}
});
if (app.getPodcastArraySize() == 0 && isNetworkAvailable())
{
new AsyncTaskParseJson(true).execute();
}
else if(app.getPodcastArraySize() != 0)
{
podcastListArrayAdapter = new PodcastListArrayAdapter(getActivity(), R.layout.fragment_podcast_list_item, app.getPodcastArray());
}
else
{
// error
Log.d(""+this.getClass().getName(),"Error 1");
}
textView.setText("Podcasts");
}
return rootView;
}
/**
* isNetworkAvailable
*
* #return boolean true is internet is connected or connecting. False if off or none found.
*/
private boolean isNetworkAvailable()
{
ConnectivityManager connectivityManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
/**
* AsyncTaskParseJson
*
* This asynchronous task downloads all of the podcasts available and
* returns a ListView compatible set of content.
*/
public class AsyncTaskParseJson extends AsyncTask<String, String, String>
{
ArrayList<XmlPodcastObject> array = new ArrayList<>();
private boolean setToArray;
public AsyncTaskParseJson(boolean setToArray)
{
this.setToArray = setToArray;
}
// All static variables
static final String URL = "http://examiningethics.org/feed/podcast/";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_TITLE = "title";
static final String KEY_LINK = "link";
static final String KEY_DESC = "description";
static final String KEY_ENCLOSURE = "enclosure";
static final String KEY_SUMMARY = "itunes:summary";
static final String KEY_DURATION = "itunes:duration";
#Override
protected void onPreExecute(){}
#Override
protected String doInBackground(String... arg0)
{
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++)
{
Element e = (Element) nl.item(i);
XmlPodcastObject obj = new XmlPodcastObject(parser.getValue(e, KEY_TITLE),
parser.getValue(e, KEY_ENCLOSURE), parser.getValue(e, KEY_LINK),
parser.getValue(e, KEY_DESC), parser.getValue(e, KEY_SUMMARY),
parser.getValue(e, KEY_DURATION));
if(developerMode)
{
Log.d("PodcastActivity ONCLICK", "Title: " + obj.getTitle() + " " +
"Podcast Link: " + obj.getPodcastUrl() + " " +
"Story Link: " + obj.getStoryUrl() + " " +
"Duration: " + obj.getTimeOfStream() + " " +
"Content: " + obj.getContent() + " " +
"Summary: " + obj.getSummary());
}
array.add(obj);
}
return null;
}
#Override
protected void onPostExecute(String strFromDoInBg)
{
app.setPodcastArray(array);
if(setToArray) {
podcastListArrayAdapter = new PodcastListArrayAdapter(getActivity(), R.layout.fragment_podcast_list_item, array);
Listv.setAdapter(podcastListArrayAdapter);
app.setCurrentPodcast(array.get(0));
}
else
{
app.setCurrentPodcast(array.get(0));
home_title.setText(app.getCurrentPodcast().getTitle());
}
try {
if (swipeContainer.isRefreshing()) {
swipeContainer.setRefreshing(false);
}
}catch (NullPointerException e)
{
e.printStackTrace();
}
}
}
}
}
I think, I found an error.
Look into onCreateView. You have if/else there, and only in the first branch home_title is being initialised, not in the second one.
So you have Activity -> ViewPager -> (Page1 - PlaceHolder fragment with home_title initialized) && (Page2 - PlaceHolder fragment without home_title initialized)
You call
mViewPager.setCurrentItem(0, true);
from the second page(fragment). But it knows nothing about home_title! I.e. you're calling not the home_title from the first page, but home_title from the second page (which, again, is not initialized!).
There're multiple possible ways of fixing it.
The simplest for you would be to
Make home_title public (or introduce a getter for it)
Then call it this way:
mViewPager.setCurrentItem(0, true);
mSectionsPagerAdapter.getItem(0).home_title.setText(app.getCurrentPodcast().getTitle());
I.e. explicitly call home_title from the first page.
In this case it'd be over engineering, but you can also think about EventBus as a way to organize cross-fragment collaboration. It'd make it bit cleaner (imho)
And my last 5 cents - you'll make your own life simpler, if you keep different fragments in separate classes. This logic in onCreateView is hardly maintainable.
So as you can see in the onCreate method i call getView on the 0th fragment in the "fragments" list. It returns null. I've tried putting a timer in the code and have it run every second and check if the view is null. And on the second tick of the timer the view is NOT null. Basically
MainActivity.java
package com.axinite.standapp;
import android.graphics.Color;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.EditText;
import android.widget.NumberPicker;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;
public class MainActivity extends AppCompatActivity {
int i = 0;
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
int standUpSeconds = 4000;
List<android.support.v4.app.Fragment> fragments = new Vector<android.support.v4.app.Fragment>();
NumberPicker SUPickerH;
NumberPicker SUPickerM;
NumberPicker SUPickerS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fragments.add(Fragment.instantiate(this, BlankFragment.class.getName()));
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), fragments);
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.setSelectedTabIndicatorColor(Color.WHITE);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
final int[] ICONS = new int[] {
R.drawable.walking,
R.drawable.iris
};
for (int i=0; i < tabLayout.getTabCount(); i++)
{
tabLayout.getTabAt(i).setIcon(getDrawable(ICONS[i]));
}//endfor)
View view = ((BlankFragment) fragments.get(0)).getView();
if(view != null) {
TextView tv = (TextView) view.findViewById(R.id.glupost);
tv.setText("dasdas");
//Toast.makeText(getApplicationContext(), ((Fragment) fragments.get(0)).toString(), Toast.LENGTH_SHORT).show();
}
}
void Setup() {
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
List<Fragment> fragments;
public SectionsPagerAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
// Show 3 total pages.
return fragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return "";
}
}
}
BlankFragment.java
package com.axinite.standapp;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link BlankFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link BlankFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class BlankFragment extends Fragment {
protected View mView;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment BlankFragment.
*/
// TODO: Rename and change types and number of parameters
public static BlankFragment newInstance(String param1, String param2) {
BlankFragment fragment = new BlankFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public BlankFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_blank, container, false);
mView = view;
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}
The typical method for an Activity to communicate with its Fragments is as follows:
MyFragment frag = (MyFragment) getFragmentManager().findFragmentById(R.id.container_of_fragment);
frag.getMyTextView().setText("New text");
or (often preferred IMO)
MyFragment frag = (MyFragment) getFragmentManager().findFragmentByTag("fragment_tag_string_value");
frag.getMyTextView().setText("New text");
This is rendered more difficult with a ViewPager however, as the "id" of the container is the ViewPager itself, which contains multiple fragments. In addition, there isn't an in built adapter mechanism (that I'm aware of) to set tags to fragments.
There are two methods I can think of that circumvent this. First, you can use an EventBus, such as GreenRobot's EventBus, or LocalBroadcastManager from the Android API. GreenRobot's EventBus is also the recommended technique in the answer to this similar question.
An alternative would leverage the fact that a Fragment always has a reference to its host Activity, which means the Fragment could request the text from the Activity via an interface, which returns it to the Fragment:
public class MainActivity implements FragmentOne.Callbacks {
//...
#Override
public String requestTextViewString() {
return "Text to send to Fragment"
}
And inside your hypothetical FragmentOne:
public class FragmentOne extends Fragment {
private Callbacks mCallback;
private TextView mTextView;
public interface Callbacks {
String requestTextViewString();
}
#Override
public void onAttach(Activity activity) {
if (activity instanceof Callbacks) {
mCallback = (Callbacks) activity;
}
}
/*
*Later in your Fragment, when you want to get text from your MainActivity
* i.e. in onCreateView()
*/
mTextView.setText(mCallback.requestTextViewString());
Edit: Also keep in mind that attempting to access your Fragment from onCreate() in your Activity is likely to result in a NullPointerException. This diagram shows both lifecycles alongside each other. This shouldn't be a problem however, as anything required during the "set-up" lifecycle events of the Fragment can just be passed as an argument in the Fragment's newInstance() method:
public class FragmentOne extends Fragment {
private static final String KEY = "text_for_text_view_key";
public static FragmentOne newInstance(String textForTextView) {
Bundle args = new Bundle();
FragmentOne frag = new FragmentOne();
args.putString(KEY, textForTextView);
frag.setArguments(args);
return frag;
}
//And when required...
mTextView.setText(getArguments().getString(KEY));
I have hare one fragment where I try to get my set value from my list, buy it don't find findPreference method , why?
package com.cetabo.trackingpoint;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.Timer;
import java.util.TimerTask;
import com.cetabo.trackingpoint.dummy.DummyContent;
import com.cetabo.trackingpoint.util.DetectionLocation;
import java.util.Date;
/**
* A fragment representing a list of Items.
* <p/>
* Large screen devices (such as tablets) are supported by replacing the ListView
* with a GridView.
* <p/>
* Activities containing this fragment MUST implement the {#link OnFragmentInteractionListener}
* interface.
*/
public class PlacesFragment extends Fragment implements AbsListView.OnItemClickListener {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
/**
* The fragment's ListView/GridView.
*/
private AbsListView mListView;
ImageView imageView;
/**
* The Adapter which will be used to populate the ListView/GridView with
* Views.
*/
private ListAdapter mAdapter;
// TODO: Rename and change types of parameters
public static PlacesFragment newInstance(String param1, String param2) {
PlacesFragment fragment = new PlacesFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public PlacesFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
// TODO: Change Adapter to display your content
// mAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, DummyContent.ITEMS);
}
String[] test ={"test","test"};
String text = "Central Park";
Date data = new Date();
//---HERE IS MY PROBLEM---
ListPreference listPreference = (ListPreference) findPreference("sync_frequency");
//------------------------
// Resources res = getResources();
// String[] time = res.getStringArray(R.array.pref_example_list_values);
// ArrayAdapter<String> adapter = ArrayAdapter.createFromResource(this, R.array.pref_sync_frequency_values, android.R.layout.simple_spinner_item);
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_place, container, false);
Context ctx = view.getContext();
DetectionLocation detectionLocation = new DetectionLocation(ctx);
CustomListAdapter adapter=new CustomListAdapter(getActivity(),test,String.valueOf(detectionLocation.getLongitude()+" "+detectionLocation.getLatitude()),data);
mListView = (AbsListView) view.findViewById(android.R.id.list);
mListView.setAdapter(adapter);
// Set OnItemClickListener so we can be notified on item clicks
mListView.setOnItemClickListener(this);
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// try {
// mListener = (OnFragmentInteractionListener) activity;
// } catch (ClassCastException e) {
// throw new ClassCastException(activity.toString()
// + " must implement OnFragmentInteractionListener");
// }
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (null != mListener) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mListener.onFragmentInteraction(DummyContent.ITEMS.get(position).id);
}
}
/**
* The default content for this Fragment has a TextView that is shown when
* the list is empty. If you would like to change the text, call this method
* to supply the text it should use.
*/
public void setEmptyText(CharSequence emptyText) {
View emptyView = mListView.getEmptyView();
if (emptyView instanceof TextView) {
((TextView) emptyView).setText(emptyText);
}
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(String id);
}
}
Because,
findPreference() is method from PreferenceFragment if you are using API Level 11+ devices. Or / Otherwise, It would be from PreferenceActivity.
For more info look at http://developer.android.com/reference/android/preference/PreferenceActivity.html
You can access preferences from within a fragment by creating a SharedPreference object in your onAttach method.
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(activity);
String myPref = sharedPrefs.getString("sync_frequency", "");
}
I'm developing an android application that currently displays a list of articles in the MainActivity and is working correctly, i want to make the application a little more sophisticated by adding a navigation drawer that contains the articles' categories and a "Home" button above them.
So i started a new project on Android Studio and i selected blank app with Navigation Drawer then i imported my previous app manually into this new project and i renamed my previous MainActivity to HomePage.java, because the MainActivity here is for the Navigation Drawer.
I made many researches and i think that i have to convert my activities into fragments in order to work with Navigation Drawer, but i don't know how.
This is the MainActivity.java:
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.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;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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 = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1); //The Home Button
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
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));
}
}
}
And this is HomePage.java :
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
public class HomePage extends ListActivity {
//Create a progress dialog instance
private ProgressDialog pDialog;
// JSON Node names
private static final String TAG_ARTICLES = "articles";
private static final String TAG_ID = "id";
private static final String TAG_TITLE = "title";
private static final String TAG_TEASER = "teaser";
private static final String TAG_COVER_PHOTO = "cover_photo";
String call_url = "http://www.ana.fm/api/main/?start=0&count=20";
int start_get = 0;
int count_get = 20;
int lastItemIndex = 0;
ListView lv;
//Articles JSONArray
JSONArray articles = null;
//Defining the articles list with type Article
List<Article> articleList;
Button loadMoreButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_page);
articleList = new ArrayList<>();
//Getting the ListView
lv = getListView();
//add the footer before adding the adapter, else the footer will not load!
View footerView = ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.list_footer, null, false);
lv.addFooterView(footerView);
//Add click listener to the load more button
loadMoreButton = (Button) findViewById(R.id.loadMoreBtn);
loadMoreButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
lastItemIndex = lv.getLastVisiblePosition();
start_get = start_get + 20;
call_url = "http://www.ana.fm/api/main/?start=".concat(String.valueOf(start_get)).concat("&count=20");
// Calling async task to get json
new GetArticles().execute();
}
});
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String article_id = ((TextView) view.findViewById(R.id.article_id))
.getText().toString();
// Starting single article activity
Intent in = new Intent(getApplicationContext(),
SingleArticleActivity.class);
in.putExtra(TAG_ID, article_id);
startActivity(in);
}
});
// Calling async task to get json
new GetArticles().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetArticles extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(HomePage.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
//call_url is defined previously
String jsonStr = sh.makeServiceCall(call_url, ServiceHandler.GET);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
articles = jsonObj.getJSONArray(TAG_ARTICLES);
// looping through All Articles
for (int i = 0; i < articles.length(); i++) {
JSONObject c = articles.getJSONObject(i);
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
title = Html.fromHtml(title).toString();
String teaser = c.getString(TAG_TEASER);
teaser = Html.fromHtml(teaser).toString();
String cover_photo = "http://www.ana.fm/med_photos/articles/";
cover_photo = cover_photo.concat(c.getString(TAG_COVER_PHOTO));
//Getting an object from the Article class
Article article = new Article();
//Setting the values to the object's variables
article.setId(id);
article.setTitle(title);
article.setTeaser(teaser);
article.setImageUrl(cover_photo);
// adding article to the article list
articleList.add(article);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
//new GetContacts().execute();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Calling my custom adapter to view the images as well
* */
MyAdapter adapter = new MyAdapter(getApplicationContext(), R.layout.list_item, articleList);
setListAdapter(adapter);
lv.setSelection(lastItemIndex);
}
}
}
Now what i want is to be navigated to the HomePage.java after clicking on the "Home" button on the Navigation Drawer (Side Menu).
Anyone can help ?
I'm new to android but from what i understand from google's official documentation, they are really similar, refer to the documentation here