Opening new view inside ViewPager - java

Using Devlight NavigationTabBar on my android app. Here's the whole code:
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_horizontal_ntb);
initUI();
}
private void initUI() {
final ViewPager viewPager = (ViewPager) findViewById(R.id.vp_horizontal_ntb);
viewPager.setAdapter(new PagerAdapter() {
#Override
public int getCount() {
return 5;
}
#Override
public boolean isViewFromObject(final View view, final Object object) {
return view.equals(object);
}
#Override
public void destroyItem(final View container, final int position, final Object object) {
((ViewPager) container).removeView((View) object);
}
#Override
public Object instantiateItem(final ViewGroup container, final int position) {
final View viewNews = LayoutInflater.from(
getBaseContext()).inflate(R.layout.item_vp_list, null, false);
final View ViewSol = LayoutInflater.from(
getBaseContext()).inflate(R.layout.activity_sol, null, false);
final View viewProfile = LayoutInflater.from(
getBaseContext()).inflate(R.layout.activity_profile, null, false);
final View viewContact = LayoutInflater.from(
getBaseContext()).inflate(R.layout.activity_contact, null, false);
View finalView = null;
if (position == 0) {
final RecyclerView recyclerView = (RecyclerView) viewNews.findViewById(R.id.rv);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(
getBaseContext(), LinearLayoutManager.VERTICAL, false
)
);
recyclerView.setAdapter(new RecycleAdapter());
container.addView(viewNews);
finalView = viewNews;
} else if (position == 1) {
container.addView(viewSol);
finalView = viewSol;
} else if (position == 2) {
container.addView(viewProfile);
finalView = viewProfile;
} else if (position == 3){
container.addView(viewContact);
finalView = viewContact;
}
return finalView;
}
});
final String[] colors = getResources().getStringArray(R.array.default_preview);
final NavigationTabBar navigationTabBar = (NavigationTabBar) findViewById(R.id.ntb_horizontal);
final ArrayList<NavigationTabBar.Model> models = new ArrayList<>();
models.add(
new NavigationTabBar.Model.Builder(
getResources().getDrawable(R.drawable.ic_library),
Color.parseColor(colors[0]))
.selectedIcon(getResources().getDrawable(R.drawable.ic_library))
.title("News")
.badgeTitle("+10")
.build()
);
models.add(
new NavigationTabBar.Model.Builder(
getResources().getDrawable(R.drawable.ic_error_black_24dp),
Color.parseColor(colors[1]))
// .selectedIcon(getResources().getDrawable(R.drawable.ic_eighth))
.title("Solicitation")
//.badgeTitle("with")
.build()
);
models.add(
new NavigationTabBar.Model.Builder(
getResources().getDrawable(R.drawable.ic_person_black_24dp),
Color.parseColor(colors[3]))
// .selectedIcon(getResources().getDrawable(R.drawable.ic_eighth))
.title("My Account")
//.badgeTitle("icon")
.build()
);
models.add(
new NavigationTabBar.Model.Builder(
getResources().getDrawable(R.drawable.ic_phone_black_24dp),
Color.parseColor(colors[2]))
.selectedIcon(getResources().getDrawable(R.drawable.ic_phone_black_24dp))
.title("Contact")
//.badgeTitle("state")
.build()
);
navigationTabBar.setModels(models);
navigationTabBar.setViewPager(viewPager, 2);
navigationTabBar.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(final int position, final float positionOffset, final int positionOffsetPixels) {
}
#Override
public void onPageSelected(final int position) {
navigationTabBar.getModels().get(position).hideBadge();
}
#Override
public void onPageScrollStateChanged(final int state) {
}
});
navigationTabBar.postDelayed(new Runnable() {
#Override
public void run() {
for (int i = 0; i < navigationTabBar.getModels().size(); i++) {
final NavigationTabBar.Model model = navigationTabBar.getModels().get(i);
navigationTabBar.postDelayed(new Runnable() {
#Override
public void run() {
//model.showBadge();
}
}, i * 100);
}
}
}, 500);
}
As you can see, whenever I choose a tab it opens the view inside the view pager.
However, I have no idea how to open another view when I click on a button. I tried to start a whole new activity with intent but it crashes and it's not really what I want.
What I want is to open the view on the viewpager ViewPager viewPager = (ViewPager) findViewById(R.id.vp_horizontal_ntb);
If I implement this:
public void openNewView(View view) {
//the code to open a view inside the viewpager should go here
}
How can I proceed?

