how to put listview in viewpager - java

i'm working on simple app , i made a viewpager of 3 views, i need to put listview in the viepager
but the listview won't showup
here's my special class for viewpager
package com.Schoolreporting.androidApp;
import java.util.ArrayList;
import android.content.Context;
import android.location.Address;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MyPagerAdapter extends PagerAdapter {
String Name;
// State number of pages
public int getCount() {
return 4;
}
public void setName(String Name) {
this.Name = Name;
}
// Set each screen's content
#Override
public Object instantiateItem(View container, int position) {
Context context = container.getContext();
LinearLayout layout = new LinearLayout(context);
// Add elements
TextView textItem = new TextView(context);
ListView grades=new ListView(context);
ArrayList<String>names=new ArrayList<String>();
names.add("Adel");
names.add("zetta");
names.add("Pringy");
ArrayAdapter<String> adapter=new ArrayAdapter<String> (context,android.R.layout.simple_list_item_1,names);
grades.setAdapter(adapter);
switch (position) {
case 0:
Toast.makeText(context,names.get(1),Toast.LENGTH_LONG).show();
textItem.setText(Name + "'s Grades");
grades.setAdapter(adapter);
Toast.makeText(context,names.get(1),Toast.LENGTH_LONG).show();
break;
case 1:
grades.setAdapter(adapter);
textItem.setText(Name + "'s grades");
break;
case 2:
textItem.setText( Name + "'s feedback");
break;
case 3:
textItem.setText( Name + "'s school");
break;
}
layout.addView(textItem);
((ViewPager) container).addView(layout, 0); // This is the line I
// added
return layout;
}
#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;
}
}

You can do so using the following code:
Context context;
List<View> viewList;
public MyPagerAdapter(Context context) {
this.context = context;
viewList = new ArrayList<View>();
LayoutInflater inflater = LayoutInflater.from(context);
View pg1 = inflater.inflate(R.layout.pg1_layout, null);
View pg2 = inflater.inflate(R.layout.pg2_layout, null);
View pg3 = inflater.inflate(R.layout.pg3_layout, null);
viewList.add(pg1);
viewList.add(pg2);
viewList.add(pg3);
}

Related

How can I pass a created array from Custom adapter class to other class?

I'm trying to pass a String list from my custom array class to another class, but for some reason when I try to access the list, it always seems empty.
Here is my Custom Adapter class:
import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class CustomAdapter extends ArrayAdapter {
private final List<Model> orders;
private final Context context;
boolean checkAll_flag = false;
boolean checkItem_flag = false;
public List<String> selectedItems = new ArrayList<>();
public CustomAdapter(#NonNull Context context, List<Model> orders) {
super(context, R.layout.company_list_order, orders);
this.context = context;
this.orders = orders;
}
static class ViewHolder {
protected TextView orderText;
protected CheckBox checkOrder;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
ViewHolder viewHolder;
selectedItems = new ArrayList<>();
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.company_list_order, parent, false);
viewHolder = new ViewHolder();
viewHolder.orderText = (TextView) convertView.findViewById(R.id.textViewList);
viewHolder.checkOrder = (CheckBox) convertView.findViewById(R.id.listCheckBox);
viewHolder.checkOrder.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag();
orders.get(getPosition).setSelected(buttonView.isChecked());
if (orders.get(getPosition).isSelected()) {
selectedItems.add(orders.get(getPosition).getName());
Log.d("Add", "Item added: " + orders.get(getPosition).getName());
Log.d("Size", "Selected items " + selectedItems.size());
} else {
selectedItems.remove(orders.get(getPosition).getName());
Log.d("Remove", "Item removed: " + orders.get(getPosition).getName());
Log.d("Size", "Selected items " + selectedItems.size());
}
}
});
convertView.setTag(viewHolder);
convertView.setTag(R.id.textViewList, viewHolder.orderText);
convertView.setTag(R.id.listCheckBox, viewHolder.checkOrder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.checkOrder.setTag(position);
viewHolder.orderText.setText(orders.get(position).getName());
viewHolder.checkOrder.setChecked(orders.get(position).isSelected());
return convertView;
}
public List<String> getListItems() {
return selectedItems;
}
}
At the bottom I have the method returning the list. How should I access this in another class?
Probably because you create a new ArrayList everytime getView() is called, which is called a lot. And when you call the method getListItems() the method getView() is called before due to scrolling the listview or something. Remove the line
selectedItems = new ArrayList<>();
from getView() method.
Another option is to make a class with static variables to hold the value during the applications lifetime
public class GlobalVars {
public static List<String> selectedItems;
}

When I search listview item and then click desire item, it does open first position of List View

