I am trying to use TextChangedListener to implement search functionality on my ListView. But after adding some character in EditText; the ListView goes blank. I have implemented filter method in my ArrayAdapter class.
I am getting my data from JSON.
My Logcat shows: getSlotFromBufferLocked: unknown buffer
Is there any other way to search ListView?
Here's my code:
UserList.java
public class UserList extends AppCompatActivity {
private ListView listView;
private ArrayList<MyDataModel> list;
private MyArrayAdapter adapter;
private EditText search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_list);
search = (EditText) findViewById(R.id.search);
//Array List for Binding Data from JSON to this List
list = new ArrayList<>();
//Binding that List to Adapter
adapter = new MyArrayAdapter(this, list);
//Getting List and Setting List Adapter
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true);
search.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String text = search.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#Override
public void afterTextChanged(Editable s) {
}
});
//Checking Internet Connection
if (InternetConnection.checkConnection(getApplicationContext())) {
new GetDataTask().execute();
} else {
Snackbar.make(findViewById(R.id.parentLayout),"Internet Connection Not Available", Snackbar.LENGTH_LONG).show();
}
}
//Creating Get Data Task for Getting Data From Web
class GetDataTask extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog;
int jIndex;
int x;
#Override
protected void onPreExecute() {
super.onPreExecute();
//Progress Dialog for User Interaction
x=list.size();
if(x==0)
jIndex=0;
else
jIndex=x;
dialog = new ProgressDialog(UserList.this);
dialog.setTitle("Please Wait..."+x);
dialog.setMessage("Retrieving Data");
dialog.show();
}
#Nullable
#Override
protected Void doInBackground(Void... params) {
//Getting JSON Object from Web Using okHttp
JSONObject jsonObject = JSONParser.getDataFromWeb();
try {
if (jsonObject != null) {
if(jsonObject.length() > 0) {
JSONArray array = jsonObject.getJSONArray(Keys.KEY_CONTACTS);
//Check Length of Array...
int lenArray = array.length();
if(lenArray > 0) {
for( ; jIndex < lenArray; jIndex++) {
//Creating Every time New Object and adding to List
MyDataModel model = new MyDataModel();
JSONObject innerObject = array.getJSONObject(jIndex);
String name = innerObject.getString(Keys.KEY_NAME);
model.setName(name);
list.add(model);
}
}
}
} else {
}
} catch (JSONException je) {
Log.i(JSONParser.TAG, "" + je.getLocalizedMessage());
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
dialog.dismiss();
//Checking if List size if more than zero then update ListView
if(list.size() > 0) {
adapter.notifyDataSetChanged();
} else {
Snackbar.make(findViewById(R.id.parentLayout), "No Data Found", Snackbar.LENGTH_LONG).show();
}
}
}
}
I have implemented the filter method in my ArrayAdapter class.
Here's my ArrayAdapter class:
MyArrayAdapter.java
public class MyArrayAdapter extends ArrayAdapter<MyDataModel> implements Filterable{
List<MyDataModel> modelList;
Context context;
private LayoutInflater mInflater;
private ArrayList<MyDataModel> arrayList;
public MyArrayAdapter(Context context, List<MyDataModel> objects) {
super(context, 0, objects);
this.context = context;
this.mInflater = LayoutInflater.from(context);
modelList = objects;
this.arrayList = new ArrayList<MyDataModel>();
this.arrayList.addAll(modelList);
}
#Override
public MyDataModel getItem(int position) {
return modelList.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder vh;
if (convertView == null) {
View view = mInflater.inflate(R.layout.layout_row_view, parent, false);
vh = ViewHolder.create((RelativeLayout) view);
view.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
MyDataModel item = getItem(position);
vh.textViewName.setText(item.getName());
return vh.rootView;
}
private static class ViewHolder {
public final RelativeLayout rootView;
public final TextView textViewName;
private ViewHolder(RelativeLayout rootView, TextView textViewName) {
this.rootView = rootView;
this.textViewName = textViewName;
}
public static ViewHolder create(RelativeLayout rootView) {
TextView textViewName = (TextView) rootView.findViewById(R.id.textViewName);
return new ViewHolder(rootView, textViewName);
}
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
modelList.clear();
if (charText.length() == 0) {
modelList.addAll(arrayList);
} else {
for (MyDataModel wp : arrayList) {
if (wp.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
modelList.add(wp);
}
}
}
notifyDataSetChanged();
}
Try,
modelList = new ArrayList<MyDataModel>;
Write this line after modelList.clear(); and check.
Go with this link, and follow steps for implementing the same:
and the problem with buffer is called every textchanged listener will call everytime if you add or delete any character or space in it. So avoid using that. It will cause memory leak problems.
Related
i want create a fragment and have inside a recycler view for show products ...
but when i render it is show this error : RecyclerView: No adapter attached; skipping layout
below i copy my codes;
this code is for adapter class :
private ArrayList<Products> ProductsList;
private Context context;
public Adapter(ArrayList<Products> productsList, Context context) {
ProductsList = productsList;
this.context = context;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.row_layout, parent, false);
return new MyHolder(v);
}
#Override
public void onBindViewHolder(MyHolder holder, final int position) {
Products products = ProductsList.get(position);
holder.txtName.setText(products.getName());
holder.txtPrice.setText("$ " + products.getPrice());
Picasso.get().load(Config.ipValue + "/images/" + products.getPhoto()).into(holder.imgV);
holder.imgV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.startAnimation(AnimationUtils.loadAnimation(context, android
.R.anim.slide_in_left));
}
});
}
#Override
public int getItemCount() {
return ProductsList.size();
}
class MyHolder extends RecyclerView.ViewHolder {
TextView txtName;
TextView txtPrice;
ImageView imgV;
public MyHolder(View itemView) {
super(itemView);
txtName = itemView.findViewById(R.id.rowTxtProductName);
txtPrice = itemView.findViewById(R.id.rowTxtPrice);
imgV = itemView.findViewById(R.id.rowImgProduct);
}
}
and this one for web api class :
public class WebApiHandler {
Context context;
String apiLink = "";
ArrayList<Products> products = new ArrayList<>();
public WebApiHandler(Context context) {
this.context = context;
}
void apiConnect(String type) {
switch (type) {
case "getproducts": {
apiLink = Config.getProductsWebApi;
break;
}
}
ProgressDialog dialog = ProgressDialog.show(context, "Connecting...",
"please wait", false, false);
StringRequest request = new StringRequest(Request.Method.POST,
apiLink, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
dialog.dismiss();
showJson(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
}
});
RequestQueue queue = Volley.newRequestQueue(context);
queue.add(request);
}
private void showJson(String response) {
products.clear();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("response");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String id = object.getString("id");
String name = object.getString("name");
String description = object.getString("description");
String price = object.getString("price");
String photo = object.getString("photo");
Products p = new Products(id, name, description, price, photo);
products.add(p);
}
} catch (JSONException e) {
e.printStackTrace();
}
VerticalFragment.productsArrayList = products;
IData iData = (IData) context;
iData.sendData();
}}
and my fragment code :
public class VerticalFragment extends Fragment implements IData {
RecyclerView rcVertical;
WebApiHandler webApiHandler;
static ArrayList<Products> productsArrayList = new ArrayList<>();
public VerticalFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_vertical, container, false);
rcVertical = view.findViewById(R.id.rcVertical);
webApiHandler = new WebApiHandler(getContext());
webApiHandler.apiConnect("getproducts");
rcVertical.addOnItemTouchListener(new RecyclerTouchListener(getContext(), rcVertical,
new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, int position) {
ProductActivity.products = productsArrayList.get(position);
startActivity(new Intent(getContext(), ProductActivity.class));
}
#Override
public void onLongClick(View view, int position) {
}
}));
return view;
}
#Override
public void sendData() {
Adapter adapter = new Adapter(productsArrayList, getContext());
rcVertical.setLayoutManager(new LinearLayoutManager((getContext())));
rcVertical.setItemAnimator(new DefaultItemAnimator());
rcVertical.setAdapter(adapter);
}}
i should say i create a interface and have one method i say it sendData
This is a common error when there is no adapter attached to recyclerview upon showing recyclerview. It will not cause any harm to your app, but you could avoid it by setting empty adapter without data, and later when you get your data, provide it to your adapter and notify it
Edit - Example added
Create setter for your list in adapter. After that, in your fragment make adapter global and in onCreateView make instance of your adapter and attach it to recyclerview
adapter = new Adapter(new ArrayList<>(), getContext());
rcVertical.setAdapter(adapter);
...Initialize recyclerview...
And then in your sendData interface put your loaded values in it
adapter.setData(productsArrayList);
adapter.notifyDataSetChanged();
I am creating an app where a list of hotels will be shown, all the data is coming from MySQL using JSON and PHP, I created the custom list view by extending the base adapter to a custom one, but I am not able to implement a OnItemClickListener for the listview, as i want to show the Hotel Name of that row in Toast whenever the user clicks on a row of list view. I tried various example available on internet, but i just doesn't work.
Adapter
public class CustomListAdapterHotel extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<WorldsBillionaires> billionairesItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapterHotel(Activity activity, List<WorldsBillionaires> billionairesItems) {
this.activity = activity;
this.billionairesItems = billionairesItems;
}
#Override
public int getCount() {
return billionairesItems.size();
}
#Override
public Object getItem(int location) {
return billionairesItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_hotel, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
//NetworkImageView thumbNail = (NetworkImageView) convertView.findViewById(R.id.thumbnail);
TextView hotel_name = (TextView) convertView.findViewById(R.id.hotel_name);
TextView zone = (TextView) convertView.findViewById(R.id.zone);
TextView contact_person = (TextView) convertView.findViewById(R.id.contact_person);
TextView contact_number = (TextView) convertView.findViewById(R.id.contact_number);
TextView btc_direct = (TextView) convertView.findViewById(R.id.btcdirect);
// getting billionaires data for the row
WorldsBillionaires m = billionairesItems.get(position);
// name
hotel_name.setText(String.valueOf(m.getHotel_Name()));
zone.setText(String.valueOf(m.getHotel_Zone()));
contact_person.setText(String.valueOf(m.getContact_Person()));
contact_number.setText(String.valueOf(m.getContact_Number()));
btc_direct.setText(String.valueOf(m.getBtc_Direct()));
return convertView;
}
}
Model
public class WorldsBillionaires {
private String hotel_name,hotel_zone,contact_person,contact_number,btc_direct;
public WorldsBillionaires(String hotel_name, String hotel_zone, String contact_person, String contact_number, String btc_direct) {
this.hotel_name=hotel_name;
this.hotel_zone=hotel_zone;
this.contact_person=contact_person;
this.contact_number=contact_number;
this.btc_direct=btc_direct;
}
public WorldsBillionaires() {
}
public String getZone() {
return zone;
}
public void setZone(String zone) {
this.zone = zone;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
}
public String getHotel_Name() {
return hotel_name;
}
public void setHotel_Name(String hotel_name) {
this.hotel_name = hotel_name;
}
public String getHotel_Zone() {
return hotel_zone;
}
public void setHotel_Zone(String hotel_zone) {
this.hotel_zone = hotel_zone;
}
public String getContact_Person() {
return contact_person;
}
public void setContact_Person(String contact_person) {
this.contact_person = contact_person;
}
public String getContact_Number() {
return contact_number;
}
public void setContact_Number(String contact_number) {
this.contact_number = contact_number;
}
public String getBtc_Direct() {
return btc_direct;
}
public void setBtc_Direct(String btc_direct) {
this.btc_direct = btc_direct;
}
}
Main Activity
public class ShowHotel extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
// Billionaires json url
private ProgressDialog pDialog;
private List<WorldsBillionaires> worldsBillionairesList = new ArrayList<WorldsBillionaires>();
private ListView listView;
private CustomListAdapterHotel adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_hotel);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapterHotel(this, worldsBillionairesList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// Creating volley request obj
JsonArrayRequest billionaireReq = new JsonArrayRequest("http://192.168.247.1/AdminBihar/getHotel.php?zone="+methods.zone,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
WorldsBillionaires worldsBillionaires = new WorldsBillionaires();
worldsBillionaires.setHotel_Name(obj.getString("hotel_name"));
worldsBillionaires.setThumbnailUrl(obj.getString("image"));
worldsBillionaires.setHotel_Zone(obj.getString("zone"));
worldsBillionaires.setContact_Person(obj.getString("contact_person"));
worldsBillionaires.setContact_Number(obj.getString("contact_number"));
worldsBillionaires.setBtc_Direct(obj.getString("btc_direct"));
// adding Billionaire to worldsBillionaires array
worldsBillionairesList.add(worldsBillionaires);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(billionaireReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
so after you get json data, in activity that shows your list do something like this:
public class DisplayListView extends AppCompatActivity {
ListView listView;
protected void onCreate(){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_list_view);
listView = (ListView) findViewById(R.id.listview);
hotelAdapter = new CustomListAdapterHotel (this, R.layout.row_layout);
listView.setAdapter(hotelAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
Model stuff = (Model) hotelAdapter.getItem(position);
String hotelName = stuff.getHotel_Name();
Toast.makeText(getApplicationContext(), hotelName, Toast.LENGTH_SHORT).show();
}
});
there, this worked for me :)
I have seen a lot of similar questions about this issue but I couldn't find any solution to this:
I have three fragments in a TabLayout handled by a ViewPager and I have a ListView in the third Fragment which is not displaying any items after I change the orientation of the screen. I have tried to set a background color to the convertView in the ArrayAdapter to see if it was displayed and indeed it is not being displayed after I change the orientation. But it's weird because in my First Fragment where I use the same ArrayAdapter for another ListView everything's working and I can't understand why it's not on the third Fragment.
One thing is sure: I have checked with logs almost everywhere that the ArrayList.size() is never zero.
Here's the Third Fragment's relevant code:
public class SavedScanFragment extends Fragment{
private ListView lv;
private Database db;
private ArrayList<Scan> scans;
private ScanAdapter adapter;
public static SavedScanFragment newInstance() {
return new SavedScanFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db = new Database(getContext());
getScans();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View result = inflater.inflate(R.layout.fragment_saved_scan, container, false);
lv = (ListView) result.findViewById(R.id.saved_scan_list);
return result;
}
#Override
public void onResume() {
super.onResume();
db = new Database(getContext());
getScans();
}
public void getScans() {
AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... params) {
scans = db.getScans();
if(scans!=null)
return true;
else {
scans = new ArrayList<>();
return false;
}
}
#Override
protected void onPostExecute(Boolean result) {
if(result)
populateList();
}
};
task.execute();
}
public void populateList() {
if(getContext()!=null) {
if (lv.getAdapter() == null) {
adapter = new ScanAdapter(getContext(), R.layout.scan_list_item, scans);
lv.setAdapter(adapter);
} else {
((ScanAdapter) lv.getAdapter()).update(scans);
}
}
}
And the ArrayAdapter's code:
public class ScanAdapter extends ArrayAdapter<Scan> implements ListAdapter {
private Context context;
private int layoutResourceID;
private ArrayList<Scan> results;
public ScanAdapter(Context context, int layoutResourceID, ArrayList<Scan> results) {
super(context, layoutResourceID, results);
this.context = context;
this.layoutResourceID = layoutResourceID;
this.results = results;
}
public void update(ArrayList<Scan> scans) {
results.clear();
results.addAll(scans);
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView; //view = row
ViewHolder holder = null;
if(view == null) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(layoutResourceID, parent, false);
view.setBackgroundColor(Color.GREEN);
holder = new ViewHolder();
holder.name = (TextView)view.findViewById(R.id.scan_name_and_date_text);
holder.ssid = (TextView)view.findViewById(R.id.scan_SSID_text);
holder.frequency = (TextView)view.findViewById(R.id.scan_frequency_text);
holder.level = (TextView)view.findViewById(R.id.scan_level_text);
view.setTag(holder);
} else
holder = (ViewHolder) view.getTag();
Scan sr = results.get(position);
holder.name.setText(sr.getName()+" ( "+sr.getDate()+" )");
holder.ssid.setText(sr.getSsid() + " ( " + sr.getBssid() + " )");
holder.frequency.setText(sr.getFrequency()+" MHz");
holder.level.setText(Integer.toString(sr.getLevel())+ " dBm");
return view;
}
static class ViewHolder {
TextView name,ssid, frequency, level;
}
}
Thanks in advance!
From this post. You can try to use onActivityCreated instead of onCreate. Try this:
public class SavedScanFragment extends Fragment{
//....to restore the saved state
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//Restore the fragment state here
db = new Database(getContext());
getScans();
}
//add this to save instant state
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//save your important variable here to outstate
}
}
i am using eclipse.
Basically what i am trying to implement is that , that i have a gridView which is fetching images from mysql database dynamically using JSON.
Now , instead of gridview i want to show them as coverflow view.
I have searched through the internet , but was not able to find any library or example for dynamic images , i only found for static images stored in the app itself and not on external database.
My code are as follows:-
MainActivity.java:-
public class MainActivity extends Activity implements OnClickListener {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
// Movies json url
private static final String url = "http://eventassociate.com/wedding/photomania";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private PullToRefreshGridView mPullRefreshGridView;
private GridView gridView;
private CustomListAdapter adapter;
ImageButton blackcapture;
private static int RESULT_LOAD_IMAGE = 1;
String picturePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.gallary_activity_main);
overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
mPullRefreshGridView = (PullToRefreshGridView) findViewById(R.id.list);
gridView = mPullRefreshGridView.getRefreshableView();
mPullRefreshGridView.setOnRefreshListener(new OnRefreshListener2<GridView>() {
#Override
public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
adapter.notifyDataSetChanged();
gridView.setAdapter(adapter);
gridView.invalidateViews();
mPullRefreshGridView.onRefreshComplete();
}
adapter = new CustomListAdapter(this, movieList);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Movie m5 = movieList.get(position);
Intent i = new Intent(getApplicationContext(),
FullImageActivity.class);
i.putExtra("movieobject", m5);
startActivity(i);
}
});
Adapter Class:-
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
List<Movie> movieItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<Movie> movieItems) {
this.activity = activity;
this.movieItems = movieItems;
}
#Override
public int getCount() {
return movieItems.size();
}
#Override
public Object getItem(int location) {
return movieItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.gallary_list_row, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.thumbnail);
// ...............................................
TextView title = (TextView) convertView.findViewById(R.id.title);
// getting movie data for the row
Movie m = movieItems.get(position);
// thumbnail image
thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
// title
title.setText(m.getTitle());
return convertView;
}
Movie.java:-
public class Movie implements Parcelable{
private String title,thumbnailUrl;
public Movie() {
// TODO Auto-generated constructor stub
}
public Movie(String name, String thumbnailUrl
) {
this.title = name;
this.thumbnailUrl = thumbnailUrl;
}
public String getTitle() {
return title;
}
public void setTitle(String name) {
this.title = name;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = "http://eventassociate.com/wedding/"+thumbnailUrl;
}
// Parcelling part
public Movie(Parcel in){
String[] data = new String[2];
in.readStringArray(data);
this.title = data[0];
this.thumbnailUrl = data[1];
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringArray(new String[] {this.title,
this.thumbnailUrl,
});
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Movie createFromParcel(Parcel in) {
return new Movie(in);
}
public Movie[] newArray(int size) {
return new Movie[size];
}
};
}
I successfully implemented this as GridView , but i am facing trouble in implementing this as coverflow design or something like that.
I searched on the net and i find this code , but only for static images:-
public class SimpleExample extends Activity {
// =============================================================================
// Child views
// =============================================================================
private FancyCoverFlow fancyCoverFlow;
// =============================================================================
// Supertype overrides
// =============================================================================
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.fancyCoverFlow = (FancyCoverFlow) this.findViewById(R.id.fancyCoverFlow);
this.fancyCoverFlow.setAdapter(new FancyCoverFlowSampleAdapter());
this.fancyCoverFlow.setUnselectedAlpha(1.0f);
this.fancyCoverFlow.setUnselectedSaturation(0.0f);
this.fancyCoverFlow.setUnselectedScale(0.5f);
this.fancyCoverFlow.setSpacing(50);
this.fancyCoverFlow.setMaxRotation(0);
this.fancyCoverFlow.setScaleDownGravity(0.2f);
this.fancyCoverFlow.setActionDistance(FancyCoverFlow.ACTION_DISTANCE_AUTO);
}
// =============================================================================
// Private classes
// =============================================================================
}
Adapter.java:-
public class FancyCoverFlowSampleAdapter extends FancyCoverFlowAdapter {
// =============================================================================
// Private members
// =============================================================================
private int[] images = {R.drawable.image1, R.drawable.image2, R.drawable.image3, R.drawable.image4, R.drawable.image5, R.drawable.image6,};
// =============================================================================
// Supertype overrides
// =============================================================================
#Override
public int getCount() {
return images.length;
}
#Override
public Integer getItem(int i) {
return images[i];
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getCoverFlowItem(int i, View reuseableView, ViewGroup viewGroup) {
ImageView imageView = null;
if (reuseableView != null) {
imageView = (ImageView) reuseableView;
} else {
imageView = new ImageView(viewGroup.getContext());
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setLayoutParams(new FancyCoverFlow.LayoutParams(300, 400));
}
imageView.setImageResource(this.getItem(i));
return imageView;
}
}
Can someone help me , in solving my problem.
Thanks.
My final code with coverflow:-
MainActivity:-
public class MainActivity extends Activity implements OnClickListener {
// Log tag
private static final String TAG = album.MainActivity.class.getSimpleName();
// Movies json url
private static final String url = "http://eventassociate.com/wedding/androidadminimages";
private ProgressDialog pDialog;
private List<Moviealbum> movieList = new ArrayList<Moviealbum>();
private FancyCoverFlow fancyCoverFlow;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.album_activity_main);
overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
this.fancyCoverFlow = (FancyCoverFlow) this.findViewById(R.id.list);
adapter = new CustomListAdapter(this, movieList);
this.fancyCoverFlow.setAdapter(new CustomListAdapter(this, movieList));
this.fancyCoverFlow.setUnselectedAlpha(1.0f);
this.fancyCoverFlow.setUnselectedSaturation(0.0f);
this.fancyCoverFlow.setUnselectedScale(0.5f);
this.fancyCoverFlow.setSpacing(50);
this.fancyCoverFlow.setMaxRotation(0);
this.fancyCoverFlow.setScaleDownGravity(0.2f);
this.fancyCoverFlow.setActionDistance(FancyCoverFlow.ACTION_DISTANCE_AUTO);
fancyCoverFlow.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Moviealbum m5 = movieList.get(position);
Intent i = new Intent(getApplicationContext(),album.
FullImageActivity.class);
i.putExtra("movieobject", m5);
startActivity(i);
}
});
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// changing action bar color
getActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#1b1b1b")));
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Moviealbum movie = new Moviealbum();
movie.setTitle(obj.getString("no"));
movie.setThumbnailUrl(obj.getString("alinks"));
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue...................................
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
AdapterClass :-
public class CustomListAdapter extends FancyCoverFlowAdapter {
private Activity activity;
private LayoutInflater inflater;
List<Moviealbum> movieItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<Moviealbum> movieItems) {
this.activity = activity;
this.movieItems = movieItems;
}
#Override
public int getCount() {
return movieItems.size();
}
#Override
public Object getItem(int location) {
return movieItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getCoverFlowItem(int position, View reuseableView, ViewGroup viewGroup) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (reuseableView == null)
reuseableView = inflater.inflate(R.layout.gallary_list_row, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) reuseableView
.findViewById(R.id.thumbnail);
// ...............................................
TextView title = (TextView) reuseableView.findViewById(R.id.title);
// getting movie data for the row
Moviealbum m = movieItems.get(position);
// thumbnail image
thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
// title
title.setText(m.getTitle());
return reuseableView;
}
The app runs fine , but after loading blank screen is shown with no images.
Logcat:-
Your issue isn't with the CoverFlow code, but rather where you're doing your network operation. On app load, begin your network request for your JSON payload, show a spinner to show the app is loading, and populate your Adapter once your images are loaded. I'm assuming you have network code already given your GridView implementation? Let me know if I've missed something. I hope that helps!
EDIT:
Once you've added images to your Adapter make sure you call notifyDataSetChanged() to tell your adapter to reload its views.
EDIT 2:
Look at this line here:
this.fancyCoverFlow.setAdapter(new CustomListAdapter(this, movieList));
You're passing a new CustomListAdapter rather than passing in your adapter variable. Try fixing that and let me know if it works.
I am creating an android app the UI of my application is below given.
On clicking of submit button, I need the selected check box, value and id textview
example size is not checked, cc(radio button) is checked.
records are populated dynamically in list view, but I am not able to make it work.
Checkbox_ProducoptionActivity.java
public class MainActivity extends Activity implements OnItemClickListener {
ListView listview;
ArrayList<HashMap<String, String>> list_kategori ;
ProgressDialog pd;
ArrayAdapter<Model_checkbox> adapter;
List<String> idprdoptins = new ArrayList<String>();
List<Model_checkbox> nameprdoptn = new ArrayList<Model_checkbox>();
List<Model_checkbox> list = new ArrayList<Model_checkbox>();
Button btn_checkbox;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.checkboxproduct_option);
listview = (ListView)findViewById(R.id.list);
btn_checkbox = (Button)findViewById(R.id.btn_productoption);
// TODO Auto-generated method stub
String id =CheckLogin();
if (id!=""){
loadproductoption(id);
}
btn_checkbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
for (Model_checkbox m : list) {
Log.i("Stack1", m.toString());
}
Log.d("Stack1",String.valueOf(Model_checkbox.class));
Toast.makeText(getApplicationContext(), "ada",Toast.LENGTH_LONG).show();
}
});
}
public void loadproductoption(String id) {
listproduct task= new listproduct();
task.execute(id);
}
private class listproduct extends AsyncTask<String, Void, String>{
protected void onPreExecute(){
pd = new ProgressDialog(Checkbox_ProducoptionActivity.this);
pd.setMessage("Please wait..");
pd.setCancelable(false);
pd.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
JSONObject jsonResult = HttpClientCustom.getRequest(Konfigurasi.strUrl+"api-v1/proop?id_user="+ params[0]);
return jsonResult.toString();
}
protected void onPostExecute(String result){
JSONObject jsonResponse=null;
JSONArray jObject=null;
list_kategori = new ArrayList<HashMap<String, String>>();
try {
jsonResponse = new JSONObject(new String(result));
if(jsonResponse.getString("status").equals("SUCCESS")) {
if (!jsonResponse.getString("total").equals("0")){
jObject = jsonResponse.getJSONArray("resultset");
for (int i = 0; i < jObject.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("idprd", jObject.getJSONObject(i).getString("id"));
map.put("id_user", jObject.getJSONObject(i).getString("id_user"));
map.put("namepd", jObject.getJSONObject(i).getString("name"));
setListnama(jObject.getJSONObject(i).getString("name"));
list_kategori.add(map);
}
adapter = new Adapter_Checkboxproductoption(Checkbox_ProducoptionActivity.this, getModel());
listview.setAdapter(adapter);
}
pd.dismiss();
} else if (jsonResponse.getString("status").equals("FAILED")) {
pd.dismiss();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pd.dismiss();
}
private List<Model_checkbox> getModel() {
return nameprdoptn;
}
public void setListnama(String name) {
nameprdoptn.add(new Model_checkbox(name));
}
}
Model checkbox.java
// public class My modele {
public class Model_checkbox {
private String name;
private boolean selected;
//private boolean isCcOrIsTo;
public Model_checkbox(String name) {
this.name = name;
}
public String getName() {
return name;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
#Override
public String toString() {
String selectedString = selected ? "selected" : "not selected";
// String value = isCcOrIsTo ? "CC" : "To";
return name+" -> "+selectedString+ " with value ";
}
}
MyAdapter.java
// public class MyAdapter extends ArrayAdapter {
class ViewHolder {
protected TextView text;
protected CheckBox checkbox;
}
public class Adapter_Checkboxproductoption extends ArrayAdapter<Model_checkbox> {
private final List<Model_checkbox> list;
private final Activity context;
boolean checkAll_flag = false;
boolean checkItem_flag = false;
public Adapter_Checkboxproductoption(Activity context, List<Model_checkbox> list) {
super(context, R.layout.list_checkbox, list);
this.context = context;
this.list = list;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
convertView = inflator.inflate(R.layout.list_checkbox, null);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) convertView.findViewById(R.id.rowTextView);
viewHolder.checkbox = (CheckBox) convertView.findViewById(R.id.CheckBox01);
viewHolder.checkbox.setTag(position);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.text.setText(list.get(position).getName());
viewHolder.checkbox.setChecked(list.get(position).isSelected());
viewHolder.checkbox.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
CheckBox checkbox = (CheckBox) v;
int getPosition = (Integer) checkbox.getTag();
list.get(getPosition).setSelected(checkbox.isChecked());
}
});
return convertView;
}
}
can't work in "Checkbox_ProducoptionActivity.java"
for (Model_checkbox m : list) {
Log.i("Stack1", m.toString());
Can any body help me in getting value and id of selected check box?
All you need to do is get/set the value of checked item in your adapter this way, I did in Cursor adapter you can update below code as per your need.
public class CursorAdapterList extends CursorAdapter {
private LayoutInflater inflater = null;
private DBAdapter db = null;
private Context ctx = null;
public CursorAdapterList(Context context, Cursor c, DBAdapter database) {
super(context, c);
ctx = context;
db = database;
inflater = LayoutInflater.from(context);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView tv = (TextView) view.findViewById(R.id.txtGameNameInList);
CheckBox favBox = (CheckBox) view.findViewById(R.id.favbuttonInList);
tv.setText(cursor.getString(1));
//here I am getting value of already checked boxes from db
String flag = cursor.getString(3);
if (flag.equals("true")) {
favBox.setChecked(true);
} else {
favBox.setChecked(false);
}
favBox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
LinearLayout parentView = (LinearLayout) v.getParent();
TextView clickedText = (TextView) parentView
.findViewById(R.id.txtGameNameInList);
//here you can get the Item value what your selcted in your list
String name = clickedText.getText().toString();
if (((CheckBox) v).isChecked()) {
Toast.makeText(ctx, name + " is Marked as Favorite Game!!",
Toast.LENGTH_SHORT).show();
//below method will store selected item value in db
db.markAsFavorite(name, "true");
} else {
db.markAsFavorite(name, "false");
}
}
});
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return inflater.inflate(R.layout.list_row_custom, parent, false);
}
}
For my activity
public class Checkbox_ProducoptionActivity<country> extends Activity {
ListView list;
static Context mContext;
Button btnSave;
List<String> val = new ArrayList<String>();
ArrayList<HashMap<String, String>> list_kategori ;
ArrayList<String> stock_list = new ArrayList<String>();
ArrayList<String> stock2_list = new ArrayList<String>();
ProgressDialog pd;
EfficientAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.checkboxproduct_option);
list = (ListView) findViewById(R.id.ListView01);
btnSave = (Button)findViewById(R.id.btnSave);
mContext = this;
final String id =CheckLogin();
if (id!=""){
loadproductoption(id);
}
btnSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SharedPreferences val_shared = getSharedPreferences("CHECKBOX_SHARED", MODE_WORLD_WRITEABLE);
SharedPreferences.Editor cleareditor=val_shared.edit();
cleareditor.clear();
cleareditor.commit();
for (int i = 0; i <list.getCount() ; i++) {
View vListSortOrder;
vListSortOrder=list.getChildAt(i);
try{
TextView textval= (TextView)vListSortOrder.findViewById(R.id.TextView01);
CheckBox ckc=(CheckBox)vListSortOrder.findViewById(R.id.chkbox1);
EditText edit=(EditText)vListSortOrder.findViewById(R.id.txtbox);
if (ckc.isChecked()){
edit.getText().toString();
String temp1 = textval.getText().toString();
Toast.makeText(getApplicationContext(), "fuck"+textval.getText().toString(), Toast.LENGTH_LONG).show();
val.add(temp1);
}
}catch (Exception e) {
// TODO: handle exception
}
}
SharedPreferences customer_ident = getSharedPreferences("CHECKBOX_SHARED", MODE_WORLD_WRITEABLE);
SharedPreferences.Editor editor=customer_ident.edit();
editor.putString("valuecheck", val.toString());
editor.commit();
// Toast.makeText(getApplicationContext(), "ada "+val, Toast.LENGTH_LONG).show();
Intent prdmenuact = new Intent(getApplicationContext(),CreateManageProductActivity.class);
prdmenuact.putExtra("idaction", "1");
startActivity(prdmenuact);
finish();
}
});
}
public void loadproductoption(String id) {
listproduct task= new listproduct();
task.execute(id);
}
private class listproduct extends AsyncTask<String, Void, String>{
protected void onPreExecute(){
pd = new ProgressDialog(Checkbox_ProducoptionActivity.this);
pd.setMessage("Please wait..");
pd.setCancelable(false);
pd.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
JSONObject jsonResult = HttpClientCustom.getRequest(Konfigurasi.strUrl+"api-v1/proop?id_user="+ params[0]);
return jsonResult.toString();
}
protected void onPostExecute(String result){
JSONObject jsonResponse=null;
JSONArray jObject=null;
list_kategori = new ArrayList<HashMap<String, String>>();
try {
jsonResponse = new JSONObject(new String(result));
if(jsonResponse.getString("status").equals("SUCCESS")) {
if (!jsonResponse.getString("total").equals("0")){
jObject = jsonResponse.getJSONArray("resultset");
for (int i = 0; i < jObject.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("idprd", jObject.getJSONObject(i).getString("id"));
map.put("id_user", jObject.getJSONObject(i).getString("id_user"));
map.put("namepd", jObject.getJSONObject(i).getString("name"));
list_kategori.add(map);
}
adapter = new EfficientAdapter(Checkbox_ProducoptionActivity.this,list_kategori );
list.setAdapter(adapter);
}
pd.dismiss();
} else if (jsonResponse.getString("status").equals("FAILED")) {
pd.dismiss();
}
} catch (JSONException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
pd.dismiss();
}
}
my adpater
public class EfficientAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private LayoutInflater inflater=null;
public ImageLoader imageLoader;
String priceprd ;
public EfficientAdapter (Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public EfficientAdapter(Runnable runnable,
ArrayList<HashMap<String, String>> list_kategori) {
// TODO Auto-generated constructor stub
}
public int getCount() {
//Log.d("country",String.valueOf(data.size()));
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_checkbox, parent,
false);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.TextView01);
holder.text2 = (TextView) convertView.findViewById(R.id.TextView02);
holder.txt = (EditText) convertView.findViewById(R.id.txtbox);
holder.cbox = (CheckBox) convertView.findViewById(R.id.chkbox1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText( data.get(position).get("idprd"));
holder.text2.setText(data.get(position).get("namepd"));
holder.txt.setText("");
holder.cbox.setChecked(false);
return convertView;
}
public class ViewHolder {
TextView text;
TextView text2;
EditText txt;
CheckBox cbox;
}
}
public String[] convert(List<String[]> list1) {
// TODO Auto-generated method stub
return null;
}
adapter to be replaced
and the model removed
so to check the value of just using ischecked
for (int i = 0; i <list.getCount() ; i++) {
View vListSortOrder;
vListSortOrder=list.getChildAt(i);
try{
TextView textval= (TextView)vListSortOrder.findViewById(R.id.TextView01);
CheckBox ckc=(CheckBox)vListSortOrder.findViewById(R.id.chkbox1);
EditText edit=(EditText)vListSortOrder.findViewById(R.id.txtbox);
if (ckc.isChecked()){
edit.getText().toString();
String temp1 = textval.getText().toString();
Toast.makeText(getApplicationContext(), "fuck"+textval.getText().toString(), Toast.LENGTH_LONG).show();
val.add(temp1);
}
}catch (Exception e) {
// TODO: handle exception
}
}
and successful