Add a view to your viewPager in the layout that is originally set to Visibility = GONE or Invisible and change it to Visible when you want it to be visible on screen.
https://developer.android.com/reference/android/view/View.html#GONE
Or use a layoutInflater to add a view from another layout to your viewpager
https://developer.android.com/reference/android/view/LayoutInflater.html

To open a new view on click of some button you can do this:
Suppose that you want to have a new view on the first button, then in the method instantiateItem of PagerAdapter you can check if position is 0 or not.
If the position if 0, then you can inflate that layout which you want to display.
something like this:
#Override
public Object instantiateItem(final ViewGroup container, final int position) {
if (position == 0)
{
final View view = LayoutInflater.from(
getBaseContext()).inflate(R.layout.your_layout, null, false);
final TextView txtPage = (TextView) view.findViewById(R.id.txt_vp_item_page);
txtPage.setText(String.format("Page #%d", position));
container.addView(view);
return view;
}
else if (position == 1)
{
final View view = LayoutInflater.from(
getBaseContext()).inflate(R.layout.item_vp, null, false);
final TextView txtPage = (TextView) view.findViewById(R.id.txt_vp_item_page);
txtPage.setText(String.format("Page #%d", position));
container.addView(view);
return view;
}
else
{
final View view = LayoutInflater.from(
getBaseContext()).inflate(R.layout.item_vp, null, false);
final TextView txtPage = (TextView) view.findViewById(R.id.txt_vp_item_page);
txtPage.setText(String.format("Page #%d", position));
container.addView(view);
return view;
}
}
To make your code more modular you can use make your custom fragments and and them in your adapter.
Hope this helps

Related

Listview not behaving well with Folding Cell Library