I have Searchable country ListView. When I click Country List Item without search, it's works properly. but when I type Brazil in search box and click Brazil, then open Country_Details.Java Activity and pass Afganistan details.
when I type Brazil in Search box and click Brazil, I want ot pass Brazil details in WebView.
Full Source Code : https://drive.google.com/open?id=0B46bPR7LKLjpZFRhcV9DdmIweTQ
Here My Code.
package com.nasir.search;
import java.util.ArrayList;
import java.util.Arrays;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class Search_Country extends ListActivity {
private EditText SearchText;
private ListView ListText;
private String[] Number_List = { "Afghanistan", "Albania", "Algeria", "Brazil"};
private ArrayList<String> array_sort;
int textlength = 0;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.search_country);
SearchText = (EditText) findViewById(R.id.listview_search);
ListText = (ListView) findViewById(android.R.id.list);
array_sort = new ArrayList<String>(Arrays.asList(Number_List));
setListAdapter(new bsAdapter(this));
SearchText.addTextChangedListener(new TextWatcher()
{
public void afterTextChanged(Editable s)
{
}
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
public void onTextChanged(CharSequence s, int start, int before, int count)
{
textlength = SearchText.getText().length();
array_sort.clear();
for (int i = 0; i < Number_List.length; i++)
{
if (textlength <= Number_List[i].length())
{
if(Number_List[i].toUpperCase().contains(SearchText.getText().toString().toUpperCase().trim()))
{
array_sort.add(Number_List[i]);
}
}
}
AppendList(array_sort);
}
});
ListText.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch( position )
{
case 0: Intent intent = new Intent(Search_Country.this, Country_Details.class);
intent.putExtra("header", getString(R.string.html_afganistan));
startActivity(intent);
break;
case 1: Intent intent1 = new Intent(Search_Country.this, Country_Details.class);
intent1.putExtra("header", getString(R.string.html_albenia));
startActivity(intent1);
break;
case 2: Intent intent2 = new Intent(Search_Country.this, Country_Details.class);
intent2.putExtra("header", getString(R.string.html_algeria));
startActivity(intent2);
break;
case 3: Intent intent3 = new Intent(Search_Country.this, Country_Details.class);
intent3.putExtra("header", getString(R.string.html_brazil));
startActivity(intent3);
break;
}
}
});
}
public void AppendList(ArrayList<String> str)
{
setListAdapter(new bsAdapter(this));
}
public class bsAdapter extends BaseAdapter
{
Activity cntx;
public bsAdapter(Activity context)
{
this.cntx = context;
}
public int getCount()
{
return array_sort.size();
}
public Object getItem(int position)
{
return array_sort.get(position);
}
public long getItemId(int position)
{
return array_sort.size();
}
public View getView(final int position, View convertView, ViewGroup parent)
{
View row = null;
LayoutInflater inflater = cntx.getLayoutInflater();
row = inflater.inflate(R.layout.search_country_listview, null);
TextView tv = (TextView) row.findViewById(R.id.listview_seacrh_text);
tv.setText(array_sort.get(position));
return row;
}
}
}
Problem is here, you are call webview on static position, instead you call accordingly your array list
Like below.
if( array_list.get(position).equals("Afghanistan")){
Intent intent = new Intent(Search_Country.this, Country_Details.class); intent.putExtra("header", getString(R.string.html_afganistan)); startActivity(intent);
}

Method requires object and finds object from extended class

I want to create fragments in my Android app activity which I can swipe through. More specifically those fragments contain images and I want to swipe through those.
Now to accomplish this I make use of the FragmentPagerAdapter. The problem I have now is that one of my methods in a class which extends FragmentPagerAdaptor requires a Fragment object to be returned but according to the compiler it finds a different object.
This is strange, because the object I return is from a class which extends Fragment and therefore it should work in my opinion.
The problematic method is getItem(int position) in the SlidesPageAdaptor class and the error is
Incompatible types
Required: android.support.v4.app.Fragment
Found: ourpackagename.fragment_slides
SlidesPageAdaptor.java
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class SlidesPageAdaptor extends FragmentPagerAdapter {
String[] devices;
String[] deviceDescription;
public SlidesPageAdaptor(FragmentManager fm, Context context) {
super(fm);
Resources resources = context.getResources();
devices = resources.getStringArray(R.array.devices);
deviceDescription = resources.getStringArray(R.array.device_description);
}
#Override
public Fragment getItem(int position) {
Bundle bundle = new Bundle();
bundle.putString(fragment_slides.DescriptionKey, deviceDescription[position]);
bundle.putInt(fragment_slides.ImageIDKey, getImageID(position));
fragment_slides fragmentSlide = new fragment_slides();
fragmentSlide.setArguments(bundle);
return fragmentSlide;
}
private int getImageID(int position) {
int id = 0;
switch (position)
{
case 0:
id = R.drawable.abc_btn_check_material;
break;
case 1:
id = R.drawable.abc_ab_share_pack_mtrl_alpha;
break;
case 2:
id = R.drawable.abc_btn_radio_material;
break;
}
return id;
}
#Override
public CharSequence getPageTitle(int position) {
return devices[position];
}
#Override
public int getCount() {
return devices.length;
}
}
And the fragment_slides.class (I know the name is bad, but not important now):
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
public class fragment_slides extends Fragment {
public static final String ImageIDKey = "imagekey";
public static final String DescriptionKey = "descriptionkey";
public fragment_slides() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_slides_images, container, false);
Bundle bundle = getArguments();
if(bundle != null)
{
int imageID = bundle.getInt(ImageIDKey);
String description = bundle.getString(DescriptionKey);
setValues(view, imageID, description);
}
return view;
//return inflater.inflate(R.layout.fragment_slides_images, container, false);
}
private void setValues(View view, int imageID, String description) {
ImageView imageview = (ImageView) view.findViewById(R.id.imageViewSlide);
imageview.setImageResource(imageID);
TextView textView = (TextView) view.findViewById(R.id.tvSlideTest);
textView.setText(description);
}
}
I don't think other activities/classes are required but I can provide them if needed.
In fragment_slides.class you should import android.support.v4.app.Fragment, not android.app.Fragment.
The problem is here:
fragment_slides fragmentSlide = new fragment_slides();
fragmentSlide.setArguments(bundle);
Since you're declaring a fragment_slides object rather than a Fragment object, the compiler thinks it isn't a Fragment. Try this instead:
Fragment fragmentSlide = new fragment_slides();
fragmentSlide.setArguments(bundle);

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

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();
});
}

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