This is my Main Activity class.I am new in android development and I'm stuck here. Having a problem in getting images from the server.
I have an image loader class to which loads an image in imageView and memory cache and utils etc.
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, SearchView.OnQueryTextListener {
ListView list;
SearchView mSearchView;
LazyAdapter adapter;
JSONArray jarray;
String data = "", line = null, strresponse, txt, myjson;
BufferedReader reader;
String dataparseurl = "https://ndroid.000webhostapp.com/Php2/getListofrestaurant.php";
public String Id;
public String SName;
public String ShortAdd;
public String imagesserver;
public String hour;
public String address;
ArrayList<HashMap<String, String>> arraylist;
private String Name[] = {"Sagar Gaire Fast Food", "Sharma and Vishnu Fast Food", "Sharma FastFood",
"Domino's Pizza", "Manohar Dairy", "Greek Food & Beyond"};
private int images[] = {R.drawable.img5, R.drawable.img6, R.drawable.img9, R.drawable.img8,
R.drawable.img7, R.drawable.img11};
private String hours[] = {"10AM TO 11PM", "8AM To 10PM", "11AM To 10:30PM", "8AM To 11PM", "8AM To 9PM", "11AM To 11PM"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
DataFromServer();
mSearchView = (SearchView) findViewById(R.id.searcview1);
list = (ListView) findViewById(R.id.lv1);
}
#Override
public void onDestroy() {
list.setAdapter(null);
super.onDestroy();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
finish();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_order) {
// Handle the order action
Intent yourorder = new Intent(MainActivity.this, YourOrder_Layout.class);
startActivity(yourorder);
finish();
} else if (id == R.id.nav_cart) {
Intent cart = new Intent(MainActivity.this, Cart_Layout.class);
startActivity(cart);
finish();
} else if (id == R.id.nav_profiledit) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void DataFromServer() {
class ServerData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String[] params) {
arraylist = new ArrayList<HashMap<String, String>>();
try {
URL url = new URL(dataparseurl);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream());
osw.write(data);
osw.flush();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
while (((line = reader.readLine()) != null)) {
sb.append(line);
strresponse = sb.toString();
}
txt = strresponse;
} catch (Exception e) {
try {
reader.close();
} catch (IOException e1) {
e1.printStackTrace();
}
Toast.makeText(getApplicationContext(), "OOPs Something went wrong Check Your Connection", Toast.LENGTH_SHORT).show();
}
return txt;
}
#Override
protected void onPostExecute(String result) {
if (result == null && txt == null) {
Toast.makeText(getApplicationContext(), "can't be saved", Toast.LENGTH_SHORT).show();
} else {
myjson = result;
showlist();
}
}
}
ServerData sd = new ServerData();
sd.execute();
}
private void showlist() {
try {
JSONObject jsonObject = new JSONObject(myjson);
jarray = jsonObject.getJSONArray("result");
for (int i = 0; i < jarray.length(); i++) {
JSONObject c = jarray.getJSONObject(i);
Id = c.getString("Id");
SName = c.getString("RestName");
ShortAdd = c.getString("RestAddressshort");
imagesserver = c.getString("RestPic");
hour = c.getString("Resthours");
address = c.getString("RestAddress");
HashMap<String, String> map = new HashMap<String, String>();
map.put("ID",Id);
map.put("RestName",SName);
map.put("ShortAddres",ShortAdd);
map.put("RestPic",imagesserver);
map.put("Hour",hour);
map.put("Address",address);
arraylist.add(map);
}
Toast.makeText(getApplicationContext(), arraylist.get(0)+""+arraylist.get(1)+"",Toast.LENGTH_LONG).show();
adapter = new LazyAdapter(this,arraylist);
list.setAdapter(adapter);
list.setTextFilterEnabled(true);
mSearchView.setOnQueryTextListener(this);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent info = new Intent(MainActivity.this, Info_Layout.class);
startActivity(info);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
}
Adapter Class
This is my Adapter Class getting data in array list but images are not getting.
It's working where saw its code but it's not working in my case.
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
private HashMap<String, String> resultp = new HashMap<String, String>();
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> arraylist) {
activity = a;
data = arraylist;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.listitem_1, parent,false);
resultp = data.get(position);
TextView text=(TextView)vi.findViewById(R.id.textviewitemname);
TextView texttime = (TextView) vi.findViewById(R.id.textviewitemhours);
ImageView image=(ImageView)vi.findViewById(R.id.imageviewitem);
text.setText(resultp.get("RestName"));
texttime.setText(resultp.get("Hour"));
// image.setImageResource(data[position]);
imageLoader.DisplayImage(resultp.get("RestPic"),image);
return vi;
}
}
$ here is the image loader class
public class ImageLoader {
private MemoryCache memoryCache=new MemoryCache();
private FileCache fileCache;
private Map<ImageView, String> imageViews= Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
private ExecutorService executorService;
public ImageLoader(Context context){
fileCache=new FileCache(context);
executorService= Executors.newFixedThreadPool(5);
}
private final int stub_id = R.drawable.image1;
public void DisplayImage(String url, ImageView imageView)
{
imageViews.put(imageView, url);
Bitmap bitmap=memoryCache.get(url);
if(bitmap!=null)
imageView.setImageBitmap(bitmap);
else
{
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
}
private void queuePhoto(String url, ImageView imageView)
{
PhotoToLoad p=new PhotoToLoad(url, imageView);
executorService.submit(new PhotosLoader(p));
}
private Bitmap getBitmap(String url)
{
File f=fileCache.getFile(url);
//from SD cache
Bitmap b = decodeFile(f);
if(b!=null)
return b;
//from the web
try {
Bitmap bitmap;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is=conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Throwable ex){
ex.printStackTrace();
if(ex instanceof OutOfMemoryError)
memoryCache.clear();
return null;
}
}
//decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f){
try {
//decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE=70;
int width_tmp=o.outWidth, height_tmp=o.outHeight;
int scale=1;
while(true){
if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale*=2;
}
//decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {e.printStackTrace();}
return null;
}
//Task for the queue
private class PhotoToLoad
{
String url;
ImageView imageView;
PhotoToLoad(String u, ImageView i){
url=u;
imageView=i;
}
}
private class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad){
this.photoToLoad=photoToLoad;
}
#Override
public void run() {
if(imageViewReused(photoToLoad))
return;
Bitmap bmp=getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
if(imageViewReused(photoToLoad))
return;
BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
Activity a=(Activity)photoToLoad.imageView.getContext();
a.runOnUiThread(bd);
}
}
private boolean imageViewReused(PhotoToLoad photoToLoad){
String tag=imageViews.get(photoToLoad.imageView);
return tag == null || !tag.equals(photoToLoad.url);
}
//Used to display bitmap in the UI thread
private class BitmapDisplayer implements Runnable
{
Bitmap bitmap;
PhotoToLoad photoToLoad;
BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;}
public void run()
{
if(imageViewReused(photoToLoad))
return;
if(bitmap!=null)
photoToLoad.imageView.setImageBitmap(bitmap);
else
photoToLoad.imageView.setImageResource(stub_id);
}
}
}
Alternative solution using Glide
If I understand, through your link you get a list of images. Right?
To make requests to the server use the okhttp or volley library and return the result in JSON format. Then load the images using the glide library.
See this tutorial for volley https://www.simplifiedcoding.net/android-volley-tutorial-to-get-json-from-server/
This is glide library https://inthecheesefactory.com/blog/get-to-know-glide-recommended-by-google/en
So, add glide in your gradle
dependencies {
compile 'com.github.bumptech.glide:glide:3.5.2'
compile 'com.android.support:support-v4:22.0.0'
}
and instead of using ImageLoader, use this
Glide.with(context)
.load(resultp.get("RestPic"))
.into(imageView);
Related
I'm currently developing an Android application which can either load information from my website or use the information stored in an SQLite database. I'm trying to implement a search feature into it but I ran into a problem.
The data in my recyclerview doesn't update when a search is made. I've looked it up on Google many times but I still haven't found a solution. Is there a bright person here willing to help me?
MainActivity.java
public class MainActivity extends AppCompatActivity implements DienstAdapter.ListItemClickListener, NavigationView.OnNavigationItemSelectedListener {
private static final String DIENST_URL = "https://mywebsite.com/apps/test/dienstenapi.php";
private RecyclerView recyclerView;
private DienstAdapter adapter;
private List<Dienst> dienstList;
private SQLiteDatabase mDb;
private Cursor cursor;
private SharedPreferences sharedPreferences;
private NavigationView navigationView;
private View headerView;
private TextView gebruikersnaam;
private Resources res;
private SwipeRefreshLayout swiper;
private static Toast mToast = null;
private SearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = this.getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle(R.string.app_name);
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
headerView = navigationView.getHeaderView(0);
gebruikersnaam = headerView.findViewById(R.id.gebruikersnaam);
res = getResources();
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
sharedPreferences.registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener);
setupPreferenceGebruikersnaam();
swiper = findViewById(R.id.swiper);
swiper.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
dienstList.clear();
loadDiensten();
}
});
dienstList = new ArrayList<>();
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
DienstDbHelper dbHelper = new DienstDbHelper(this);
mDb = dbHelper.getWritableDatabase();
loadDiensten();
}
#Override
protected void onDestroy() {
sharedPreferences.unregisterOnSharedPreferenceChangeListener(sharedPreferenceChangeListener);
super.onDestroy();
}
SharedPreferences.OnSharedPreferenceChangeListener sharedPreferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals("example_text")){
setupPreferenceGebruikersnaam();
}
}
};
private void loadDienstenOnline() {
String moetInfoOphalen = sharedPreferences.getString("example_list", "1");
if (moetInfoOphalen.equals("1") || moetInfoOphalen.equals("0")) {
StringRequest stringRequest = new StringRequest(Request.Method.GET, DIENST_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray diensten = new JSONArray(response);
for (int i = 0; i < diensten.length(); i++) {
JSONObject dienstObject = diensten.getJSONObject(i);
int id = dienstObject.getInt("id");
String naam = dienstObject.getString("naam");
String beschrijving = dienstObject.getString("beschrijving");
String categorie = dienstObject.getString("categorie");
double prijs = dienstObject.getDouble("prijs");
String afbeelding = dienstObject.getString("afbeelding");
dienstList.add(new Dienst(id, naam, beschrijving, categorie, prijs, afbeelding));
}
voegDienstenToeAanDb(mDb, dienstList);
adapter = new DienstAdapter(MainActivity.this, dienstList, MainActivity.this);
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_LONG).show();
}
});
Volley.newRequestQueue(this).add(stringRequest);
} else {
loadDienstenOffline();
Toast.makeText(MainActivity.this, R.string.instelling_blokkeert_ophalen_diensten, Toast.LENGTH_LONG).show();
}
}
private void loadDienstenOffline() {
cursor = getAlleDiensten();
if ((cursor != null) && (cursor.getCount() > 0)) {
omzettenCursorNaarDiensten(cursor);
adapter = new DienstAdapter(MainActivity.this, dienstList, MainActivity.this);
recyclerView.setAdapter(adapter);
} else {
dienstList.add(new Dienst(0, "", "", "", 0, ""));
adapter = new DienstAdapter(MainActivity.this, dienstList, MainActivity.this);
recyclerView.setAdapter(adapter);
recyclerView.setVisibility(View.GONE);
if (mToast != null)
mToast.cancel();
mToast.makeText(this, R.string.internet_werkt_niet, Toast.LENGTH_LONG).show();
}
}
private boolean internetIsBeschikbaar() {
ConnectivityManager cm =(ConnectivityManager) this.getSystemService(CONNECTIVITY_SERVICE);
assert cm != null;
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}
private void loadDiensten() {
recyclerView.setVisibility(View.VISIBLE);
if (internetIsBeschikbaar()) {
loadDienstenOnline();
} else {
loadDienstenOffline();
}
swiper.setRefreshing(false);
}
#Override
public void onListItemClick(String url, String naam) {
Intent intent = new Intent(MainActivity.this, DienstActivity.class);
intent.putExtra(Intent.EXTRA_TEXT, url);
intent.putExtra("DienstNaam", naam);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
inflater.inflate(R.menu.search_menu, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setSearchableInfo(searchManager != null ? searchManager.getSearchableInfo(getComponentName()) : null);
searchView.setMaxWidth(Integer.MAX_VALUE);
// listening to search query text change
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// filter recycler view when query submitted
adapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String query) {
// filter recycler view when text is changed
adapter.getFilter().filter(query);
return false;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent startSettingsActivity = new Intent(this, SettingsActivity.class);
startActivity(startSettingsActivity);
return true;
} else if (id == R.id.action_search) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
return;
}
if (!searchView.isIconified()) {
searchView.setIconified(true);
return;
}
super.onBackPressed();
}
private static void voegDienstenToeAanDb(SQLiteDatabase db, List<Dienst> diensten){
if(db == null){
return;
}
List<ContentValues> list = new ArrayList<>();
ContentValues cv;
for (Dienst d : diensten) {
cv = new ContentValues();
cv.put(DienstContract.DienstEntry.COLUMN_NAAM, d.getNaam());
cv.put(DienstContract.DienstEntry.COLUMN_BESCHRIJVING, d.getBeschrijving());
cv.put(DienstContract.DienstEntry.COLUMN_CATEGORIE, d.getCategorie());
cv.put(DienstContract.DienstEntry.COLUMN_PRIJS, d.getPrice());
cv.put(DienstContract.DienstEntry.COLUMN_AFBEELDING, d.getAfbeelding());
list.add(cv);
}
try
{
db.beginTransaction();
//clear the table first
db.delete (DienstContract.DienstEntry.TABLE_NAME,null,null);
//go through the list and add one by one
for(ContentValues c : list){
db.insert(DienstContract.DienstEntry.TABLE_NAME, null, c);
}
db.setTransactionSuccessful();
}
catch (SQLException e) {
//too bad :(
}
finally
{
db.endTransaction();
}
}
private Cursor getAlleDiensten() {
return mDb.query(
DienstContract.DienstEntry.TABLE_NAME,
null,
null,
null,
null,
null,
DienstContract.DienstEntry._ID
);
}
private void omzettenCursorNaarDiensten(Cursor c) {
int teller = 0, id;
String naam, beschrijving, categorie, afbeelding;
double prijs;
while (c.moveToPosition(teller)) {
id = Integer.parseInt(c.getString(c.getColumnIndex(DienstContract.DienstEntry._ID)));
naam = c.getString(c.getColumnIndex(DienstContract.DienstEntry.COLUMN_NAAM));
beschrijving = c.getString(c.getColumnIndex(DienstContract.DienstEntry.COLUMN_BESCHRIJVING));
categorie = c.getString(c.getColumnIndex(DienstContract.DienstEntry.COLUMN_CATEGORIE));
prijs = c.getDouble(c.getColumnIndex(DienstContract.DienstEntry.COLUMN_PRIJS));
afbeelding = c.getString(c.getColumnIndex(DienstContract.DienstEntry.COLUMN_AFBEELDING));
dienstList.add(new Dienst(id, naam, beschrijving, categorie, prijs, afbeelding));
teller++;
}
}
private void setupPreferenceGebruikersnaam() {
String text = String.format(res.getString(R.string.welkomsbericht), sharedPreferences.getString("example_text", "gebruiker"));
gebruikersnaam.setText(text);
}
}
DienstAdapter.java
public class DienstAdapter extends RecyclerView.Adapter<DienstAdapter.DienstViewHolder> implements Filterable {
private Context mContext;
private List<Dienst> dienstList;
private List<Dienst> dienstListFiltered;
private final ListItemClickListener mOnClickListener;
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
dienstListFiltered = dienstList;
} else {
List<Dienst> filteredList = new ArrayList<>();
for (Dienst row : dienstList) {
// name match condition. this might differ depending on your requirement
// here we are looking for name or phone number match
if (row.getNaam().toLowerCase().contains(charString.toLowerCase()) || row.getBeschrijving().contains(charSequence)) {
filteredList.add(row);
}
}
dienstListFiltered = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = dienstListFiltered;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
dienstListFiltered = (ArrayList<Dienst>) filterResults.values;
notifyDataSetChanged();
}
};
}
public interface ListItemClickListener {
void onListItemClick(String url, String naam);
}
DienstAdapter(Context mContext, List<Dienst> dienstList, ListItemClickListener listener) {
this.mContext = mContext;
this.dienstList = dienstList;
this.dienstListFiltered = dienstList;
mOnClickListener = listener;
}
#Override
public DienstViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.list_layout, null);
return new DienstViewHolder(view);
}
#Override
public void onBindViewHolder(DienstViewHolder holder, int position) {
Dienst dienst = dienstList.get(position);
holder.tv_naam.setText(dienst.getNaam());
holder.tv_beschrijving.setText(dienst.getBeschrijving());
holder.tv_categorie.setText(String.valueOf(dienst.getCategorie()));
holder.tv_prijs.setText(String.valueOf(dienst.getPrice()));
if (dienst.getPrice() != 0)
holder.tv_prijs.setText(String.format("€ %.2f", dienst.getPrice()));
else
holder.tv_prijs.setText("");
Glide.with(mContext).load(dienst.getAfbeelding()).into(holder.iv_afbeelding);
}
#Override
public int getItemCount() {
return dienstList.size();
}
public class DienstViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView iv_afbeelding;
TextView tv_naam, tv_beschrijving, tv_categorie, tv_prijs;
DienstViewHolder(View itemView) {
super(itemView);
iv_afbeelding = itemView.findViewById(R.id.iv_afbeelding);
tv_naam = itemView.findViewById(R.id.tv_naam);
tv_beschrijving = itemView.findViewById(R.id.tv_beschrijving);
tv_categorie = itemView.findViewById(R.id.tv_categorie);
tv_prijs = itemView.findViewById(R.id.tv_prijs);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
int clickedPosition = getAdapterPosition();
String url = dienstList.get(clickedPosition).getAfbeelding().replace(".png", ".html");
String naam = dienstList.get(clickedPosition).getNaam();
mOnClickListener.onListItemClick(url, naam);
}
}
}
Firstly, getItemCount() and onBindViewHolder() should use the filtered list dienstListFiltered.
And You forgot to update the count of the FilterResults.
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
// Filter data ...
// ...
FilterResults filterResults = new FilterResults();
filterResults.values = dienstListFiltered;
filterResults.count = dienstListFiltered.size();
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
dienstListFiltered = (ArrayList<Dienst>) filterResults.values;
notifyDataSetChanged();
}
};
}
See: Custom Listview Adapter with filter Android
Can you add
notifyDataSetChanged();
immediately after
filteredList.add(row);
?
I am trying to make a basic shopping cart android application
Here is how the code looks
Items.java
public class Items extends AppCompatActivity {
private ListView lvUsers;
private ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub);
Intent intent = getIntent();
int subCategoryId = intent.getIntExtra("parameter_name", 1);
dialog = new ProgressDialog(this);
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.setMessage("Loading, please wait.....");
lvUsers = (ListView) findViewById(R.id.lvUsers);
String url = "http://146.185.178.83/resttest/subCategories/" + subCategoryId +"/items/";
new JSONTask().execute(url);
}
public class JSONTask extends AsyncTask<String, String, List<ItemModel> > {
#Override
protected void onPreExecute(){
super.onPreExecute();
dialog.show();
}
#Override
protected List<ItemModel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line ="";
while ((line=reader.readLine()) !=null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONArray parentArray = new JSONArray(finalJson);
List<ItemModel> itemModelList = new ArrayList<>();
Gson gson = new Gson();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
ItemModel itemModel = gson.fromJson(finalObject.toString(), ItemModel.class);
itemModelList.add(itemModel);
}
return itemModelList;
}catch (MalformedURLException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(connection !=null) {
connection.disconnect();
}
try {
if (reader !=null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<ItemModel> result) {
super.onPostExecute(result);
dialog.dismiss();
ItemAdapter adapter = new ItemAdapter(getApplicationContext(), R.layout.row_item, result);
lvUsers.setAdapter(adapter);
}
}
public class ItemAdapter extends ArrayAdapter {
public List<ItemModel> itemModelList;
private int resource;
private LayoutInflater inflater;
public ItemAdapter(Context context, int resource, List<ItemModel> objects) {
super(context, resource, objects);
itemModelList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView == null){
holder = new ViewHolder();
convertView=inflater.inflate(resource, null);
holder.tvItemName = (TextView) convertView.findViewById(R.id.tvItemName);
holder.tvPrice = (TextView) convertView.findViewById(R.id.tvPrice);
convertView.setTag(holder);
}else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvItemName.setText(itemModelList.get(position).getItemName());
holder.tvPrice.setText("Rs " + itemModelList.get(position).getSalesRate());
final String itemName = itemModelList.get(position).getItemName();
final String salesRate = itemModelList.get(position).getSalesRate();
Intent intent = new Intent(Items.this, CartDisplay.class);
intent.putExtra("itemName", itemName);
intent.putExtra("salesRate", salesRate);
return convertView;
}
class ViewHolder{
private TextView tvItemName;
private TextView tvPrice;
}
}
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem add_item = menu.findItem(R.id.action_add_item);
add_item.setVisible(false);
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.testmenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.action_show_cart:
cartMenuItem();
break;
}
return true;
}
private void cartMenuItem() {
Intent intent = new Intent(Items.this, CartDisplay.class);
startActivity(intent);
finish();
}
}
CartDisplay.java
public class CartDisplay extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.row_cart_display);
TextView tvItemName = (TextView) findViewById(R.id.tvItemName);
TextView tvSalesRate = (TextView) findViewById(R.id.tvSalesRate);
TextView tvTotalAmount = (TextView) findViewById(R.id.tvTotalAmount);
Intent intent = getIntent();
String itemName = intent.getStringExtra("itemName");
tvItemName.setText(itemName);
String salesRate = intent.getStringExtra("salesRate");
tvSalesRate.setText("RS"+salesRate);
tvTotalAmount.setText("Total: RS"+salesRate);
}
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem show_cart = menu.findItem(R.id.action_show_cart);
show_cart.setVisible(false);
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.testmenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.action_add_item:
addMenuItem();
break;
}
return true;
}
private void addMenuItem() {
Intent intent = new Intent(this, Categories.class);
startActivity(intent);
finish();
}
}
Here is how the item layout looks
Here is how the CartDisplay layout looks
The issue at the moment is I am not able to send data to CartDisplay
Activity also I need help with implementing few other things
In Items Activity, how do I make EditText between - and + button to
show the number based on the clicks on + and - button it should not
go below zero (ie like no negative figures its like x1 or x2 or x3
etc)
When pressed on itemAddToCart button (its the cart button inside the
item list ) , it must add item to cart and not move to CartDisplay
activity , it must also send the no of items added (because its
needed there ie in CartDisplay layout needs to show this in EditText
there).
When there is an update in Cart (i.e like once we have Added an item
to cart) need to show update on cart icon on Action bar with little
+1 or where there is two items in cart +2 or anything similar , the cart icon is an menu_item if pressed here it will take you to
CartDisplay activity how to code this ?
Also how to code it to send info of multiple selected items to cart?
when pressed on cart icon it must show the updates and the last
activity must be paused ? now i have menu item in CartDisplay
Activity which will take me back to Items Activity , so i can add
more items to the cart , the process continues until i checkout or
Clear cart .
Also I need help to write code for Clear cart .
My project is open source at github there you can see my full code
I have a bunch of images from sdcard that are load asynchronously on a gridview. Everything works fine, but when accessing a multi select contextual action menu by long clicking in any image the entire activity reloads and all images are loaded again. How to prevent it?
Myadapter
public class PhotosGridViewImageAdapter extends BaseAdapter {
AsyncTaskLoadFiles myAsyncTaskLoadFiles;
public class AsyncTaskLoadFiles extends AsyncTask<Void, String, Void> {
File targetDirector;
PhotosGridViewImageAdapter myTaskAdapter;
public AsyncTaskLoadFiles(PhotosGridViewImageAdapter adapter) {
myTaskAdapter = adapter;
}
#Override
protected void onPreExecute() {
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory().getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + File.separator + AppConstant.PHOTO_ALBUM + File.separator;
targetDirector = new File(targetPath);
myTaskAdapter.clear();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
File[] files = targetDirector.listFiles();
Arrays.sort(files);
for (File file : files) {
publishProgress(file.getAbsolutePath());
if (isCancelled()) break;
}
return null;
}
#Override
protected void onProgressUpdate(String... values) {
myTaskAdapter.add(values[0]);
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Void result) {
myTaskAdapter.notifyDataSetChanged();
super.onPostExecute(result);
}
}
ArrayList<String> itemList = new ArrayList<String>();
void add(String path) {
itemList.add(path);
}
void clear() {
itemList.clear();
}
void remove(int index){
itemList.remove(index);
}
private Activity _activity;
private ArrayList<String> _filePaths = new ArrayList<String>();
private int imageWidth;
public PhotosGridViewImageAdapter(Activity activity, ArrayList<String> filePaths,
int imageWidth) {
this._activity = activity;
this._filePaths = filePaths;
this.imageWidth = imageWidth;
}
#Override
public int getCount() {
return this._filePaths.size();
}
#Override
public Object getItem(int position) {
return this._filePaths.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
final ImageView imageView;
if (convertView == null) {
imageView = new ImageView(_activity);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(imageWidth,
imageWidth));
convertView = imageView;
holder = new ViewHolder();
holder.image = imageView;
holder.position = position;
convertView.setTag(holder);
} else {
//imageView = (ImageView) convertView;
holder = (ViewHolder) convertView.getTag();
((ImageView)convertView).setImageBitmap(null);
}
new AsyncTask<ViewHolder, Void, Bitmap>() {
private ViewHolder v;
// get screen dimensions
#Override
protected Bitmap doInBackground(ViewHolder... params) {
v = params[0];
Bitmap image = decodeFile(_filePaths.get(position), imageWidth,
imageWidth);
//imageView.setImageBitmap(image);
return image;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
v.image.setImageBitmap(result);
}
}.execute(holder);
return convertView;
}
/*
* Resizing image size
*/
public Bitmap decodeFile(String filePath, int WIDTH, int HEIGHT) {
try {
File f = new File(filePath);
if(filePath.contains(".jpg")) {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
final int REQUIRED_WIDTH = WIDTH;
final int REQUIRED_HEIGHT = HEIGHT;
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_WIDTH
&& o.outHeight / scale / 2 >= REQUIRED_HEIGHT)
scale *= 2;
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
}else if(filePath.contains(".mp4")){
return ThumbnailUtils.createVideoThumbnail(filePath, 0);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
class ViewHolder {
ImageView image;
int position;
}
}
Contextual action menu code
public class MultiChoiceModeListener implements
GridView.MultiChoiceModeListener {
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.contextual_action_menu, menu);
//mode.setTitle("Select Items");
mode.setTitle("1 item selected");
return true;
}
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return true;
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// Respond to clicks on the actions in the CAB
switch (item.getItemId()) {
case R.id.delete:
SparseBooleanArray checked = gridView.getCheckedItemPositions();
try {
int len = checked.size();
for (int i = 0; i < len; i++) {
if (checked.valueAt(i)) {
Integer position = checked.keyAt(i);
//deleteToMessageHistory(position);
}
}
}catch (Exception i){
Toast.makeText(PhotosGridViewActivity.this, "Message was not deleted. Try again.", Toast.LENGTH_SHORT).show();
}
mode.finish(); // Action picked, so close the CAB
return true;
default:
return false;
}
}
public void onDestroyActionMode(ActionMode mode) {
}
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked) {
int selectCount = gridView.getCheckedItemCount();
switch (selectCount) {
case 1:
mode.setTitle("1 item selected");
break;
default:
mode.setTitle("" + selectCount + " items selected");
break;
}
}
}
I appreciate any help!
==UPDATE==
Here is the MainActivity code:
public class PhotosGridViewActivity extends Activity {
private PhotosUtils utils;
private ArrayList<String> imagePaths = new ArrayList<String>();
private PhotosGridViewImageAdapter adapter;
private GridView gridView;
private int columnWidth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initilizing Grid View
InitilizeGridLayout();
}
private void InitilizeGridLayout() {
setContentView(R.layout.photos_grid_view);
utils = new PhotosUtils(PhotosGridViewActivity.this);
gridView = (GridView) findViewById(R.id.grid_view);
// loading all image paths from SD card
imagePaths = utils.getFilePaths();
Resources r = getResources();
float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
AppConstant.GRID_PADDING, r.getDisplayMetrics());
columnWidth = (int) ((utils.getScreenWidth() - ((AppConstant.NUM_OF_COLUMNS + 1) * padding)) / AppConstant.NUM_OF_COLUMNS);
gridView.setNumColumns(AppConstant.NUM_OF_COLUMNS);
gridView.setColumnWidth(columnWidth);
gridView.setStretchMode(GridView.NO_STRETCH);
gridView.setPadding((int) padding, (int) padding, (int) padding,
(int) padding);
gridView.setHorizontalSpacing((int) padding);
gridView.setVerticalSpacing((int) padding);
gridView.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE_MODAL);
gridView.setMultiChoiceModeListener(new MultiChoiceModeListener());
// Gridview adapter
adapter = new PhotosGridViewImageAdapter(PhotosGridViewActivity.this, imagePaths,
columnWidth);
// setting grid view adapter
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
gridView.getItemAtPosition(position);
Intent i = new Intent(PhotosGridViewActivity.this, PhotosScreenViewActivity.class);
i.putExtra("position", position);
PhotosGridViewActivity.this.startActivity(i);
}
});
}
public class MultiChoiceModeListener implements
GridView.MultiChoiceModeListener {
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.contextual_action_menu, menu);
//mode.setTitle("Select Items");
mode.setTitle("1 item selected");
return true;
}
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return true;
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// Respond to clicks on the actions in the CAB
switch (item.getItemId()) {
case R.id.delete:
SparseBooleanArray checked = gridView.getCheckedItemPositions();
try {
int len = checked.size();
for (int i = 0; i < len; i++) {
if (checked.valueAt(i)) {
Integer position = checked.keyAt(i);
//deleteToMessageHistory(position);
}
}
}catch (Exception i){
Toast.makeText(PhotosGridViewActivity.this, "Message was not deleted. Try again.", Toast.LENGTH_SHORT).show();
}
mode.finish(); // Action picked, so close the CAB
return true;
default:
return false;
}
}
public void onDestroyActionMode(ActionMode mode) {
}
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked) {
int selectCount = gridView.getCheckedItemCount();
switch (selectCount) {
case 1:
mode.setTitle("1 item selected");
break;
default:
mode.setTitle("" + selectCount + " items selected");
break;
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(co.glurl.appoid.R.menu.photo_gallery, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.add:
/** Go to the user's add photos. */
startActivity(new Intent(this, PhotoIntentActivity.class));
break;
//case R.id.settings:
/** Go to the user's settings photos. */
// startActivity(new Intent(this, PhotoGridSettings.class));
// break;
default:
return super.onContextItemSelected(item);
}
return true;
}
}
My soluction. Thanks to #pushbit for guiding me through it.
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ImageView imageView = (ImageView) convertView;
if (imageView == null) {
imageView = new ImageView(_activity);
}
// Trigger the download of the URL asynchronously into the image view.
if(_filePaths.get(position).contains(".jpg")) {
Picasso.with(_activity)
.load(new File(_filePaths.get(position)))
.resize(imageWidth, imageWidth)
.centerCrop()
.tag(_activity)
.into(imageView);
}else if(_filePaths.get(position).contains(".mp4")){
VideoRequestHandler videoRequestHandler;
Picasso picassoInstance;
videoRequestHandler=new VideoRequestHandler();
picassoInstance = new Picasso.Builder(_activity.getApplicationContext())
.addRequestHandler(videoRequestHandler)
.build();
picassoInstance
.load(videoRequestHandler.SCHEME_VIDEO+":"+_filePaths.get(position))
.resize(imageWidth, imageWidth)
.centerCrop()
.tag(_activity)
.into(imageView);
}
return imageView;
}
public static boolean deleteToPhotoAlbum(Integer position) {
File file = new File(_filePaths.get(position));
boolean deleted = file.delete();
return deleted;
}
public class VideoRequestHandler extends RequestHandler {
public String SCHEME_VIDEO = "video";
#Override
public boolean canHandleRequest(Request data)
{
String scheme = data.uri.getScheme();
return (SCHEME_VIDEO.equals(scheme));
}
#Override
public Result load(Request data, int arg1) throws IOException
{
Bitmap bm = ThumbnailUtils.createVideoThumbnail(data.uri.getPath(), MediaStore.Images.Thumbnails.MINI_KIND);
return new Result(bm, Picasso.LoadedFrom.DISK);
}
}
I write client for kaltura media platform.
I have an activity "Video". In this activity I must display list of video with thumbnails
First of all, I download list of videos using kaltura api, and this works fine. Every video entry have a field thumbnailUrl, which point out to thumbnail for video.
When I download this thumbnails for videos, it's(thumbnails) downloads in incorrect order, some thumbnails not downloaded, some thumbnails repeated for other video, and some not downloaded.
This is code of callback if downloadind videos:
private void handleFetchvideoListTask(List<VideoObject> videoObjects){
LinearLayout videoListProgressBarContainer = (LinearLayout)mActivity.findViewById(R.id.videoListProgressBarContainer);
LinearLayout videoListViewContainer = (LinearLayout)mActivity.findViewById(R.id.videoListViewContainer);
videoListProgressBarContainer.setVisibility(View.GONE);
videoListViewContainer.setVisibility(View.VISIBLE);
ListView listView = (ListView)videoListViewContainer.findViewById(R.id.videoListView);
VideoListAdapter adapter = new VideoListAdapter((LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE));
adapter.setList(videoObjects);
listView.setAdapter(adapter);
DownloadThumbnailsTask task = new DownloadThumbnailsTask(videoObjects, adapter);
task.execute();
}
This is code of DownloadThumbnailsTask:
public class DownloadThumbnailsTask extends AsyncTask<List<VideoObject>, VideoObject, Void>{
private List<VideoObject> videoObjectList = null;
private List<VideoObject> toProcess = null;
private VideoListAdapter adapter = null;
public DownloadThumbnailsTask(List<VideoObject> videoObjectList, VideoListAdapter adapter){
this.videoObjectList = videoObjectList;
this.toProcess = new ArrayList<VideoObject>(videoObjectList);
this.adapter = adapter;
}
#Override
protected Void doInBackground(List<VideoObject>... lists) {
for(int i=0; i<toProcess.size(); i++){
VideoObject item = videoObjectList.get(i);
String urldisplay = item.getThumbnailUrl();
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
item.setThumbnail(mIcon11);
mIcon11 = null;
publishProgress(item);
}
return null;
}
#Override
protected void onProgressUpdate(VideoObject... values) {
if(values != null && values.length > 0){
VideoObject item = values[0];
videoObjectList.remove(item);
videoObjectList.add(item);
adapter.setList(videoObjectList);
adapter.notifyDataSetChanged();
}
}
#Override
protected void onPostExecute(Void aVoid) {
this.toProcess.clear();
this.toProcess = null;
}
}
This is code of adapter:
public class VideoListAdapter extends BaseAdapter {
private List<VideoObject> list;
private LayoutInflater layoutInflater;
public VideoListAdapter(LayoutInflater layoutInflater){
this.layoutInflater = layoutInflater;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return list.get(i).getId();
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if(view == null){
view = layoutInflater.inflate(R.layout.list_item_video, viewGroup, false);
}
ViewHolder viewHolder = new ViewHolder(view);
view.setTag(viewHolder);
VideoObject item = getVideoObjectItem(i);
viewHolder.duration.setText(item.getFormattedDuration());
viewHolder.title.setText(item.getName());
if(item.getThumbnail() != null){
viewHolder.thumbnail.setImageBitmap(item.getThumbnail());
}
return view;
}
private VideoObject getVideoObjectItem(int position){
return (VideoObject) getItem(position);
}
public List<VideoObject> getList() {
return list;
}
public void setList(List<VideoObject> list) {
this.list = list;
}
public static class ViewHolder {
public final ImageView thumbnail;
public final TextView title;
public final TextView duration;
public ViewHolder(View view) {
this.thumbnail = (ImageView)view.findViewById(R.id.imgVideoThumbnail);
this.title = (TextView)view.findViewById(R.id.txtVideoName);
this.duration = (TextView)view.findViewById(R.id.txtVideoDuration);
}
}
}
And this is result of my code:
I noticed two things:
Inside doInBackground you are waiting
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
to complete before downloading the next image.
Try this:
protected Void doInBackground(List<VideoObject>... lists) {
for(final int i=0; i<toProcess.size(); i++){
try {
new Thread(){
#Override
public void run() {
VideoObject item = videoObjectList.get(i);
String urldisplay = item.getThumbnailUrl();
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
item.setThumbnail(mIcon11);
publishProgress(item);
}
}.start();
} catch (Exception e) {
Log.e("Error", e.getMessage());
}
}
return null;
}
#Override
protected void onProgressUpdate(VideoObject... values) {
adapter.notifyDataSetChanged();
}
I think this two lines is the problem:
videoObjectList.remove(item);
videoObjectList.add(item);
You're removing an item and adding again at the bottom. Just call notifyDataSetChanged after setting the bitmap.
Inside getView you're creating a new ViewHolder every time.
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder viewHolder;
if(view == null){
view = layoutInflater.inflate(R.layout.list_item_video, viewGroup, false);
viewHolder = new ViewHolder(view);
view.setTag(viewHolder);
}else{
viewHolder = view.getTag();
}
VideoObject item = getVideoObjectItem(i);
viewHolder.duration.setText(item.getFormattedDuration());
viewHolder.title.setText(item.getName());
if(item.getThumbnail() != null){
viewHolder.thumbnail.setImageBitmap(item.getThumbnail());
}
return view;
}
Do you get anything in your logcat? Maybe opening the stream or decoding fails. Are the images large?
I'm getting two errors in eclipse:
GetXMLTask cannot be resolved to a type line 119:
which is
GetXMLTask task = new GetXMLTask(this);
as well as
mPager cannot be resolved line 151: onTabChanged(mPager.getAdapter(), mCurrentTabPosition, position);
I believe I've declared and called both GetXMLTask and mPager correctly so I'm not sure exactly what might be causing this.
Any suggestions are greatly appreciated.
Java Source:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.parser_main);
final ActionBar actionBar = getActionBar();
final ViewPager mPager = (ViewPager) findViewById(R.id.view_pager);
adapter.notifyDataSetChanged();
mPager.setAdapter(adapter);
actionBar.setCustomView(R.layout.actionbar_custom_view_home);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
drawerListViewItems = getResources().getStringArray(R.array.items);
drawerListView = (ListView) findViewById(R.id.left_drawer);
drawerListView.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_listview_item, drawerListViewItems));
mPager.setOnPageChangeListener(mPageChangeListener);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
drawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
);
drawerLayout.setDrawerListener(actionBarDrawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
_initMenu();
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
findViewsById();
listView.setOnItemClickListener(this);
GetXMLTask task = new GetXMLTask(this);
task.execute(new String[] { URL });
}
private void findViewsById() {
listView = (ListView) findViewById(R.id.videosListView);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
}
#Override
public void onClick(View view) {
class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT)
.show();
drawerLayout.closeDrawer(drawerListView);
}
}
mPageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
onTabChanged(mPager.getAdapter(), mCurrentTabPosition, position);
position = mCurrentTabPosition;
int oldPos = mPager.getCurrentItem();
Log.d("PK", "Page selected");
if (position > oldPos) {
System.out.print(position);
// Moving to the right
String playlist = "TheMozARTGROUP";
View vg = findViewById(R.layout.home);
vg.invalidate();
}
if (position > oldPos) {
System.out.print(position);
// Moving to the right
String playlist = "TheMozARTGROUP";
View vg = findViewById(R.layout.home);
vg.invalidate();
} else if (position < oldPos) {
// Moving to the Left
System.out.print(position);
String playlist = "TheMozARTGROUP";
View vg = findViewById(R.layout.home);
vg.invalidate();
}
mPager.setOnPageChangeListener(mPageChangeListener);
}
private void onTabChanged(PagerAdapter adapter,
int mCurrentTabPosition, int position) {
Log.d("PK", "Tab changed");
// TODO Auto-generated method stub
}
};
}
private void _initMenu() {
// TODO Auto-generated method stub
class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view,
int position, long id) {
Log.d("pk", "onItemClick");
// Highlight the selected item, update the title, and close the
// drawer
// update selected item and title, then close the drawer
drawerListView.setItemChecked(position, true);
setTitle("......");
Toast.makeText(getApplicationContext(), "Item Clicked",
Toast.LENGTH_SHORT).show();
// Toast.makeText(Home.this, text, Toast.LENGTH_LONG).show();
drawerLayout.closeDrawer(drawerListView);
}
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class ImagePagerAdapter extends PagerAdapter implements
ViewPager.OnPageChangeListener {
public ImagePagerAdapter(Activity act, int[] mImages,
String[] stringArra) {
imageArray = mImages;
activity = act;
stringArray = stringArra;
}
// this is your constructor
public ImagePagerAdapter() {
super();
}
private int[] mImages = new int[] { R.drawable.selstation_up_btn,
R.drawable.classical_up_btn, R.drawable.country_up_btn,
R.drawable.dance_up_btn, R.drawable.hiphop_up_btn,
R.drawable.island_up_btn, R.drawable.latin_up_btn,
R.drawable.pop_up_btn, R.drawable.samba_up_btn };
private String[] stringArray = new String[] { "vevo",
"TheMozARTGROUP", "TimMcGrawVEVO", "TiestoVEVO",
"EminemVEVO" };
#Override
public int getCount() {
return mImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = SAXParserAsyncTaskActivity.this;
ImageView imageView = new ImageView(context);
imageView.setScaleType(ScaleType.FIT_XY);
imageView.setImageResource(mImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
#Override
public void onPageScrollStateChanged(int pos) {
Log.d("PK", "onPageScrollStateChanged");
// Toast.makeText(getApplicationContext(),
// "onPageScrollStateChanged", Toast.LENGTH_SHORT).show();
// String playlist = "TheMozARTGROUP";
// new GetYouTubeUserVideosTask(responseHandler,
// playlist).execute();
// adapter.notifyDataSetChanged();
//
;
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
Log.d("PK", "onPageScrolled");
// TODO Auto-generated method stub
// Toast.makeText(getApplicationContext(), "onPageScrolled",
// Toast.LENGTH_SHORT).show();
}
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
Log.d("pk", "onPageSelected");
}
// private inner class extending AsyncTask
class GetXMLTask extends AsyncTask<String, Void, List<Cmd>> {
private Activity context;
public GetXMLTask(Activity context) {
this.context = context;
}
protected void onPostExecute(List<Cmd> videos) {
if (videos != null) {
listViewAdapter = new CustomListViewAdapter(context, videos);
listView.setAdapter(listViewAdapter);
} else {
Toast.makeText(getApplicationContext(),
"XML Video Feed is Null!", Toast.LENGTH_LONG)
.show();
}
}
private String getXmlFromUrl(String urlString) {
StringBuffer output = new StringBuffer("");
try {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(stream));
String s = "";
while ((s = buffer.readLine()) != null)
output.append(s);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return output.toString();
}
#Override
protected List<Cmd> doInBackground(String... urls) {
List<Cmd> videos = null;
String xml = null;
for (String url : urls) {
xml = getXmlFromUrl(url);
InputStream stream = new ByteArrayInputStream(
xml.getBytes());
videos = SAXXMLParser.parse(stream);
if (videos != null) {
for (Cmd cmd : videos) {
// String videoName = cmd.getVideoName();
}
}
}
return videos;
}
}
}
}
Two problems:
mPager is defined in onCreate() method and you are trying to use it in another method. You should declare it in class level outside any method.
GetXMLTask is an inner class of ImagePagerAdapter. so it is not visible outside it. move this definition into your main class outside ImagePagerAdapter or use it as ImagePagerAdapter.GetXMLTask