ListView custom adapter for Android 9.0 - NullPointerException - java

I have a ListView that displays a custom view when the user clicks in the search button. Each custom view is a checkbox. When the user selects a checkbox, the object in that position goes to a list. What I need to do is: if the user clicks again in the search button, the view that was already checked (is on the list), can't appear in the ListView again.
I did a code that is working perfectly in Android 6.0, my problem is at Android 9.0 that is returning:
java.lang.NullPointerException: Attempt to invoke virtual method 'int
android.view.View.getImportantForAccessibility()' on a null object
reference
This is the adapter code:
package com.example.nerasexpert.adapter;
import android.app.Activity;
import android.net.wifi.ScanResult;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import com.example.nerasexpert.R;
import java.util.ArrayList;
import java.util.List;
public class ListaDevicesAdapter extends BaseAdapter {
private List<ScanResult> devices;
private final Activity activity;
private ArrayList<ScanResult> selectedDevices = new ArrayList<>();
public ListaDevicesAdapter(Activity activity, List<ScanResult> nerasList) {
this.activity = activity;
this.devices = nerasList;
}
#Override
public int getCount() {
return devices.size();
}
#Override
public Object getItem(int position) {
return devices.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
LayoutInflater inflater = activity.getLayoutInflater();
View viewCriada = inflater.inflate(R.layout.item_install, viewGroup, false);
Log.i("lista devices", "" + devices);
Log.i("item", "" + devices.get(position));
Log.i("selected devices", "" + selectedDevices);
for (ScanResult device :
selectedDevices){
if(device.SSID.equals(devices.get(position).SSID)) {
return null;
}
}
populaView(position, viewCriada);
return viewCriada;
}
private void populaView(int position, View viewCriada) {
CheckBox deviceName = viewCriada.findViewById(R.id.checkBox);
ScanResult deviceDevolvido = devices.get(position);
deviceName.setText(deviceDevolvido.SSID);
deviceName.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked) {
selectedDevices.add(deviceDevolvido);
} else {
selectedDevices.remove(deviceDevolvido);
}
}
});
}
public ArrayList<ScanResult> getSelectedDevicesList() {
return this.selectedDevices;
}
public void update(List<ScanResult> list) {
this.devices.clear();
this.devices.addAll(list);
notifyDataSetChanged();
}
}
I know that the problem is in returning null when the objects exists in the list, but what can I do to have the same result without the NullPointException in Android 9.0?

Related

Android filterResults() showing duplicate items