I have a problem using folding cell library from the RAMOTION
I have implemented everything but I am facing a problem with the list view
I have a list of planets and when user tap on let's say Jupiter the view gets unfolded and more information is visible to the user and when user tap on the same view which is seeing then the view gets folded
Problem
if the user scrolls down the list and then scroll back up and come back up to Jupiter the view remains unfolded and it is happening to all the view.
I appreciate if anyone helps me out
folding state
here
unfolding state
here
AdapterClass
#SuppressWarnings({"WeakerAccess", "unused"})
public class SolarSystemFoldingCellListAdapter extends ArrayAdapter<SolarSystemItemFoldingCell> {
private HashSet<Integer> unfoldedIndexes = new HashSet<>();
private View.OnClickListener defaultRequestBtnClickListener;
private int incomingPosition ;
public SolarSystemFoldingCellListAdapter(Context context, List<SolarSystemItemFoldingCell> objects) {
super(context, 0, objects);
}
#NonNull
#Override
public View getView(int position, View convertView, #NonNull ViewGroup parent) {
// get item for selected view
SolarSystemItemFoldingCell solarSystemItemFoldingCell = getItem(position);
// if cell is exists - reuse it, if not - create the new one from resource
FoldingCell cell = (FoldingCell) convertView;
final ViewHolder viewHolder;
if (cell == null) {
viewHolder = new ViewHolder();
LayoutInflater vi = LayoutInflater.from(getContext());
cell = (FoldingCell) vi.inflate(R.layout.solar_system_folding_cell, parent, false);
// binding view parts to view holder
viewHolder.foldingCell = cell.findViewById(R.id.folding_cell);
viewHolder.relativeLayoutFolded = cell.findViewById(R.id.relativeLayoutFolded);
viewHolder.linearLayoutFolded = cell.findViewById(R.id.linearLayoutFolded);
viewHolder.planetOrStarNameFolded = cell.findViewById(R.id.planetOrStarNameFolded);
viewHolder.mass = cell.findViewById(R.id.mass);
viewHolder.actualMass = cell.findViewById(R.id.actualMass);
viewHolder.distance = cell.findViewById(R.id.distance);
viewHolder.actualDistance = cell.findViewById(R.id.actualDistance);
viewHolder.diameter = cell.findViewById(R.id.diameter);
viewHolder.actualDiameter = cell.findViewById(R.id.actualDiameter);
viewHolder.speed = cell.findViewById(R.id.speed);
viewHolder.actualSpeed = cell.findViewById(R.id.actualSpeed);
viewHolder.moreInfoButton = cell.findViewById(R.id.button);
viewHolder.frameLayoutUnfolded = cell.findViewById(R.id.frameLayoutUnfolded);
viewHolder.planetOrStarNameUnfolded = cell.findViewById(R.id.planetOrStarNameUnfolded);
cell.setTag(viewHolder);
} else {
// for existing cell set valid valid state(without animation)
if (unfoldedIndexes.contains(position)) {
cell.unfold(true);
} else {
cell.fold(true);
}
viewHolder = (ViewHolder) cell.getTag();
}
if (null == solarSystemItemFoldingCell)
return cell;
// bind data from selected element to view through view holder
viewHolder.planetOrStarNameFolded.setText(solarSystemItemFoldingCell.getPlantOrStarNameFolded());
viewHolder.actualMass.setText(solarSystemItemFoldingCell.getActualMass());
viewHolder.actualDistance.setText(solarSystemItemFoldingCell.getActualDistance());
viewHolder.actualDiameter.setText(solarSystemItemFoldingCell.getActualDiameter());
viewHolder.actualSpeed.setText(solarSystemItemFoldingCell.getActualSpeed());
viewHolder.planetOrStarNameUnfolded.setText(String.valueOf(solarSystemItemFoldingCell.getPlanetOrStarNameUnfolded()));
//setting Fonts
viewHolder.planetOrStarNameFolded.setTypeface(App.getAppInstance().getArvoBold());
viewHolder.mass.setTypeface(App.getAppInstance().getArvoBold());
viewHolder.distance.setTypeface(App.getAppInstance().getArvoBold());
viewHolder.diameter.setTypeface(App.getAppInstance().getArvoBold());
viewHolder.speed.setTypeface(App.getAppInstance().getArvoBold());
viewHolder.actualMass.setTypeface(App.getAppInstance().getArvoRegular());
viewHolder.actualDistance.setTypeface(App.getAppInstance().getArvoRegular());
viewHolder.actualDiameter.setTypeface(App.getAppInstance().getArvoRegular());
viewHolder.actualSpeed.setTypeface(App.getAppInstance().getArvoRegular());
viewHolder.moreInfoButton.setTypeface(App.getAppInstance().getArvoRegular());
// set custom btn handler for list item from that item
if (solarSystemItemFoldingCell.getRequestBtnClickListener() != null) {
viewHolder.moreInfoButton.setOnClickListener(solarSystemItemFoldingCell.getRequestBtnClickListener());
} else {
// (optionally) add "default" handler if no handler found in item
viewHolder.moreInfoButton.setOnClickListener(defaultRequestBtnClickListener);
}
viewHolder.relativeLayoutFolded.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "Something gets clicked", Toast.LENGTH_SHORT).show();
viewHolder.foldingCell.fold(false);
registerFold(incomingPosition);
}
});
return cell;
}
// simple methods for register cell state changes
public void registerToggle(int position) {
if (unfoldedIndexes.contains(position)) {
registerFold(position);
incomingPosition = position;
}else
registerUnfold(position);
}
public void registerFold(int position) {
unfoldedIndexes.remove(position);
}
public void registerUnfold(int position) {
unfoldedIndexes.add(position);
}
public View.OnClickListener getDefaultRequestBtnClickListener() {
return defaultRequestBtnClickListener;
}
public void setDefaultRequestBtnClickListener(View.OnClickListener defaultRequestBtnClickListener) {
this.defaultRequestBtnClickListener = defaultRequestBtnClickListener;
}
// View lookup cache
private static class ViewHolder {
RelativeLayout relativeLayoutFolded ;
LinearLayout linearLayoutFolded ;
TextView planetOrStarNameFolded;
TextView mass;
TextView actualMass;
TextView distance;
TextView actualDistance;
TextView diameter;
TextView actualDiameter;
TextView speed;
TextView actualSpeed ;
Button moreInfoButton ;
FrameLayout frameLayoutUnfolded ;
TextView planetOrStarNameUnfolded;
FoldingCell foldingCell ;
}
}
SolarSystemClass
private void listViewIntegration (){
arrayList = addingDataIntoList();
solarSystemFoldingCellListAdapter = new SolarSystemFoldingCellListAdapter(SolarSystem.this , arrayList);
listView.setAdapter(solarSystemFoldingCellListAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int duration = 500; //miliseconds
int offset = 0; //fromListTop
listView.smoothScrollToPositionFromTop(position,offset,duration);
// toggle clicked cell state
((FoldingCell) view).toggle(false);
// register in adapter that state for selected cell is toggled
solarSystemFoldingCellListAdapter.registerToggle(position);
// listView.smoothScrollToPosition(position);
}
});
}

