How do I get a videoView to play inside a fragment? - java

I'm very new to fragments and I'm attempting to load a videoView into a fragment . I have my layout files laid out correctly (as I can swipe among images just fine), but I'm unsure of how to load a videoView into a fragment. My code for my activities is as follows:
package com.example.PLS;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.VideoView;
public class CustomPagerAdapter extends PagerAdapter
{
public Object instantiateItem(View collection, int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int resId = 0;
switch (position) {
case 0: {
resId = R.layout.page1;
break;
}
case 1: {
resId = R.layout.page2;
break;
}
case 2: {
resId = R.layout.page3;
break;
}
}
View view = inflater.inflate(resId, null);
((ViewPager) collection).addView(view, 0);
return view;
}
#Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
#Override
public Parcelable saveState() {
return null;
}
#Override
public int getCount() {
return 3;
}
}
package com.example.PLS;
import android.app.Fragment;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.widget.VideoView;
public class MyActivity extends FragmentActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create and set adapter
CustomPagerAdapter adapter = new CustomPagerAdapter();
ViewPager myPager = (ViewPager) findViewById(R.id.customviewpager);
myPager.setAdapter(adapter);
myPager.setCurrentItem(0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
I'm not sure where or how to place the code that tells the videoView to play a video in page1 for example. Where would I place that and how would it look?

A bit offtopic:
Are you sure, that you are using Fragments and not just Views? As far as I can see, you add and remove Views.
Or do you do something within the layout files? If so, could you provide the xml layout resources?
See can i use view pager with views (not with fragments)
For your question:
After you call addView, you could do something like to following (or add that to a button listener):
String videoUri = getVideoUriForPosition(position);
// TODO check if videoUri is not null or something
mPlayerView = (VideoView) mView.findViewById(R.id.video_player);
mPlayerView.requestFocus();
if(mPlayerView == null) {
Log.e(TAG, "Video view null");
} else {
mPlayerView.setVideoURI(Uri.parse(videoUri));
mPlayerView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mPlayerView.start();
});
}

Related

FragmentViewPagerAdapter not calling getItem after screen rotation

I have a custom viewPagerAdapter in this activity, when the first launch of the activity (When the main activity starts it with the intent) the pager displays the fragments correctly, but when I rotate the device, the recipe is got from the savedInstantState, and the adapter is started, but the fragments are not displayed and the getItem method doesn't get callled!
Here's the code for the Activity:
package com.ameer.bake.activities;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.ViewGroup;
import com.ameer.bake.Constants;
import com.ameer.bake.fragments.IngredientsFragment;
import com.ameer.bake.fragments.StepDetailsFragment;
import com.ameer.bake.fragments.StepsFragment;
import com.ameer.bake.R;
import com.ameer.bake.models.Recipe;
import com.ameer.bake.models.Step;
import com.google.gson.Gson;
import com.ogaclejapan.smarttablayout.SmartTabLayout;
public class DetailsActivity extends AppCompatActivity implements StepsFragment.StepCallback{
private Recipe recipe;
private IngredientsFragment ingredientsFragment;
private StepsFragment stepsFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (savedInstanceState != null){
recipe = new Gson().fromJson(savedInstanceState.getString(Constants.RECIPE), Recipe.class);
setupViewPager();
} else if (getIntent().hasExtra(Constants.CURRENT_RECIPE_KEY) ) {
Gson gson = new Gson();
recipe = gson.fromJson(getIntent().getStringExtra(Constants.CURRENT_RECIPE_KEY), Recipe.class);
setTitle(recipe.getName());
setupViewPager();
}
}
#Override
public void onStepClicked(Step step) {
Intent intent = new Intent(DetailsActivity.this, StepActivity.class);
intent.putExtra(Constants.STEP_KEY, new Gson().toJson(step));
startActivity(intent);
}
private class RecipePagerAdapter extends FragmentPagerAdapter {
private static final int NUM_ITEMS = 2;
private final String[] titles = new String[]{
getString(R.string.ingredients), getString(R.string.steps)};
private RecipePagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
if (ingredientsFragment == null && stepsFragment == null) {
ingredientsFragment = new IngredientsFragment();
ingredientsFragment.setIngredients(recipe.getIngredients());
stepsFragment = new StepsFragment();
stepsFragment.setSteps(recipe.getSteps());
stepsFragment.setCallback(DetailsActivity.this);
}
}
// Returns total number of pages
#Override
public int getCount() {
return NUM_ITEMS;
}
// Returns the fragment to display for that page
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return ingredientsFragment;
case 1:
return stepsFragment;
default:
return null;
}
}
// Returns the page title for the top indicator
#Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home){
NavUtils.navigateUpFromSameTask(this);
}
return super.onOptionsItemSelected(item);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString(Constants.RECIPE, new Gson().toJson(recipe));
super.onSaveInstanceState(savedInstanceState);
}
private void setupViewPager(){
ViewPager vpPager = (ViewPager) findViewById(R.id.vpPager);
FragmentPagerAdapter pagerAdapter = new RecipePagerAdapter(getSupportFragmentManager());
vpPager.setAdapter(pagerAdapter);
SmartTabLayout viewPagerTab = (SmartTabLayout) findViewById(R.id.viewpager_tab);
viewPagerTab.setViewPager(vpPager);
}
}
Switch to a FragmentStatePagerAdapter rather than using FragmentPagerAdapter. Also use getChildFragmentManager() instead of getSupportFragmentManager()
The solution was as Pedro Varela mentioned in the comments:
"Hope this works. Add setRetainInstance(true); in onCreate of your internal fragments of the view pager "Control whether a fragment instance is retained across Activity re-creation (such as from a configuration change). This can only be used with fragments not in the back stack. If set, the fragment lifecycle will be slightly different when an activity is recreated""
Thanks