I don't know why I am getting this error.
I had implemented filterResults().
Actually, when I search first time in edit text and click on it, it works fine.
Then when I come back and search for some city again, it shows 2 same entries. I have added screenshots.
Then when I come back and search 3rd time I got 3 same entries for each city searched.
My java class:
package com.wordpress.myselfnikunj.cofighter;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.wordpress.myselfnikunj.cofighter.Adapters.CountryListAdapter;
import com.wordpress.myselfnikunj.cofighter.Model.CountryNamesModel;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class AffectedCountriesFragment extends Fragment {
EditText searchEditText;
ListView listView;
public static List<CountryNamesModel> countryNamesModelList = new ArrayList<>();
CountryNamesModel countryNamesModel;
CountryListAdapter countryListAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_affected_countries, container, false);
searchEditText = (EditText) view.findViewById(R.id.searchEditText);
listView = (ListView) view.findViewById(R.id.countriesListView);
countryListAdapter = new CountryListAdapter(getContext(), countryNamesModelList);
// listView.setAdapter(countryListAdapter);
fetchData();
searchEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
countryListAdapter.getFilter().filter(charSequence);
countryListAdapter.notifyDataSetChanged();
}
#Override
public void afterTextChanged(Editable editable) {
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Bundle position = new Bundle();
position.putInt("position", i);
Navigation.findNavController(view).navigate(R.id.action_affectedCountriesFragment_to_countryDetailsFragment, position);
}
});
return view;
}
private void fetchData() {
String Url = "https://corona.lmao.ninja/v2/countries/";
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
Url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.i("hehes","entered");
try {
Log.i("hehe", response.toString());
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
String countryName = jsonObject.getString("country");
String cases = jsonObject.getString("cases");
String todayCases = jsonObject.getString("todayCases");
String deaths = jsonObject.getString("deaths");
String recovered = jsonObject.getString("recovered");
String todayDeaths = jsonObject.getString("todayDeaths");
String active = jsonObject.getString("active");
String critical = jsonObject.getString("critical");
JSONObject object = jsonObject.getJSONObject("countryInfo");
String flagUrl = object.getString("flag");
countryNamesModel = new CountryNamesModel(getContext(),flagUrl, countryName, cases, todayCases, deaths, todayDeaths, recovered, active, critical);
countryNamesModelList.add(countryNamesModel);
}
countryListAdapter.notifyDataSetChanged();
listView.setAdapter(countryListAdapter);
}catch (Exception e) {
Log.i("error", e.getMessage());
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("errors", error.getMessage());
Toast.makeText(getContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}
);
requestQueue.add(jsonArrayRequest);
}
My custom Adapter
package com.wordpress.myselfnikunj.cofighter.Adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.bumptech.glide.Glide;
import com.wordpress.myselfnikunj.cofighter.AffectedCountriesFragment;
import com.wordpress.myselfnikunj.cofighter.Model.CountryNamesModel;
import com.wordpress.myselfnikunj.cofighter.R;
import com.wordpress.myselfnikunj.cofighter.UpdatesFragment;
import java.util.ArrayList;
import java.util.List;
public class CountryListAdapter extends ArrayAdapter<CountryNamesModel> {
private Context context;
private List<CountryNamesModel> countryModelList;
private List<CountryNamesModel> countryModelListFiltered;
public CountryListAdapter( Context context, List<CountryNamesModel> countryModelList) {
super(context, R.layout.countryitem, countryModelList);
this.context = context;
this.countryModelList = countryModelList;
this.countryModelListFiltered = countryModelList;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.countryitem, null, true);
TextView tvCountryName = view.findViewById(R.id.countryName);
ImageView imageView = view.findViewById(R.id.countryImageFlag);
tvCountryName.setText(countryModelListFiltered.get(position).getCountry());
Glide.with(context).load(countryModelListFiltered.get(position).getFlag()).into(imageView);
return view;
}
#Override
public int getCount() {
return countryModelListFiltered.size();
}
#Nullable
#Override
public CountryNamesModel getItem(int position) {
return countryModelListFiltered.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#NonNull
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
FilterResults filterResults = new FilterResults();
if (charSequence == null
|| charSequence.length() == 0
) {
filterResults.count = countryModelList.size();
filterResults.values = countryModelList;
} else {
List<CountryNamesModel> resultsModel = new ArrayList<>();
String searchStr = charSequence.toString().toLowerCase();
for (CountryNamesModel itemsModel: countryModelList) {
if(itemsModel.getCountry().toLowerCase().contains(searchStr)) {
resultsModel.add(itemsModel);
}
filterResults.count = resultsModel.size();
filterResults.values = resultsModel;
}
}
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults results) {
countryModelListFiltered = (List<CountryNamesModel>) results.values;
UpdatesFragment.countryNamesModelList = (List<CountryNamesModel>) results.values;
//AffectedCountriesFragment.countryNamesModelList = (List<CountryNamesModel>) results.values;
notifyDataSetChanged();
}
};
return filter;
}
}
Screenshots
Second Time
Third Time
When you navigate to another fragment view of the AffectedCountriesFragment getting destroyed and public void onDestroyView() is called. When you return back public View onCreateView is called again. But your fragment was not totally destroyed and all of its variables still exist and are in the state they were left.
It means that when you navigate to the next fragment your countryNamesModelList stays filled and when you return back to the AffectedCountriesFragment the same filled list getting filled again resulting in duplicated entries.
What you can do?
Track the state of your fragment. Create a new class-level variable private View view; that will hold the view of your fragment.
// If null - must be initialized and returned in `onCreateView`
// If not null - must be returned in `onCreateView` immediately
// avoiding recreation of the same view (performance improvement)
private View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (view == null) {
// Inflate the layout for this fragment ONLY IF IT IS NULL
View view = inflater.inflate(R.layout.fragment_affected_countries, container, false);
searchEditText = (EditText) view.findViewById(R.id.searchEditText);
listView = (ListView) view.findViewById(R.id.countriesListView);
countryListAdapter = new CountryListAdapter(getContext(), countryNamesModelList);
// listView.setAdapter(countryListAdapter);
fetchData();
searchEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
countryListAdapter.getFilter().filter(charSequence);
countryListAdapter.notifyDataSetChanged();
}
#Override
public void afterTextChanged(Editable editable) {
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Bundle position = new Bundle();
position.putInt("position", I);
Navigation.findNavController(view).navigate(R.id.action_affectedCountriesFragment_to_countryDetailsFragment, position);
}
});
}
return view;
}
Make sure you are not missing something in an understanding of Activity and Fragment lifecycles. Here is a good example of their lifecycles.