How setText in a Layout from a ViewPager

I try to set a Text in a Layout in a ViewPager, but if i do this there will be thrown a NullPointerException:
private ViewPager viewPager;
private ViewPagerAdapter viewPagerAdapter;
private LinearLayout dotsLayout;
private TextView[] dots;
private int[] layouts;
private Button btnNext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_slider);
viewPager = (ViewPager) findViewById(R.id.view_pager);
dotsLayout = (LinearLayout) findViewById(R.id.layoutDots);
//btnSkip = (Button) findViewById(R.id.btn_skip);
btnNext = (Button) findViewById(R.id.btn_next);
layouts = new int[]{
R.layout.slide_header_bild_text,
R.layout.slide_header_bild_text_2,
R.layout.slide_01_03,
R.layout.slide_01_04,
R.layout.slide_01_05,
R.layout.slide_01_06,
R.layout.startquiz_layout};
//These two lines are the Problem
TextView t1 = (TextView) findViewByID(R.id.header_text);
t1.setText("Test")
// adding bottom dots
addBottomDots(0);
viewPagerAdapter = new ViewPagerAdapter();
viewPager.setAdapter(viewPagerAdapter);
viewPager.addOnPageChangeListener(viewPagerPageChangeListener);
}
public void btnQuizStart(View v){
Intent intent = new Intent(this, Quiz.class);
this.startActivity(intent);
}
public void btnNextClick(View v)
{
// checking for last page
// if last page home screen will be launched
int current = getItem(1);
if (current < layouts.length) {
// move to next screen
viewPager.setCurrentItem(current);
} else {
launchHomeScreen();
}
}
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
addBottomDots(position);
// changing the next button text 'NEXT' / 'GOT IT'
if (position == layouts.length - 1) {
// last page. make button text to GOT IT
btnNext.setText(getString(R.string.start));
} else {
// still pages are left
btnNext.setText(getString(R.string.next));
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
};
private void addBottomDots(int currentPage) {
dots = new TextView[layouts.length];
dotsLayout.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new TextView(this);
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextSize(35);
dots[i].setTextColor(getResources().getColor(R.color.inactive_dots));
dotsLayout.addView(dots[i]);
}
if (dots.length > 0)
dots[currentPage].setTextColor(getResources().getColor(R.color.active_dots));
}
private int getItem(int i) {
return viewPager.getCurrentItem() + i;
}
private void launchHomeScreen() {
startActivity(new Intent(this, MainActivity.class));
finish();
}
public class ViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
public ViewPagerAdapter() {
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(layouts[position], container, false);
container.addView(view);
return view;
}
#Override
public int getCount() {
return layouts.length;
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
I've got the ViewPager which contains seven Pages.
I think the Layout wont be found, so the TextView is Null. I also read that I have to configure the instantiateItem method and to add there the TextView and the setter. Anybody can help?
findViewByID(R.layout.header_text)
TaxtView can't be a layout.
oh this was also a failure but not which I searched for. I had the problem with the viewpager that i didn't got the layout and so the elements of the layout was null. I fixed the instantiateItem Method so any layout will be initiated specific:
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View one = layoutInflater.inflate(R.layout.slide_type_a, container, false);
WebView header_1_a = (WebView) one.findViewById(R.id.header_slide_type_a_1);
loadHTLMContentHeader(getString(R.string.Historie1_header),header_1_a);
ImageView image_1_a = (ImageView) one.findViewById(R.id.image_slide_type_a_1);
image_1_a.setImageResource(R.drawable.picture_kap01_01);
WebView text_1_a = (WebView) one.findViewById(R.id.text_slide_type_a_1);
loadHTLMContentText(getString(R.string.Historie1), text_1_a);
View two = layoutInflater.inflate(R.layout.slide_type_a, container, false);
View three = layoutInflater.inflate(R.layout.slide_type_a, container, false);
View four = layoutInflater.inflate(R.layout.slide_type_b, container, false);
View five = layoutInflater.inflate(R.layout.slide_type_b, container, false);
View six = layoutInflater.inflate(R.layout.slide_type_b, container, false);
View seven = layoutInflater.inflate(R.layout.slide_type_b, container, false);
View eight = layoutInflater.inflate(R.layout.startquiz_layout, container, false);
View viewarr[] = {one, two, three, four, five, six, seven, eight};
container.addView(viewarr[position]);
return viewarr[position];
}
So after initiate the layout, i can get the xml element and change the content of it.