Fragments won't show up in activity extending ActionBarActivity

I have a main activity extending ActionBarActivity. In my activity i create a fragment which isn't showing up. I modified the main activity to extend FragmentActivity and in this case the fragment is showing up. Why isn't the fragment showing up when my activity extends ActionBarActivity? I know that ActionBarActivity extends FragmentActivity so in theory ActionBarActivity should support fragments.
Edit: I resolved it. I wouldn't set any content view on my activity. Now that i set it it works when i extend ActionBarActivity. Still is weird that even if i don't set it, when i extend FragmentActivity it works.
This is my main activity code:
package com.example.yamba;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
//import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
public class StatusActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState == null)
{
StatusFragment fragment = new StatusFragment();
FragmentTransaction fr = getSupportFragmentManager().beginTransaction();
fr.add(android.R.id.content, fragment);
fr.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.status, 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);
}
}
This is my fragment code:
package com.example.yamba;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Toast;
import android.os.AsyncTask;
import android.text.TextWatcher;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.support.v4.app.Fragment;
import com.marakana.android.yamba.clientlib.YambaClient;
import com.marakana.android.yamba.clientlib.YambaClientException;
public class StatusFragment extends Fragment implements OnClickListener
{
private static final String TAG = "StatusFragment";
private EditText editStatus;
private Button buttonTweet;
private TextView textCount;
private int defaultColor;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.activity_fragment, container, false);
editStatus = (EditText) view.findViewById (R.id.editStatus);
buttonTweet = (Button) view.findViewById (R.id.buttonTweet);
textCount = (TextView) view.findViewById (R.id.textCount);
buttonTweet.setOnClickListener(this);
defaultColor = textCount.getTextColors().getDefaultColor();
editStatus.addTextChangedListener(new TextWatcher()
{
public void afterTextChanged (Editable s)
{
int count = 140 - editStatus.length();
textCount.setText(Integer.toString(count));
textCount.setTextColor(Color.GREEN);
if(count<20 && count >= 10)
textCount.setTextColor(Color.YELLOW);
else if (count<10)
textCount.setTextColor(Color.RED);
else
textCount.setTextColor(defaultColor);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged (CharSequence s, int start, int b, int c){}
});
return view;
}
public void onClick(View view)
{
String status = editStatus.getText().toString();
Log.d(TAG, "onClicked with status: " + status);
new PostTask().execute(status);
editStatus.getText().clear();
}
private final class PostTask extends AsyncTask<String, Void, String>
{
protected String doInBackground(String... params)
{
YambaClient yambaCloud = new YambaClient("student", "password");
try
{
yambaCloud.postStatus(params[0]);
return "Succesfuly posted!";
}
catch (YambaClientException e)
{
e.printStackTrace();
return "Failed to post to yamba sevice!";
}
}
#Override
protected void onPostExecute (String result)
{
super.onPostExecute(result);
Toast.makeText(StatusFragment.this.getActivity(), result, Toast.LENGTH_LONG).show();
}
}
}
You are calling the FragmentManager method add into the wrong container. The id you provide must reference to a View (usually a layout) that is part of your activity's layout. So android.R.id.content is surely wrong, look into your activity xml layout and find the correct id (maybe is R.id.content (without android) ? )
It appears to be a bug. As a workaround you could try to add fragment inside a post command. It did the trick for me.
new Handler().post(new Runnable() {
#Override
public void run() {
StatusFragment fragment = new StatusFragment();
FragmentTransaction fr = getSupportFragmentManager().beginTransaction();
fr.add(android.R.id.content, fragment);
fr.commit();
}
});

Is it possible to share the image located in drawable folder on social platform in viewpager ? (One user says he is not sure, How about you )