Use epicDialog in Adapter class

I have built an overview of an order with a ReyclerView. Below you can see the code for the adapter class. My problem only occurs in the following place, if the user clicks on an element of ReyclerView, a popup with an expanded view should appear.
This popup also occurs. Unfortunately, as soon as I want to populate the TextView with the order code, the app supports and says null Attempt to invoke virtual method'void android.widget.TextView.setText (java.lang.CharSequence)' on a null object reference.
How can I avoid this null error so that it all works?
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class UserBestellAdapter extends RecyclerView.Adapter<UserBestellAdapter.ViewHolder> {
ArrayList<Bestellung> bestellung;
Context mContext;
Dialog epicDialog;
public UserBestellAdapter(Context context, ArrayList<Bestellung> list) {
mContext = context;
bestellung = list;
epicDialog = new Dialog(mContext);
}
#NonNull
#Override
public UserBestellAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.adapter_bestell, parent, false);
UserBestellAdapter.ViewHolder viewHolder = new UserBestellAdapter.ViewHolder(view);
return viewHolder;
}
#NonNull
#Override
public void onBindViewHolder(#NonNull UserBestellAdapter.ViewHolder holder, int position) {
//Gesamtpreis: holder.item_betrag.setText(String.valueOf(bestellung.get(position).getBetrag()));
// Datum: holder.item_datum.setText(bestellung.get(position).getDatum());
holder.item_items.setText(bestellung.get(position).getProdukte());
//holder.item_code.setText(bestellung.get(position).getBestellnummer());
String bestellid =bestellung.get(position).getBestellnummer() + "";
holder.item_code.setText(bestellid);
holder.item_betrag.setText(Double.toString(bestellung.get(position).getSumme()));
holder.item_datum.setText(bestellung.get(position).getDatum());
holder.layout_user_bestellung.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TextView order_overview_number = epicDialog.findViewById(R.id.order_overview_number);
order_overview_number.setText();
epicDialog.setContentView(R.layout.order_popup_waiting);
epicDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
Button btn_order_overview_finish = (Button) epicDialog.findViewById(R.id.btn_order_overview_finish);
/*
btn_order_overview_finish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
epicDialog.dismiss();
}
});*/
epicDialog.show();
}
});
}
#Override
public int getItemCount() {
return bestellung.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private TextView item_items, item_betrag, item_datum, item_code;
private ConstraintLayout layout_user_bestellung;
public ViewHolder(#NonNull View itemView) {
super(itemView);
item_items = itemView.findViewById(R.id.items);
item_betrag = itemView.findViewById(R.id.betrag);
item_datum = itemView.findViewById(R.id.datum);
item_code = itemView.findViewById(R.id.code);
layout_user_bestellung = itemView.findViewById(R.id.layout_user_bestellung);
}
}
}
Your Dialog is initialized with new Dialog(context) but in your onClick Method you expect that your epicDialog has a TextVew with the id order_overview_number.
This will always return null and thus order_overview_number.setText() thows a NPE.
To reference a view of a Dialog the Dialog needs a layout which contains that view, similar to fragments and activities.
This may have further information for you:
How to create a Custom Dialog box in android?
https://developer.android.com/guide/topics/ui/dialogs

Saving dynamically added Views(pages) of Viewpager in SharedPreferences

