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.
Related
So I am very new to Android studio. My problem is relatively simple, convert data from a text field into a integer. The goal of that int is to be used in a conditional statement. However I cannot seem to find an answer that works. This is where my code that i'm having problems with is.
public void saveMatchData (MenuItem item) {
//save button in my menu
//creates a toast to notify that it has been pressed
Toast toast = Toast.makeText(getApplicationContext(), "Save button pressed", Toast.LENGTH_SHORT);
toast.show();
// create an EditText for matchNumberInput
EditText matchNumberET = (EditText) findViewById(R.id.matchNumberInput);
//assign value of matchNumberET(Edit Text) to match number
EditText matchNumber = (EditText) matchNumberET.getText();
//attempted to assign to an int
int matchNumberValue = Integer.parseInt(matchNumber);
// error here^^^^^
//same as abover just tried a different way that i read online
EditText teamNumberDT = (EditText) findViewById(R.id.teamNumberInput);
int teamNumber = Integer.parseInt(teamNumberDT.getText().toString());
int i;
//i have an array for matchNumber values and teamNumber values
//they start empty and as of now still are
//
for (i = 0, i <= matchNumberArray.size(), i++);{
if (matchNumberValue == matchNumberArray.get(i)){
// error here^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//I just want to compare the value of i position of the array with the data from textfield
//code to add matchNumber if not already there
}
//both of these different ways to do this give me errors
}
if (teamNumberArray.get(i) == teamNumber) {
//error here^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//code to add teamNumber if not already there
}
Is it a problem with the conversion of the textField to an int or is it the way im using it? Or is it a problem with my array/s?
Here is all of my code. Sorry, it's very sloppy.`
package com.example.garre.frcscouting13;
import android.net.Uri;
import android.support.design.widget.TabLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
List<String> matchNumberArray = new ArrayList<String>();
//String matchNumberArray[] = {};
ArrayAdapter matchNumberAdapter = new ArrayAdapter<String> (this, R.layout.previous_fragment, matchNumberArray);
List<String> teamNumberArray = new ArrayList<String>();
// String teamNumberArray[] = {};
ArrayAdapter teamNumberAdapter = new ArrayAdapter<String>(this, R.layout.previous_fragment, teamNumberArray);
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#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);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
#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. #Override
// Handle item selection
switch (item.getItemId()) {
case R.id.saveMenuItem:
return true;
case R.id.ScreenShotMenuItem:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void openScreenshotToast(MenuItem item) {
Toast toast = Toast.makeText(getApplicationContext(), "Screenshot button pressed", Toast.LENGTH_SHORT);
toast.show();
}
public void saveMatchData (MenuItem item) {
//save button in my menu
//creates a toast to notify that it has been pressed
Toast toast = Toast.makeText(getApplicationContext(), "Save button pressed", Toast.LENGTH_SHORT);
toast.show();
// create an EditText for matchNumberInput
EditText matchNumberET = (EditText) findViewById(R.id.matchNumberInput);
//assign value of matchNumberET(Edit Text) to match number
EditText matchNumber = (EditText) matchNumberET.getText();
//attempted to assign to an int
int matchNumberValue = Integer.parseInt(matchNumber);
//same as abover just tried a different way that i read online
EditText teamNumberDT = (EditText) findViewById(R.id.teamNumberInput);
int teamNumber = Integer.parseInt(teamNumberDT.getText().toString());
int i;
//i have an array for matchNumber values and teamNumber values
//they start empty and as of now still are
//
for (i = 0, i <= matchNumberArray.size(), i++);{
if (matchNumberValue == matchNumberArray.get(i)){
//code to add matchNumber if not already there
}
//both of these different ways to do this give me errors
}
if (teamNumberArray.get(i) == teamNumber) {
//code to add teamNumber if not already there
}
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Main Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (getArguments().getInt(ARG_SECTION_NUMBER) == 1) {
View rootView = inflater.inflate(R.layout.fieldmap_fragment, container, false);
return rootView;
} else if (getArguments().getInt(ARG_SECTION_NUMBER) == 2) {
View rootView = inflater.inflate(R.layout.datainput_fragment, container, false);
return rootView;
} else {
View rootView = inflater.inflate(R.layout.previous_fragment, container, false);
return rootView;
}
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "FieldMap";
case 1:
return "Match Data";
case 2:
return "Previous";
}
return null;
}
}
}
`
Extract your EditText Value like:
EditText matchNumberET = (EditText) findViewById(R.id.matchNumberInput);
int matchNumberValue = Integer.parseInt(matchNumberET.getText().toString());
And as seeing your code, I couldn't find your Intention towards the App. Please go through few tutorials as provided on Google's official site.
I did that for teamNumber. And then did matchnumber different to show that I've tried some different ways. Niether of them work though.
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.
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
What i basically have is a simple android navigation drawer with some fragments , i have a checkbox called from a Fragment placed in the main activity which then when clicked executes a root command that should modify the build.prop file in /system but unfortunately it doesn't seem to work and i get this in the logs -->
D/su (17546): su invoked.
D/su (17546): starting daemon client 10129 10129
D/su (17548): remote pid: 17546
D/su (17548): remote pts_slave:
D/su (17548): waiting for child exit
D/su (17550): su invoked.
D/su (17550): db allowed
D/su (17550): 10129 /system/xbin/su executing 0 /system/bin/sh using binary
/system/bin/sh : sh
D/su (17548): sending code
D/su (17548): child exited
D/su (17546): client exited 0
D/AndroidRuntime(17551):
D/AndroidRuntime(17551): >>>>>> AndroidRuntime START com.android.internal.os.Run
timeInit <<<<<<
D/AndroidRuntime(17551): CheckJNI is OFF
D/AndroidRuntime(17551): Calling main entry com.android.commands.am.Am
here is the code of my Activity (AboutActivity)
package com.adromo.tweaker.activities;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.GravityCompat;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.Toast;
import com.adromo.tweaker.R;
import com.adromo.tweaker.fragments.InitD;
import com.adromo.tweaker.fragments.StartFragment;
import com.adromo.tweaker.widget.CustomDrawerLayout;
import com.ikimuhendis.ldrawer.ActionBarDrawerToggle;
import com.ikimuhendis.ldrawer.DrawerArrowDrawable;
import org.sufficientlysecure.rootcommands.Shell;
import org.sufficientlysecure.rootcommands.command.SimpleCommand;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.TimeoutException;
public class AboutActivity extends FragmentActivity {
public static Context appContext;
//==================================
// Drawer
//==================================
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private ActionBarDrawerToggle mDrawerToggle;
private CustomDrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private ListView mDrawerList;
private DrawerArrowDrawable drawerArrow;
private boolean drawerArrowColor;
private static int DRAWER_MODE = 0;
private SharedPreferences mPreferences;
private static final int MENU_BACK = Menu.FIRST;
String titleString[];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
appContext = getApplicationContext();
setContentView(R.layout.drawer_main);
mDrawerListView = (ListView) findViewById(R.id.dw_navigation_drawer);
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(),
R.layout.drawer_list,
android.R.id.text1,
getTitles()));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
setUpNavigationDrawer(
findViewById(R.id.dw_navigation_drawer),
(CustomDrawerLayout) findViewById(R.id.dw_drawer_layout));
ActionBar ab = getActionBar();
ab.setDisplayHomeAsUpEnabled(true);
ab.setHomeButtonEnabled(true);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
File folder = new File(Environment.getExternalStorageDirectory() + "/Adromo");
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}
CopyAssets();
}
private void CopyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("Files");
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
for(String filename : files) {
System.out.println("File name => "+filename);
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open("Files/"+filename); // if files resides inside the "Files" directory itself
out = new FileOutputStream("/sdcard/Adromo/" + filename );
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(Exception e) {
Log.e("tag", e.getMessage());
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onPause() {
super.onPause();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, MENU_BACK, 0, R.string.toggle_back_cfibers)
.setIcon(R.drawable.ic_back)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
restoreActionBar();
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case MENU_BACK:
onBackPressed();
return true;
default:
return super.onContextItemSelected(item);
}
}
//==================================
// Methods
//==================================
/**
* Users of this fragment must call this method to set up the
* navigation menu_drawer interactions.
*
* #param fragmentContainerView The view of this fragment in its activity's layout.
* #param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUpNavigationDrawer(View fragmentContainerView, CustomDrawerLayout drawerLayout) {
mFragmentContainerView = fragmentContainerView;
mDrawerLayout = drawerLayout;
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
drawerArrow = new DrawerArrowDrawable(this) {
#Override
public boolean isLayoutRtl() {
return false;
}
};
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
drawerArrow, R.string.navigation_drawer_open,
R.string.navigation_drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
mDrawerToggle.setDrawerIndicatorEnabled(true);
if (!mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
selectItem(mCurrentSelectedPosition);
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Restores the action bar after closing the menu_drawer
*/
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setTitle(getTitle());
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.dw_container, PlaceholderFragment.newInstance(getPosition(position)))
.commit();
}
/**
* Depending on if the item is shown or not, it increases
* the position to make the activity load the right fragment.
*
* #param pos The selected position
* #return the modified position
*/
public int getPosition(int pos) {
int position = pos;
switch (DRAWER_MODE) {
default:
case 0:
position = pos;
break;
case 1:
if (pos > 0) position = pos + 1;
break;
case 2:
if (pos > 3) position = pos + 1;
break;
case 3:
if (pos > 0) position = pos + 1;
if (pos > 3) position = pos + 2;
break;
}
return position;
}
/**
* Get a list of titles for the tabstrip to display depending on if the
* voltage control fragment and battery fragment will be displayed. (Depends on the result of
* Helpers.voltageTableExists() & Helpers.showBattery()
*
* #return String[] containing titles
*/
private String[] getTitles() {
String titleString[];
DRAWER_MODE = 0;
titleString = new String[]{
getString(R.string.start_title),
getString(R.string.navdraw_initd),};
return titleString;
}
//==================================
// Internal Classes
//==================================
public static final int FRAGMENT_ID_StartFragment = 0;
public static final int FRAGMENT_ID_InitD = 1;
public static class PlaceholderFragment extends Fragment {
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static Fragment newInstance(int fragmentId) {
Fragment fragment;
switch (fragmentId) {
default:
case FRAGMENT_ID_StartFragment:
fragment = new StartFragment();
break;
case FRAGMENT_ID_InitD:
fragment = new InitD();
break;
}
return fragment;
}
public PlaceholderFragment() {
// intentionally left blank
}
}
// begin initd checkboxes
public void initd1(View view) {
// Is the view now checked?
boolean checked = ((CheckBox) view).isChecked();
// Check which checkbox was clicked
switch(view.getId()) {
case R.id.initd1:
if (checked){
try {
Shell shell = Shell.startRootShell();
SimpleCommand command2 = new SimpleCommand("su -c cp /system/build.prop /system/build.prop.bak");
shell.add(command2).waitForFinish();
shell.close();
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "LOL",
Toast.LENGTH_SHORT).show();
}
// Remove the meat
break;
}
}
}
here is the code of my fragment
/*
* Copyright (C) 2013 Carbon Development
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.adromo.tweaker.fragments;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.adromo.tweaker.R;
public class InitD extends PreferenceFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.initd, container, false);
}
}
the library i am using is called rootcommands (i think this shouldn't matter as every library i try gives me the same exact result)
i am running android lolipop 5.0.1 on an SGS4
Make sure you have mounted /system as read-write.
Run this command for mounting r/w:
mount -o remount,rw /system
And for mounting read-only again do:
mount -o remount,ro /system
Never forget this or you cannot write to /system.
In my android application I have two .xaml layouts like activity_1 and activity_2 and I want to change these layout's activity through 2 swipeable tabs because after that i want to add more tabs: and below is my activity:
package com.example.hakslogin;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.PagerTitleStrip;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Color;
import android.view.View.OnClickListener;
public class LoginSuccess extends ActionBarActivity {
static final String LOG_TAG = "SlidingTabsBasicFragment";
private SlidingTabLayout mSlidingTabLayout;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_success);
Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
mViewPager = (ViewPager) findViewById(R.id.viewpager);
mViewPager.setAdapter(new SamplePagerAdapter());
mSlidingTabLayout = (SlidingTabLayout) findViewById(R.id.sliding_tabs);
mSlidingTabLayout.setViewPager(mViewPager);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login_success, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
class SamplePagerAdapter extends PagerAdapter {
/**
* #return the number of pages to display
*/
#Override
/* public int getCount() { //I am not using this method
return 5;
}*/
/**
* #return true if the value returned from
* {#link #instantiateItem(ViewGroup, int)} is the same object
* as the {#link View} added to the {#link ViewPager}.
*/
#Override
public boolean isViewFromObject(View view, Object o) {
return o == view;
}
#Override
/*public CharSequence getPageTitle(int position) { //I am not using this //method because I am giving name of tabs in SlidingTabLayout.java class
return pageTitle + " " + (position + 1);
}*/
// END_INCLUDE (pageradapter_getpagetitle)
/**
* Instantiate the {#link View} which should be displayed at
* {#code position}. Here we inflate a layout from the apps resources
* and then change the text view to signify the position.
*/
#Override
public Object instantiateItem(ViewGroup container, int position) {
// Inflate a new layout from our resources
View view = getLayoutInflater().inflate(R.layout.activity_login_success,
container, false);
container.addView(view);
// Retrieve a TextView from the inflated View, and update it's text
// --comment by me
//TextView title = (TextView) view.findViewById(R.id.item_title);
//title.setText(String.valueOf(position + 1));
Log.i(LOG_TAG, "instantiateItem() [position: " + position + "]");
return view;
}
/**
* Destroy the item from the {#link ViewPager}. In our case this is
* simply removing the {#link View}.
*/
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
Log.i(LOG_TAG, "destroyItem() [position: " + position + "]");
}
}
}
And I am doing above the same code into my another activity like below:
package com.example.hakslogin;
import com.example.android.common.view.SlidingTabLayout;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Color;
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.View.OnClickListener;
import android.widget.Button;
import android.widget.TableRow;
import android.widget.TextView;
public class AddChildActivity extends ActionBarActivity {
static final String LOG_TAG = "SlidingTabsBasicFragment";
private SlidingTabLayout mSlidingTabLayout;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_child);
Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
mViewPager = (ViewPager) findViewById(R.id.viewpager);
mViewPager.setAdapter(new SamplePagerAdapter());
mSlidingTabLayout = (SlidingTabLayout) findViewById(R.id.sliding_tabs);
mSlidingTabLayout.setViewPager(mViewPager);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.add_child, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
class SamplePagerAdapter extends PagerAdapter {
/*#Override
public int getCount() {
return 5;
}*/
#Override
public boolean isViewFromObject(View view, Object o) {
return o == view;
}
/*#Override
public CharSequence getPageTitle(int position) {
return pageTitle + " " + (position + 1);
}*/
// END_INCLUDE (pageradapter_getpagetitle)
/**
* Instantiate the {#link View} which should be displayed at
* {#code position}. Here we inflate a layout from the apps resources
* and then change the text view to signify the position.
*/
#Override
public Object instantiateItem(ViewGroup container, int position) {
// Inflate a new layout from our resources
View view = getLayoutInflater().inflate(R.layout.activity_add_child,
container, false);
container.addView(view);
// Retrieve a TextView from the inflated View, and update it's text
// --comment by me
//TextView title = (TextView) view.findViewById(R.id.item_title);
//title.setText(String.valueOf(position + 1));
Log.i(LOG_TAG, "instantiateItem() [position: " + position + "]");
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
Log.i(LOG_TAG, "destroyItem() [position: " + position + "]");
}
}
}
and below is SlidingTabLayout.java class:
package com.example.android.common.view;
import com.example.hakslogin.LoginSuccess;
import android.content.Context;
import android.graphics.Typeface;
import android.os.Build;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.TextView;
public class SlidingTabLayout extends HorizontalScrollView {
/**
* Allows complete control over the colors drawn in the tab layout. Set with
* {#link #setCustomTabColorizer(TabColorizer)}.
*/
public interface TabColorizer {
/**
* #return return the color of the indicator used when {#code position} is selected.
*/
int getIndicatorColor(int position);
/**
* #return return the color of the divider drawn to the right of {#code position}.
*/
int getDividerColor(int position);
}
private static final int TITLE_OFFSET_DIPS = 24;
private static final int TAB_VIEW_PADDING_DIPS = 16;
private static final int TAB_VIEW_TEXT_SIZE_SP = 12;
private int mTitleOffset;
private int mTabViewLayoutId;
private int mTabViewTextViewId;
private ViewPager mViewPager;
private ViewPager.OnPageChangeListener mViewPagerPageChangeListener;
String value = "";
private final SlidingTabStrip mTabStrip;
// public SlidingTabLayout() {
// TODO Auto-generated constructor stub
//}
public SlidingTabLayout(Context context) {
this(context, null);
}
public SlidingTabLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SlidingTabLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// Disable the Scroll Bar
setHorizontalScrollBarEnabled(false);
// Make sure that the Tab Strips fills this View
setFillViewport(true);
mTitleOffset = (int) (TITLE_OFFSET_DIPS * getResources().getDisplayMetrics().density);
mTabStrip = new SlidingTabStrip(context);
addView(mTabStrip, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
}
/**
* Set the custom {#link TabColorizer} to be used.
*
* If you only require simple custmisation then you can use
* {#link #setSelectedIndicatorColors(int...)} and {#link #setDividerColors(int...)} to achieve
* similar effects.
*/
public void setCustomTabColorizer(TabColorizer tabColorizer) {
mTabStrip.setCustomTabColorizer(tabColorizer);
}
/**
* Sets the colors to be used for indicating the selected tab. These colors are treated as a
* circular array. Providing one color will mean that all tabs are indicated with the same color.
*/
public void setSelectedIndicatorColors(int... colors) {
mTabStrip.setSelectedIndicatorColors(colors);
}
/**
* Sets the colors to be used for tab dividers. These colors are treated as a circular array.
* Providing one color will mean that all tabs are indicated with the same color.
*/
public void setDividerColors(int... colors) {
mTabStrip.setDividerColors(colors);
}
/**
* Set the {#link ViewPager.OnPageChangeListener}. When using {#link SlidingTabLayout} you are
* required to set any {#link ViewPager.OnPageChangeListener} through this method. This is so
* that the layout can update it's scroll position correctly.
*
* #see ViewPager#setOnPageChangeListener(ViewPager.OnPageChangeListener)
*/
public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) {
mViewPagerPageChangeListener = listener;
}
/**
* Set the custom layout to be inflated for the tab views.
*
* #param layoutResId Layout id to be inflated
* #param textViewId id of the {#link TextView} in the inflated view
*/
public void setCustomTabView(int layoutResId, int textViewId) {
mTabViewLayoutId = layoutResId;
mTabViewTextViewId = textViewId;
}
/**
* Sets the associated view pager. Note that the assumption here is that the pager content
* (number of tabs and tab titles) does not change after this call has been made.
*/
public void setViewPager(ViewPager viewPager) {
mTabStrip.removeAllViews();
mViewPager = viewPager;
if (viewPager != null) {
viewPager.setOnPageChangeListener(new InternalViewPagerListener());
populateTabStrip();
}
}
/**
* Create a default view to be used for tabs. This is called if a custom tab view is not set via
* {#link #setCustomTabView(int, int)}.
*/
protected TextView createDefaultTabView(Context context) {
TextView textView = new TextView(context);
textView.setGravity(Gravity.CENTER);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, TAB_VIEW_TEXT_SIZE_SP);
textView.setTypeface(Typeface.DEFAULT_BOLD);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// If we're running on Honeycomb or newer, then we can use the Theme's
// selectableItemBackground to ensure that the View has a pressed state
TypedValue outValue = new TypedValue();
getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground,
outValue, true);
textView.setBackgroundResource(outValue.resourceId);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
// If we're running on ICS or newer, enable all-caps to match the Action Bar tab style
//textView.setAllCaps(true);
//textView.setAllCaps(true);
}
int padding = (int) (TAB_VIEW_PADDING_DIPS * getResources().getDisplayMetrics().density);
textView.setPadding(padding, padding, padding, padding);
return textView;
}
String names[] = {"Home","Add Child"};//,"Add Item", "Questions", "Answer"};
int len = names.length;
private void populateTabStrip() {
final PagerAdapter adapter = mViewPager.getAdapter();
final View.OnClickListener tabClickListener = new TabClickListener();
for (int i = 0; i < names.length ; i++) {// i++) {;adapter.getCount()
View tabView = null;
TextView tabTitleView = null;
if (mTabViewLayoutId != 0) {
// If there is a custom tab view layout id set, try and inflate it
tabView = LayoutInflater.from(getContext()).inflate(mTabViewLayoutId, mTabStrip,
false);
tabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId);
}
if (tabView == null) {
tabView = createDefaultTabView(getContext());
}
if (tabTitleView == null && TextView.class.isInstance(tabView)) {
tabTitleView = (TextView) tabView;
}
LoginSuccess.pageTitle = names[i].toString();
tabTitleView.setText(names[i].toString());//adapter.getPageTitle(i)
tabView.setOnClickListener(tabClickListener);
mTabStrip.addView(tabView);
}
}
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (mViewPager != null) {
scrollToTab(mViewPager.getCurrentItem(), 0);
}
}
private void scrollToTab(int tabIndex, int positionOffset) {
final int tabStripChildCount = mTabStrip.getChildCount();
if (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) {
return;
}
View selectedChild = mTabStrip.getChildAt(tabIndex);
if (selectedChild != null) {
int targetScrollX = selectedChild.getLeft() + positionOffset;
if (tabIndex > 0 || positionOffset > 0) {
// If we're not at the first child and are mid-scroll, make sure we obey the offset
targetScrollX -= mTitleOffset;
}
scrollTo(targetScrollX, 0);
}
}
private class InternalViewPagerListener implements ViewPager.OnPageChangeListener {
private int mScrollState;
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
int tabStripChildCount = mTabStrip.getChildCount();
if ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) {
return;
}
mTabStrip.onViewPagerPageChanged(position, positionOffset);
View selectedTitle = mTabStrip.getChildAt(position);
int extraOffset = (selectedTitle != null)
? (int) (positionOffset * selectedTitle.getWidth())
: 0;
scrollToTab(position, extraOffset);
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageScrolled(position, positionOffset,
positionOffsetPixels);
}
}
#Override
public void onPageScrollStateChanged(int state) {
mScrollState = state;
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageScrollStateChanged(state);
}
}
#Override
public void onPageSelected(int position) {
if (mScrollState == ViewPager.SCROLL_STATE_IDLE) {
mTabStrip.onViewPagerPageChanged(position, 0f);
scrollToTab(position, 0);
}
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageSelected(position);
}
}
}
private class TabClickListener implements View.OnClickListener {
#Override
public void onClick(View v) {
for (int i = 0; i < mTabStrip.getChildCount(); i++) {
if (v == mTabStrip.getChildAt(i)) {
mViewPager.setCurrentItem(i);
return;
}
}
}
}
}
I am using this link, and its show me two tabs on any first activity but the problem is that its show layout multiple times one on my activity layout and on sliding page layout, Kindly suggest me what can I handle it, waiting for reply Thanks.