Wrong item position into ListView

I need to open a frameLayout details into a listView, but when I press the buttonDetails, it opens a wrong frameLayout.
here is the code of my adapterView
public class SitesAdapter extends ArrayAdapter<AtlantisSite> {
ImageLoader imageLoader;
DisplayImageOptions options;
FrameLayout frameLayout;
public SitesAdapter(Context ctx, int textViewResourceId, List<AtlantisSite> sites) {
super(ctx, textViewResourceId, sites);
//Setup the ImageLoader, we'll use this to display our images
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(ctx).build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
//Setup options for ImageLoader so it will handle caching for us.
options = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
}
/*
* (non-Javadoc)
* #see android.widget.ArrayAdapter#getView(int, android.view.View, android.view.ViewGroup)
*
* This method is responsible for creating row views out of a AtlantisSite object that can be put
* into our ListView
*/
#Override
public View getView(final int pos, final View convertView, final ViewGroup parent){
RelativeLayout row = (RelativeLayout)convertView;
Log.i("AtlantisSites", "getView pos = " + pos);
//ViewHolder mainViewHolder = null;
final ViewHolder viewHolder;
if(null == row){
//No recycled View, we have to inflate one.
LayoutInflater inflater = (LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = (RelativeLayout)inflater.inflate(R.layout.row_site, null);
viewHolder = new ViewHolder();
viewHolder.btnDownload = (Button) row.findViewById(R.id.btnDownload);
viewHolder.btnDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer pos=(Integer)v.getTag();
Log.i("AtlantisSites", "getView pos = " + pos);
//String url = getItem(pos).getLink();
DownloadZip zipActivity = new DownloadZip();
zipActivity.DownloadFromUrlZip();
//Intent i = new Intent(Intent.ACTION_VIEW);
//i.setData(Uri.parse(url));
//Intent zipActivity = new DownloadZip();
//zipActivity.start...;
//Toast.makeText(getContext(), "Downloading " + pos, Toast.LENGTH_SHORT).show();
}
});
viewHolder.btnDetails = (Button) row.findViewById(R.id.btnDetails);
viewHolder.btnDetails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Integer pos = (Integer) v.getTag();
//Log.i("AtlantisSites", "getView pos = " + pos);
getItemId(pos);
if(frameLayout.getVisibility()==View.GONE){
showFrameLayout();
} else {
hideFrameLayout();
}
}
});
row.setTag(viewHolder);
} else{
viewHolder = (ViewHolder) row.getTag();
}
//Get our View References
final ImageView iconImg = (ImageView)row.findViewById(R.id.iconImg);
TextView nameTxt = (TextView)row.findViewById(R.id.nameTxt);
TextView titleTxt = (TextView)row.findViewById(R.id.titleTxt);
//Button btnDownload = (Button)row.findViewById(R.id.btnDownload);
TextView summaryIta = (TextView)row.findViewById(R.id.textViewSummaryItaRow);
TextView summaryEng = (TextView)row.findViewById(R.id.textViewSummaryEngRow);
TextView priceItaTxt=(TextView)row.findViewById(R.id.txtViewPriceIta);
TextView priceEngTxt=(TextView)row.findViewById(R.id.txtViewPriceEng);
final ProgressBar indicator = (ProgressBar)row.findViewById(R.id.progress);
frameLayout = (FrameLayout)row.findViewById(R.id.frame_layout_listview);
//Set the relavent text in our TextViews
nameTxt.setText(getItem(pos).getName());
titleTxt.setText(getItem(pos).getTitle());
summaryIta.setText(getItem(pos).getSummaryIta());
summaryEng.setText(getItem(pos).getSummaryEng());
viewHolder.btnDetails.setTag(pos);
return row;
}
public class ViewHolder{
Button btnDownload;
Button btnDetails;
}
private void showFrameLayout(){
frameLayout = (FrameLayout) frameLayout.findViewById(R.id.frame_layout_listview);
frameLayout.setVisibility(View.VISIBLE);
}
private void hideFrameLayout(){
frameLayout = (FrameLayout) frameLayout.findViewById(R.id.frame_layout_listview);
frameLayout.setVisibility(View.GONE);
}
}
Something goes wrong with the position.
please help me to find error o solutions.
thanks
in the method showFrameLayout() you dont have any reference to the current frame layout you want to show, remove the methods show/hide frameLayout and inside the listener for the details btn
viewHolder.btnDetails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Integer pos = (Integer) v.getTag();
//Log.i("AtlantisSites", "getView pos = " + pos);
getItemId(pos);
FrameLayout detailsFrame = row.findViewById(R.id.frame_layout_listview);
if(detailsFrame.getVisibility()==View.GONE){
detailsFrame.setVisibility(View.VISIBLE);
} else {
detailsFrame.setVisibility(View.GONE);
}
}
});
As a general suggestion i would put my FrameLayout inside the viewholder, wich is exactly whats for.
I found the solution . I have to declare the Frame Layout final. It works
final FrameLayout detailsFrame = (FrameLayout)row.findViewById(R.id.frame_layout_listview);