Hi friends I am trying from long time to save dynamically added views of Viewpager in shardepreferences. So that when user next time open the app , his added pages or views should be there. But I have no success. I am trying to save the size of ArrayList in sharedpreferences and then trying to call regenerate the size of ArrayList next time when user open app. what I am doing is i am adding number of pages in pager with for loop that are equal to size of ArrayList. I dont know is this a right way or i am completely wrong. Please guide me someone through this. Thanks in advance. I am uploading the pic of my UI also enter image description here.I am pasting my code here. First below is code of my adapter.
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
public class MainPagerAdapter extends PagerAdapter
{
private ArrayList<View> views = new ArrayList<View>();
SharedPreferences preferences;
Context context;
LayoutInflater inflater;
final static String PREF_COUNT="com.savesampledata";
final static String PREF_KEY="com.savesampledata.key";
final static String PREF_LIST="com.savesampledata.list";
final static String PREF_LIST_KEY="com.savesampledata.listkey";
int numberofview;
public MainPagerAdapter(Context c){
context=c;
}
#Override
public int getItemPosition (Object object)
{
int index = views.indexOf (object);
if (index == -1)
return POSITION_NONE;
else
return index;
}
#Override
public Object instantiateItem (ViewGroup container, int position)
{
Log.v("instantiate is called","now");
View v;
v = views.get(position);
if(v.getParent()!=null)
((ViewGroup)v.getParent()).removeView(v);
container.addView(v);
return v;
}
#Override
public void destroyItem (ViewGroup container, int position, Object object)
{
container.removeView (views.get (position));
}
#Override
public int getCount ()
{
Log.d("view list size",views.size()+"");
Log.d("numofViews before save",numberofview+"");
return views.size();
}
#Override
public boolean isViewFromObject (View view, Object object)
{
return view == object;
}
public int addView (View v)
{
return addView (v, views.size());
}
public int addView (View v, int position)
{
views.add (position, v);
return position;
}
public int removeView (ViewPager pager, View v)
{
return removeView (pager, views.indexOf (v));
}
public int removeView (ViewPager pager, int position)
{
if (numberofview > 1)
position = numberofview - 1;
if(position>0) {
pager.setAdapter(null);
views.remove(position);
pager.setAdapter(this);
}
return position;
}
public View getView (int position)
{
return views.get (position);
}
public void setCount(){
//storing size of views list
SharedPreferences preferences=context.getSharedPreferences(PREF_COUNT,Context.MODE_PRIVATE);
SharedPreferences.Editor editor=preferences.edit();
editor.putInt(PREF_KEY,views.size());
Log.d("shared stored val :",views.size()+"");
editor.apply();
}
public int getNumberOfView(){
//getting size of views list
SharedPreferences preferences=context.getSharedPreferences(PREF_COUNT, Context.MODE_PRIVATE);
numberofview=preferences.getInt(PREF_KEY,0);
return numberofview;
}
}
Code of my Activity:
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
public class ViewPagerActivity extends AppCompatActivity implements View.OnClickListener {
private ViewPager pager =null;
private MainPagerAdapter pageradapter=null;
Button addpagebtn,removebtn;
final static String PREF_COUNT="com.savesampledata";
final static String PREF_KEY="com.savesampledata.key";
int numberofview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_pager_activity);
addpagebtn=(Button)findViewById(R.id.addbtn) ;
removebtn=(Button)findViewById(R.id.removeButton);
removebtn.setOnClickListener(this);
addpagebtn.setOnClickListener(this);
pageradapter= new MainPagerAdapter(this);
pager=(ViewPager)findViewById(R.id.view_pager);
pager.setAdapter(pageradapter);
pager.setOffscreenPageLimit(3);
numberofview=pageradapter.getNumberOfView();//here i am getting the value
Log.d("value after saving",pageradapter.getNumberOfView()+"");
LayoutInflater inflater=getLayoutInflater();
FrameLayout v0=(FrameLayout)inflater.inflate(R.layout.sample_layout_page,null);
pageradapter.addView(v0,0);
pageradapter.notifyDataSetChanged();
if(numberofview>1) {
Log.d("ManyView","added");
for (int i = 1; i <= numberofview; i++) {
pageradapter.addView(v0,i);
pageradapter.notifyDataSetChanged();
}
}
}
public void addView(View newpage){
int pageIndex=pageradapter.addView(newpage);
Log.d("page added at",pageIndex+"");
pageradapter.notifyDataSetChanged();
pageradapter.setCount();
pager.setCurrentItem(pageIndex,true);
}
public void removeView(View defunctPage){
int pageindex=pageradapter.removeView(pager,defunctPage);
Log.d("page removed at",pageindex+"");
pageradapter.notifyDataSetChanged();
pageradapter.setCount();
if(pageindex==pageradapter.getCount())
pageindex--;
pager.setCurrentItem(pageindex);
}
public View getCurrentPage(){
return pageradapter.getView(pager.getCurrentItem());
}
public void setCurrentPage(View pageToShow){
pager.setCurrentItem(pageradapter.getItemPosition(pageToShow),true);
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.addbtn) {
LayoutInflater inflater=getLayoutInflater();
FrameLayout v0=(FrameLayout)inflater.inflate(R.layout.sample_layout_page,null);
addView(v0);
pageradapter.setCount();
}
if(v.getId()==R.id.removeButton){
View v1=getCurrentPage();
removeView(v1);
pageradapter.setCount();
}
}
#Override
protected void onStop() {
//here I am storing value
super.onStop();
pageradapter.setCount();
}
}

In Android, how to achieve snap effect on a listview while respecting acceleration caused by fling?

