Java 使用ViewPager从单独的占位符片段更新Textview
我正在开发一个播客应用程序,我现在有两个页面。收听页面和播客列表页面。我将我的MainActivity与我的object和singleton类放在这个问题的底部 所以我的问题是,当我从第二页(播客列表)导航回第一页(正在播放)时,很快就会添加一个媒体播放器 从第2页移到第1页的代码为:Java 使用ViewPager从单独的占位符片段更新Textview,java,android,android-fragments,Java,Android,Android Fragments,我正在开发一个播客应用程序,我现在有两个页面。收听页面和播客列表页面。我将我的MainActivity与我的object和singleton类放在这个问题的底部 所以我的问题是,当我从第二页(播客列表)导航回第一页(正在播放)时,很快就会添加一个媒体播放器 从第2页移到第1页的代码为: mViewPager.setCurrentItem(0, true); // now playing 但是当我在上面的陈述之后直接调用类似的东西时: home_title.setText(app.getCur
mViewPager.setCurrentItem(0, true); // now playing
但是当我在上面的陈述之后直接调用类似的东西时:
home_title.setText(app.getCurrentPodcast().getTitle());
我得到一个NullPointerException
我对如何从使用标准ViewPager对象的占位符类中的另一个片段更新TextView感到困惑。我希望能够从另一个片段或线程更新home\u标题
,但我不知道如何更新。帮忙
播客对象:
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>
//=========================================================================================
}
包对象;
/**
*XmlPodcastObject.java
*
*此对象用于处理Prindle站点上播客中的XML内容
*
*@作者亚历山大·米勒,2016年
*/
公共类XmlPodcastObject{
私有字符串标题;
私有字符串podcastUrl;
私有字符串;
私有字符串内容;
私有字符串摘要;
流的私有字符串时间;
/**
*XmlPodcastObject
*
*XmlPodcastObject包含应用程序上流式播客的所有信息。
*@param titl播客的字符串标题
*@param imageUr播客的字符串图像url
*@param storyUr播客故事的字符串url
*@param conten字符串解释播客的所有内容
*@param summar String内容的breif摘要
*@param timeOfStrea播客字符串的持续时间为HH:mm:ss
*/
公共XmlPodcastObject(字符串标题、字符串图像、字符串故事、字符串内容、字符串总和、字符串时间)
{
this.title=titl;
this.podcastUrl=imageUr;
this.storyUrl=storyUr;
这个。内容=内容;
this.summary=summar;
this.timeOfStream=timeOfStrea;
}
公共XmlPodcastObject()
{
}
//=========================================================================================
//
//=========================================================================================
公共字符串getTitle(){
返回标题;
}
公共无效集合标题(字符串标题){
this.title=标题;
}
公共字符串getPodcastUrl(){
返回podcastUrl;
}
公共void setPodcastUrl(字符串imageUrl){
this.podcastUrl=imageUrl;
}
公共字符串getStoryUrl(){
返回故事URL;
}
公共void setStoryUrl(字符串storyUrl){
this.storyUrl=storyUrl;
}
公共字符串getContent(){
返回内容;
}
公共void setContent(字符串内容){
this.content=内容;
}
公共字符串getSummary(){
返回摘要;
}
公共void集合摘要(字符串摘要){
this.summary=摘要;
}
公共字符串getTimeOfStream(){
流的返回时间;
}
public void setTimeOfStream(字符串timeOfStream){
this.timeOfStream=流的时间;
}
//=========================================================================================
//
//=========================================================================================
}
单身人士:
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;
}
}
package-Utils;
导入java.util.ArrayList;
导入Objects.XmlPodcastObject;
/**
*由depauw于2015年3月12日创建。
*/
公共类应用程序{
私有ArrayList podcastArray;
私有XmlPodcast对象currentPodcast;
私有静态应用程序ourInstance=新应用程序();
公共静态应用程序getInstance(){
回归自然状态;
}
公共应用程序(){
}
公共ArrayList getPodcastArray(){
返回podcast数组;
}
public int getpodcastaraysize(){
试一试{
返回podcastary.size();
}
捕获(NullPointerException e)
{
返回0;
}
}
公共void setPodcastArray(ArrayList podcastArray){
this.podcastary=podcastary;
}
公共XmlPodcastObject getCurrentPodcast(){
返回当前播客;
}
公共void setCurrentPodcast(XmlPodcastObject currentPodcast){
this.currentPodcast=currentPodcast;
}
}
主要活动:
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();
}
}
}
}
}
教育包,教育包,检查伦理;
导入android.content.Context;
导入android.graphics.Color;
导入android.net.ConnectivityManager;
导入android.net.NetworkInfo;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.support.design.widget.FloatingActionButton;
导入android.support.design.widget.Snackbar;
导入android.support.v4.app.Fragment;
导入android.support.v4.app.FragmentManager;
导入android.support.v4.app.FragmentPagerAdapter;
导入android.support.v4.view.ViewPager;
导入android.support.v4.widget.swiperFreshLayout;
导入android.support.v7.app.AppActivity;
导入android.support.v7.widget.Toolbar;
导入android.util.Log;
导入android.view.LayoutInflater;
导入android.view.Menu;
导入android.view.MenuItem;
导入android.view.view;
导入android.view.ViewGroup;
导入android.widget.AdapterView;
导入android.widget.ListView;
导入android.widget.TextView;
导入android.widget.Toast;
导入org.w3c.dom.Document;
导入org.w3c.dom.Element;
导入org.w3c.dom.NodeList;
导入java.util.ArrayList;
导入Objects.XmlPodcastObject;
导入Utils.App;
导入Utils.PodcastListArrayAdapter;
导入Utils.XMLParser;
/*
*-hambuger图标无滑动功能。
*-将设置移动到新活动,通过菜单选项访问
*-为缓存添加单例类
*-每天一次通知新RSS源对象
*/
公共类MainActivity扩展了AppCompatActivity{
私有静态布尔developerMode=false;
/**
*{@li
mViewPager.setCurrentItem(0, true);
mViewPager.setCurrentItem(0, true);
mSectionsPagerAdapter.getItem(0).home_title.setText(app.getCurrentPodcast().getTitle());