I have created viewpager app that is suppose to display images located in the drawable folder. I read android official guide and changed my code ,but it is not working for me. Any help will be appreciated....The user should be able to share the image located in drawable folder ..they like on various platforms according to the app downloaded in their phones.. My question is it possible ?. If yes, please..please.. provide some code..
Following are my codes...
Mainactivity.java
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ShareActionProvider;
public class MainActivity extends Activity {
MediaPlayer oursong;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oursong = MediaPlayer.create(MainActivity.this, R.raw.a);
oursong.start ();
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImageAdapter adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
}
private ShareActionProvider mShareActionProvider;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate menu resource file.
getMenuInflater().inflate(R.menu.activity_main, menu);
// Locate MenuItem with ShareActionProvider
MenuItem item = menu.findItem(R.id.menu_item_share);
// Fetch and store ShareActionProvider
mShareActionProvider = (ShareActionProvider) item.getActionProvider();
// Return true to display menu
return true;
}
// Call to update the share intent
private void setShareIntent(Intent shareIntent) {
if (mShareActionProvider != null) {
mShareActionProvider.setShareIntent(shareIntent);
}
}
#Override
protected void onPause(){
super.onPause();
oursong.release();
}
}
imageadapter.java
import java.io.IOException;
import android.app.WallpaperManager;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class ImageAdapter extends PagerAdapter {
Context context;
private final int[] GalImages = new int[] {
R.drawable.one,
R.drawable.two,
R.drawable.three
};
ImageAdapter(Context context){
this.context=context;
}
#Override
public int getCount() {
return GalImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(R.dimen.padding_small);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setImageResource(GalImages[position]);
imageView.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
WallpaperManager myWallpaperManager = WallpaperManager.getInstance(context);
try {
myWallpaperManager.setResource(GalImages[position]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
I am new to android programming so..please provide some explanation along with the code..if possible..thanks..
The user should be able to share the image they like on various
platforms according to the app downloaded in their phones
Yes, of course it is possible.
You have to use Intents to do that. I am not sure if one can send the images from the drawable folder, never tried that. However, if you want to let people share the images from the gallery or something:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/*");
Uri uri = Uri.parse(pathToImage);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(shareIntent),"Share Via...")
What this is doing is that it is representing the intention of your application that it wants to send an image.

Unable to launch app - java.lang.NullPointerException [duplicate]

This question already has answers here:
NullPointerException accessing views in onCreate()
(13 answers)
Closed 8 years ago.
I'm having problems launching my app (crashes), while there is no errors in code.
This happend after i converted code of List View activity to List Fragment...
My main activity:
package com.example.eronetmarket;
import com.preporuceno_app.AppAdapter;
import android.R.drawable;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.itemmenu, menu);
return true;
}
ViewPager viewPager=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager);
final ActionBar actionBar=getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.RED));
//actionBar.setDisplayShowHomeEnabled(false);
addTabs(actionBar);
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i2) {
Log.d("VIVZ","onPageScrolled "+i+" "+v+" "+i2);
}
#Override
public void onPageSelected(int i) {
actionBar.setSelectedNavigationItem(i);
Log.d("VIVZ","onPageSelected "+i);
}
#Override
public void onPageScrollStateChanged(int i) {
if(i==ViewPager.SCROLL_STATE_IDLE)
Log.d("VIVZ","onPageScrollStateChanged scroll state idle "+i);
if(i==ViewPager.SCROLL_STATE_DRAGGING)
Log.d("VIVZ","onPageScrollStateChanged scroll state dragging "+i);
if(i==ViewPager.SCROLL_STATE_SETTLING)
Log.d("VIVZ","onPageScrollStateChanged scroll state settling "+i);
}
});
}
private void addTabs(ActionBar actionBar)
{
ActionBar.Tab tab1=actionBar.newTab();
tab1.setText("PREPORUČENO");
tab1.setTabListener(this);
ActionBar.Tab tab2=actionBar.newTab();
tab2.setText("NAJPOPULARNIJE");
tab2.setTabListener(this);
ActionBar.Tab tab3=actionBar.newTab();
tab3.setText("KATEGORIJE");
tab3.setTabListener(this);
actionBar.addTab(tab1);
actionBar.addTab(tab2);
actionBar.addTab(tab3);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
// Log.d("VIVZ","onTabSelected "+tab.getText());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
// Log.d("VIVZ","onTabUnselected "+tab.getText());
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
// Log.d("VIVZ","onTabReselected "+tab.getText());
}
}
class MyAdapter extends FragmentStatePagerAdapter
{
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment=null;
if(i==0)
{
fragment=new FragmentA();
}
if(i==1)
{
fragment=new Preporuceno();
}
if(i==2)
{
fragment=new FragmentC();
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
}
And my fragment list:
package com.example.eronetmarket;
import java.io.FileNotFoundException;
import android.content.Context;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class Preporuceno extends ListFragment {
private AppAdapter mAdapter;
private ListView siteList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.i("mobAppModel", "OnCreate()");
View rootView = inflater.inflate(R.layout.activity_preporuceno, container, false);
siteList = (ListView) getActivity().findViewById(R.id.listView1);
siteList.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View v, int pos,long id) {
String url = mAdapter.getItem(pos).getstoreURL();
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
if(isNetworkAvailable()){
Log.i("mobAppModel", "starting download Task");
AppDownloadTask download = new AppDownloadTask();
download.execute();
}else{
mAdapter = new AppAdapter(getActivity().getApplicationContext(), -1, XMLsourcePullParser.getmobAppModel(getActivity()));
siteList.setAdapter(mAdapter);
}
return rootView;
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
private class AppDownloadTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... arg0) {
//Download the file
try {
Downloader.DownloadFromUrl("http://minores.info/joomla30/stacksites.xml", getActivity().openFileOutput("XMLsource.xml", Context.MODE_PRIVATE));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result){
//setup our Adapter and set it to the ListView.
mAdapter = new AppAdapter(getActivity().getApplicationContext(), -1, XMLsourcePullParser.getmobAppModel(getActivity()));
siteList.setAdapter(mAdapter);
Log.i("mobAppModel", "adapter size = "+ mAdapter.getCount());
}
}
}
Here is my LogCat messages:
In line 38 where LogCat shows error, I have this line public void onItemClick(AdapterView<?> parent, View v, int pos,long id) {
I don't understand where I went wrong?
Change this
siteList = (ListView) getActivity().findViewById(R.id.listView1);
to
siteList = (ListView) rootView.findViewById(R.id.listView1);
The view belongs to the inflated layout and you need to use the view object to initialize views.
java.lang.RuntimeException: Your content must have a ListView whose
id attribute is 'android.R.id.list'
ListActivity or ListFragment will have listview which occuppies the entire screen. If you want to have other views in the layout then your layout must have listview with id andorid.R.id.list
http://developer.android.com/reference/android/app/ListFragment.html
QUoting docs
ListFragment has a default layout that consists of a single list view.
However, if you desire, you can customize the fragment layout by
returning your own view hierarchy from onCreateView(LayoutInflater,
ViewGroup, Bundle). To do this, your view hierarchy must contain a
ListView object with the id "#android:id/list" (or list if it's in
code)

Inflating Views and Objects Android

I have a PagerAdapter with two views. Right now I am calling populateList() from the xml by attaching a android:onClick="populateList()" to a button. If I try to call the populateList() from within the Main activity it creates a NullPointerException on my ListView. How do I inflate my view/ListView so that I can use it within the Main activity?
package com.itoxygen.publicsafety;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
public class Main extends Activity {
/** Called when the activity is first created. */
EditText alarmLabel;
ArrayList<String> item = new ArrayList<String>();
Dialog alarmDialog;
ArrayAdapter<String> listAdapter;
ListView list;
private List<String> path = null;
private String root;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
root = Environment.getExternalStorageDirectory().getPath(); //gets the root path of SD card
MyPagerAdapter adapter = new MyPagerAdapter();
ViewPager myPager = (ViewPager) findViewById(R.id.threepageviewer);
myPager.setAdapter(adapter);
myPager.setCurrentItem(0);
}
}
public void populateList(View v) {
list.setAdapter(listAdapter);
}
////////////////////////////////////////SWIPE NAVIGATION STUFF///////////////////////////////////////////////////////////////
/**
*
*/
private class MyPagerAdapter extends PagerAdapter {
/**
* Returns how many pages on the main Activity
*/
public int getCount() {
return 2; //increment this if adding pages
}
public Object instantiateItem(View collection, int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
/*
* Add your layouts here
*/
int resId = 0;
switch (position) {
case 0:
resId = R.layout.activity_main_list;
break;
case 1:
resId = R.layout.activity_main_tile;
break;
}
View view = inflater.inflate(resId, null);
((ViewPager) collection).addView(view, 0);
list = (ListView)findViewById(R.id.list);
listAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, item);
return view;
}
public void destroyItem(View arg0, int arg1, Object arg2) { ((ViewPager) arg0).removeView((View) arg2); }
public void finishUpdate(View arg0) { }
public boolean isViewFromObject(View arg0, Object arg1) { return arg0 == ((View) arg1); }
public void restoreState(Parcelable arg0, ClassLoader arg1) { }
public Parcelable saveState() { return null; }
public void startUpdate(View arg0) { }
}
}
In list.setAdapter(listAdapter); list will be null unless instantiateItem is called first. Move your assignment of list into onCreate()

Categories