list view adapter setting null object on custom dialog

hi friends i had tried to implement list view in the custom dialog and passing data dynamically by using JSON and searched everywhere but don't got any solution i had tried everything from past 3 days and also i don't see any wrong in my code too i had set adapter correctly i am getting this error
Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
public class Cat_comment_adap extends BaseAdapter {
String cid;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
int idddget;
private LayoutInflater inflater;
private List<CurrentList> catlist;
private PopupWindow commentWindow;
ArrayList<CurrentList> commentlist = new ArrayList<CurrentList>();
Activity activity;
public Cat_comment_adap(Activity activity, List<CurrentList> catlist) {
this.activity = activity;
this.catlist = catlist;
}
#Override
public int getCount() {
return catlist.size();
}
#Override
public Object getItem(int i) {
return catlist.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.cat_row, viewGroup, false);
NetworkImageView singleimg = (NetworkImageView) view.findViewById(R.id.singleimg);
final ImageView agree = (ImageView) view.findViewById(R.id.agree);
ImageView commentbox = (ImageView) view.findViewById(R.id.commentbox);
commentbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onShowpopup(view);
Toast.makeText(activity, "Comments Button clicked", Toast.LENGTH_SHORT).show();
}
});
final CurrentList catertlist = catlist.get(i);
singleimg.setImageUrl(catertlist.getCatimg(), imageLoader);
idddget = catertlist.getCcids();
SharedPreferences eveid = activity.getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
cid = eveid.getString("userid", "");
agree.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String url = "http://sampletemplates.net/majority/api.php?action=addVote&question_id=" + idddget + "&user_id=" + cid + "&vote=1&source=android";
Log.d("Vote", "http://sampletemplates.net/majority/api.php?action=addVote&question_id=" + idddget + "&user_id=" + cid + "&vote=1&source=android");
JsonObjectRequest voting = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String votings = response.getString("status");
if (votings.equals("success")) {
agree.setImageResource(R.drawable.agreed);
Toast.makeText(activity, "Voted Successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(activity, "Already Voted", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
AppController.getInstance().addToRequestQueue(voting);
}
});
return view;
}
public void onShowpopup(View v) {
LayoutInflater layoutInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View popupview = layoutInflater.inflate(R.layout.current_comment_dialog, null);
ListView commentsListView = (ListView) v.findViewById(R.id.commentsListView);
// commentAdapter = new comment_adapter(activity, commentlist);
WindowManager wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
commentWindow = new PopupWindow(popupview, width - 50, height - 400, true);
commentWindow.setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.comment_bg));
commentWindow.setFocusable(true);
commentWindow.setOutsideTouchable(true);
commentWindow.showAtLocation(v, Gravity.BOTTOM, 0, 100);
commentsListView.setAdapter(new comment_adapter(activity,commentlist));
commentAdapter.notifyDataSetChanged();
}
Adapter class
public class comment_adapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<CurrentList> commentlist;
public comment_adapter(Activity activity, List<CurrentList> commentlist){
this.activity = activity;
this.commentlist = commentlist;
}
#Override
public int getCount() {
return commentlist.size();
}
#Override
public Object getItem(int i) {
return commentlist.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (inflater == null)
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null)
view = inflater.inflate(R.layout.comment_row, viewGroup, false);
TextView user_name = (TextView) view.findViewById(R.id.user_name);
TextView posttime = (TextView) view.findViewById(R.id.posttime);
TextView comtsdetails = (TextView) view.findViewById(R.id.comtsdetails);
CurrentList listofcomments = commentlist.get(i);
user_name.setText(listofcomments.getEvtusername());
posttime.setText(listofcomments.getTimetaken());
comtsdetails.setText(listofcomments.getEvcomment());
return view;
}
}
here in this class Cat_comment_adap in the method onShowpopup change
View popupview = layoutInflater.inflate(R.layout.current_comment_dialog, null);
ListView commentsListView = (ListView) v.findViewById(R.id.commentsListView);
to
View popupview = layoutInflater.inflate(R.layout.current_comment_dialog, null);
ListView commentsListView = (ListView) popupview.findViewById(R.id.commentsListView);
because your inflating listview from this layout so u have to give the name of inflated layout object there not the parameter of the method
public void onClick(View view) {
onShowpopup(view);
Toast.makeText(activity, "Comments Button clicked", Toast.LENGTH_SHORT).show();
}
Here passed view is not R.layout.cat_row as you think but it's a button that was clicked.
So just use onShowpopup(self.view) and it will work :)
or change to onClick(View clickedButton)