For demonstration, I have a ListView displaying a list of numbers. I would like to achieve the effect that when the user scrolls the ListView and the scrolling ends, it will only stop at certain positions so that the first visible item is always shown completely. I've attached my attempted code below. It works when users drag to scroll the ListView. But when there's fling, the normal acceleration is interrupted, causing an unnatural stop. My question is, how can I take acceleration caused by fling into account while achieving the same effect?
package com.example.snaptest;
import android.content.Context;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
private static class TestListViewAdapter extends BaseAdapter {
private Context mContext;
public TestListViewAdapter(Context context) {
mContext = context;
}
#Override
public int getCount() {
return 100;
}
#Override
public Object getItem(int position) {
return Integer.toString(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView textView = new TextView(mContext);
textView.setText(Integer.toString(position));
AbsListView.LayoutParams params = new AbsListView.LayoutParams(ViewGroup.LayoutParams
.MATCH_PARENT, 180);
textView.setLayoutParams(params);
return textView;
}
}
private static class TestListView extends ListView {
public TestListView(Context context) {
super(context);
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_CANCEL) {
View itemView = getChildAt(0);
int top = Math.abs(itemView.getTop()); // top is a negative value
int bottom = Math.abs(itemView.getBottom());
if (top >= bottom){
smoothScrollToPositionFromTop
(getFirstVisiblePosition() + 1, 0);
} else {
smoothScrollToPositionFromTop
(getFirstVisiblePosition(), 0);
}
}
return super.onTouchEvent(ev);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TestListView listView = new TestListView(this);
listView.setAdapter(new TestListViewAdapter(this));
setContentView(listView);
}
}
I would try with an OnScrollListener rather than extending ListView.
Something like this:
listView.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == AbsListView.SCROLL_STATE_IDLE) {
// snap the listview according to the top/bottom items' visibility
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
});

"Set wallpaper" button function, Android

I've created a custom gallery; however, the "Set wallpaper" button will not set the wallpaper. Here's the wallpaper.java I have. I'm just lost on how to implement OnClickListener and then set my button to use an onclicklistener like so:
buttonName.setOnClickListener(this);
package com.totem;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Gallery.LayoutParams;
import java.io.IOException;
import java.io.InputStream;
public class Wallpaper extends Activity implements
AdapterView.OnItemSelectedListener, AdapterView.OnItemClickListener {
private static final String LOG_TAG = "Home";
private static final Integer[] THUMB_IDS = {
R.drawable.andy_small,
};
private static final Integer[] IMAGE_IDS = {
R.drawable.andy,
};
private Gallery mGallery;
private boolean mIsWallpaperSet;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.wallpaper_chooser);
mGallery = (Gallery) findViewById(R.id.gallery);
mGallery.setAdapter(new ImageAdapter(this));
mGallery.setOnItemSelectedListener(this);
mGallery.setOnItemClickListener(this);
}
#Override
protected void onResume() {
super.onResume();
mIsWallpaperSet = false;
}
#SuppressWarnings("unchecked")
public void onItemSelected(AdapterView parent, View v, int position, long id) {
getWindow().setBackgroundDrawableResource(IMAGE_IDS[position]);
}
#SuppressWarnings("unchecked")
public void onItemClick(AdapterView parent, View v, int position, long id) {
selectWallpaper(position);
}
private synchronized void selectWallpaper(int position) {
if (mIsWallpaperSet) {
return;
}
mIsWallpaperSet = true;
try {
InputStream stream = getResources().openRawResource(IMAGE_IDS[position]);
setWallpaper(stream);
setResult(RESULT_OK);
finish();
} catch (IOException e) {
Log.e(LOG_TAG, "Failed to set wallpaper " + e);
}
}
#SuppressWarnings("unchecked")
public void onNothingSelected(AdapterView parent) {
}
public boolean onTouchEvent(MotionEvent event, Object Action_Down) {
getAction(Action_Down);
selectWallpaper(mGallery.getSelectedItemPosition());
return true;
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return THUMB_IDS.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
i.setImageResource(THUMB_IDS[position]);
i.setAdjustViewBounds(true);
i.setLayoutParams(new Gallery.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
i.setBackgroundResource(android.R.drawable.picture_frame);
return i;
}
}
}
Parsed in 0.242 seconds, using GeSHi 1.0.8.4
Go to http://www.xtensivearts.com/topics/tutorials/ there are video tutorials that will help you with the onclicklisteners
are you set user permission in androidmanifest file for set Wallpaper?
<uses-permission android:name="android.permission.SET_WALLPAPER" />

Categories

Resources