Selected list item background colour unexpectedly reused after list scroll on tablets

For my list view on tablets, I'm trying to get my selected list item selection to keep its state when selected but unfortunately I'm seeing some weird behaviour. For some reason whenever I scroll through the list to the point where the selected item is not visible and then scroll back to the point where the selected item IS visible, the background colour unexpectedly gets reused. I believe something needs to go in the getView method but I'm not sure what to do with this method. What must be done in order to prevent the background colour from being reused?
Adapter class
public class VictoriaListAdapter extends BaseAdapter {
private List<Victoria> mData;
private LayoutInflater mInflater;
public VictoriaListAdapter (List<Victoria> data, Context context) {
mData = data;
mData = new ArrayList(mData);
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return mData.size();
}
#Override
public String getItem(int position) {
return mData.get(position).getStation();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item_dualline, parent, false);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.item_station);
holder.description = (TextView) convertView.findViewById(R.id.item_zone);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.title.setText(mData.get(position).getStation());
holder.description.setText(mData.get(position).getZone());
return convertView;
}
/**
* View holder
*/
static class ViewHolder {
private TextView title;
private TextView description;
}
}
Fragment class
public class FragmentVictoriaLine extends ListFragment {
private VictoriaListAdapter mAdapter;
public FragmentVictoriaLine() {
}
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet
* device.
*/
public boolean mTwoPane;
public static FragmentVictoriaLine newInstance() {
return new FragmentVictoriaLine();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_victoria_line, container, false);
initialize();
return view;
}
List<Victoria> list = new ArrayList<>();
private void initialize() {
String[] items = getActivity().getResources().getStringArray(R.array.victoria_stations);
String[] itemDescriptions = getActivity().getResources().getStringArray(R.array.victoria_zones);
for (int n = 0; n < items.length; n++){
Victoria victoria = new Victoria();
victoria.setID();
victoria.setStation(items[n]);
victoria.setZone(itemDescriptions[n]);
list.add(victoria);
}
mAdapter = new VictoriaListAdapter(list, getActivity());
setListAdapter(mAdapter);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
View v = getView();
mTwoPane = getActivity().findViewById(R.id.detail_container) != null;
assert v != null;
ListView lv = (ListView)v.findViewById(android.R.id.list);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
private Victoria selectedMain;
private View selectedView;
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
VictoriaListAdapter adapter = (VictoriaListAdapter) parent.getAdapter();
String station = adapter.getItem(position);
if (mTwoPane) {
setItemNormal();
View rowView = view;
setItemSelected(rowView);
Fragment newFragment;
if (station.equals(view.getResources().getString(R.string.bho))) {
newFragment = new FragmentVictoriaBHO();
} else if (station.equals(view.getResources().getString(R.string.brx))) {
newFragment = new FragmentVictoriaBRX();
} else if (station.equals(view.getResources().getString(R.string.eus))) {
newFragment = new FragmentVictoriaEUS();
} else if (station.equals(view.getResources().getString(R.string.fpk))) {
newFragment = new FragmentVictoriaFPK();
} else if (station.equals(view.getResources().getString(R.string.green_park))) {
newFragment = new FragmentVictoriaGreenPark();
} else if (station.equals(view.getResources().getString(R.string.hhy))) {
newFragment = new FragmentVictoriaHHY();
} else if (station.equals(view.getResources().getString(R.string.kxsp))) {
newFragment = new FragmentVictoriaKXSP();
} else {
newFragment = new FragmentVictoriaBHO();
}
VictoriaLineActivity activity = (VictoriaLineActivity) view.getContext();
FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.fade_out, R.anim.fade_in);
transaction.replace(R.id.detail_container, newFragment);
transaction.commit();
} else {
Intent intent;
if (station.equals(view.getResources().getString(R.string.bho))) {
intent = new Intent(getActivity(), VictoriaBHOActivity.class);
} else if (station.equals(view.getResources().getString(R.string.brx))) {
intent = new Intent(getActivity(), VictoriaBRXActivity.class);
} else if (station.equals(view.getResources().getString(R.string.eus))) {
intent = new Intent(getActivity(), VictoriaEUSActivity.class);
} else if (station.equals(view.getResources().getString(R.string.fpk))) {
intent = new Intent(getActivity(), VictoriaFPKActivity.class);
} else if (station.equals(view.getResources().getString(R.string.green_park))) {
intent = new Intent(getActivity(), VictoriaGreenParkActivity.class);
} else if (station.equals(view.getResources().getString(R.string.hhy))) {
intent = new Intent(getActivity(), VictoriaHHYActivity.class);
} else if (station.equals(view.getResources().getString(R.string.kxsp))) {
intent = new Intent(getActivity(), VictoriaKXSPActivity.class);
} else {
intent = new Intent(getActivity(), VictoriaBHOActivity.class);
}
startActivity(intent);
}
}
public void setItemSelected(View view) {
View rowView = view;
view.setBackgroundColor(Color.parseColor("#868F98"));
TextView tv0 = (TextView) rowView.findViewById(R.id.item_station);
tv0.setTextColor(Color.WHITE);
TextView tv1 = (TextView) rowView.findViewById(R.id.item_zone);
tv1.setTextColor(Color.WHITE);
}
public void setItemNormal() {
for (int i = 0; i < getListView().getChildCount(); i++) {
View v = getListView().getChildAt(i);
v.setBackgroundColor(Color.TRANSPARENT);
TextView tv0 = ((TextView) v.findViewById(R.id.item_station));
tv0.setTextColor(Color.WHITE);
TextView tv1 = ((TextView) v.findViewById(R.id.item_zone));
tv1.setTextColor(Color.parseColor("#B5B5B5"));
}
}
});
super.onActivityCreated(savedInstanceState);
}
}
data class
public class Victoria {
public Victoria(){}
private String station;
private String zone;
private boolean selected;
public String getStation(){
return station;
}
public void setStation(String item){
this.station = item;
}
public String getZone(){
return zone;
}
public void setZone(String zone){
this.zone = zone;
}
private int _id;
public void getID(int _id){
this._id = _id;
}
public int setID(){
return _id;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
When you scroll through the list, the items/views in the ListView will get reused to optimize the memory.So when you set a selected state to a list item, you will see that selected state in multiple list items as you scroll through. The best way to prevent this is to preserve the state in your Data Model and set the state in getView function of the Adapter.
Here is what you can do -
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
VictoriaListAdapter adapter = (VictoriaListAdapter) parent.getAdapter();
//reverse the selected state in data model
for (int i = 0; i < adapter.getCount(); i++) {
Victoria victoria = (Victoria)adapter.getItem(i);
victoria.setSelected(i == position ? true : false);
}
Victoria victoria = (Victoria)adapter.getItem(position);
---
---
And in adapter -
#Override
public Object getItem(int position) {
//Return full object, coz we need to access other
//member variables too
return mData.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item_dualline, parent, false);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.item_station);
holder.description = (TextView) convertView.findViewById(R.id.item_zone);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Victoria victoria = (Victoria)getItem(position);
holder.title.setText(victoria.getStation());
holder.description.setText(victoria.getZone());
if (victoria.isSelected()) {
setItemSelected(convertView);
} else {
setItemNormal(convertView);
}
return convertView;
}
public void setItemSelected(View view) {
View rowView = view;
view.setBackgroundColor(Color.parseColor("#868F98"));
TextView tv0 = (TextView) rowView.findViewById(R.id.item_station);
tv0.setTextColor(Color.WHITE);
TextView tv1 = (TextView) rowView.findViewById(R.id.item_zone);
tv1.setTextColor(Color.WHITE);
}
public void setItemNormal(View v) {
v.setBackgroundColor(Color.TRANSPARENT);
TextView tv0 = ((TextView) v.findViewById(R.id.item_station));
tv0.setTextColor(Color.WHITE);
TextView tv1 = ((TextView) v.findViewById(R.id.item_zone));
tv1.setTextColor(Color.parseColor("#B5B5B5"));
}
Hope it helps!

Categories