What I am doing::
I have three buttons
When I click any one of the button, it must clear adapter & Assign
the newvalues.
The newvalues must reflect in the listview
Problem::
My listview is not reflecting the changes onclick of Button
No log Errors
DisplayBuffet_NotifyDataSetChanged_Fragment.java
public class DisplayBuffet_NotifyDataSetChanged_Fragment extends Fragment implements View.OnClickListener{
// Declaration
static ListView xmlFragmentListView;
static View layout;
static DisplayBuffetAsyncTask downloadTask=null;
Button btnRating,btnPrice,btnDistance;
private FileCache fileCache=null;
private MemoryCache memoryCache=null;
DisplayBuffetAdapter listViewAdapter;
static Bundle bundle=null;
DisplayBuffet_Json_Fragment fragment=null;
ArrayList<HashMap<String, String>> arrayListBuffet=null;
FindMyBuffetDatabaseHelper mHelper=null;;
SQLiteDatabase database=null;
public static DisplayBuffet_NotifyDataSetChanged_Fragment newInstance(FileCache _fileCache,MemoryCache _memoryCache) {
DisplayBuffet_NotifyDataSetChanged_Fragment fragment = new DisplayBuffet_NotifyDataSetChanged_Fragment();
bundle = new Bundle();
bundle.putSerializable(FindMyBuffetConstants.BUFFET_FILECACHE_KEY, _fileCache);
bundle.putSerializable(FindMyBuffetConstants.BUFFET_MEMORYCACHE_KEY, _memoryCache);
fragment.setArguments(bundle);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Retain this fragment across configuration changes.
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
layout = inflater.inflate(R.layout.display_buffets_fragment,container, false);
return layout;
}
private void initViews() {
fileCache = (FileCache) getArguments().getSerializable(FindMyBuffetConstants.BUFFET_FILECACHE_KEY);
memoryCache = (MemoryCache) getArguments().getSerializable(FindMyBuffetConstants.BUFFET_MEMORYCACHE_KEY);
xmlFragmentListView = ((ListView) layout.findViewById(R.id.sortrestaurantlistview));
btnRating=(Button) getActivity().findViewById(R.id.btnRating);
btnPrice=(Button) getActivity().findViewById(R.id.btnPrice);
btnDistance=(Button) getActivity().findViewById(R.id.btnDistance);
}
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
}
#Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
arrayListBuffet = new ArrayList<HashMap<String, String>>();
mHelper = new FindMyBuffetDatabaseHelper(FindMyBuffetApplication.currentActivityContext);
database = mHelper.getWritableDatabase();
initViews();
btnRating.setOnClickListener(this);
btnPrice.setOnClickListener(this);
btnDistance.setOnClickListener(this);
setListViewAdapter();
}
#Override
public void onClick(View v) {
String strOrder="asc";
if (FindMyBuffetApplication.isRatingOrderByDesc == false && FindMyBuffetApplication.sortBy.equalsIgnoreCase(FindMyBuffetConstants.TAB_NAME_RATING)){
btnRating.setBackgroundResource(R.drawable.tab_button_foucs_asc);
btnPrice.setBackgroundResource(R.drawable.tab_button_default);
btnDistance.setBackgroundResource(R.drawable.tab_button_default);
}
else if (FindMyBuffetApplication.isPriceOrderByDesc == false && FindMyBuffetApplication.sortBy.equalsIgnoreCase(FindMyBuffetConstants.TAB_NAME_PRICE)){
btnPrice.setBackgroundResource(R.drawable.tab_button_foucs_asc);
btnRating.setBackgroundResource(R.drawable.tab_button_default);
btnDistance.setBackgroundResource(R.drawable.tab_button_default);
}
else if (FindMyBuffetApplication.isDistanceOrderByDesc == false && FindMyBuffetApplication.sortBy.equalsIgnoreCase(FindMyBuffetConstants.TAB_NAME_DISTANCE)){
btnDistance.setBackgroundResource(R.drawable.tab_button_foucs_asc);
btnRating.setBackgroundResource(R.drawable.tab_button_default);
btnPrice.setBackgroundResource(R.drawable.tab_button_default);
}
else if (FindMyBuffetApplication.isRatingOrderByDesc == true && FindMyBuffetApplication.sortBy.equalsIgnoreCase(FindMyBuffetConstants.TAB_NAME_RATING)){
btnRating.setBackgroundResource(R.drawable.tab_button_foucs_dec);
btnDistance.setBackgroundResource(R.drawable.tab_button_default);
btnPrice.setBackgroundResource(R.drawable.tab_button_default);
}
else if (FindMyBuffetApplication.isPriceOrderByDesc == true && FindMyBuffetApplication.sortBy.equalsIgnoreCase(FindMyBuffetConstants.TAB_NAME_PRICE)){
btnPrice.setBackgroundResource(R.drawable.tab_button_foucs_dec);
btnDistance.setBackgroundResource(R.drawable.tab_button_default);
btnRating.setBackgroundResource(R.drawable.tab_button_default);
}
else if (FindMyBuffetApplication.isDistanceOrderByDesc == true && FindMyBuffetApplication.sortBy.equalsIgnoreCase(FindMyBuffetConstants.TAB_NAME_DISTANCE)){
btnDistance.setBackgroundResource(R.drawable.tab_button_foucs_dec);
btnPrice.setBackgroundResource(R.drawable.tab_button_default);
btnRating.setBackgroundResource(R.drawable.tab_button_default);
}
switch(v.getId()) {
case R.id.btnRating:
FindMyBuffetApplication.sortBy = FindMyBuffetConstants.TAB_NAME_RATING;
if (FindMyBuffetApplication.isRatingOrderByDesc == false)
FindMyBuffetApplication.isRatingOrderByDesc = true;
else
FindMyBuffetApplication.isRatingOrderByDesc = false;
//displayView();
if(FindMyBuffetApplication.isRatingOrderByDesc==true)strOrder="desc";
sortListView(FindMyBuffetConstants.SORT_BY_RATING_1,strOrder);
break;
case R.id.btnPrice:
FindMyBuffetApplication.sortBy = FindMyBuffetConstants.TAB_NAME_PRICE;
if (FindMyBuffetApplication.isPriceOrderByDesc == false)
FindMyBuffetApplication.isPriceOrderByDesc = true;
else
FindMyBuffetApplication.isPriceOrderByDesc = false;
//displayView();
if(FindMyBuffetApplication.isPriceOrderByDesc==true)strOrder="desc";
sortListView(FindMyBuffetConstants.SORT_BY_PRICE_1,strOrder);
break;
case R.id.btnDistance:
FindMyBuffetApplication.sortBy = FindMyBuffetConstants.TAB_NAME_DISTANCE;
if (FindMyBuffetApplication.isDistanceOrderByDesc == false)
FindMyBuffetApplication.isDistanceOrderByDesc = true;
else
FindMyBuffetApplication.isDistanceOrderByDesc = false;
//displayView();
if(FindMyBuffetApplication.isPriceOrderByDesc==true)strOrder="desc";
sortListView(FindMyBuffetConstants.SORT_BY_DISTANCE_1,strOrder);
break;
}
}
private void setListViewAdapter(){
downloadTask = new DisplayBuffetAsyncTask();
if (FindMyBuffetApplication.sortBy == FindMyBuffetConstants.TAB_NAME_RATING){
if (FindMyBuffetApplication.isDownloading) {
downloadTask.initilizeAsyncTask(
getFragmentManager(), xmlFragmentListView,downloadTask,
fileCache,memoryCache);
downloadTask.execute();
}
}
else if (FindMyBuffetApplication.sortBy == FindMyBuffetConstants.TAB_NAME_PRICE){
if (FindMyBuffetApplication.isDownloading) {
downloadTask.initilizeAsyncTask(
getFragmentManager(), xmlFragmentListView,
downloadTask,
fileCache,memoryCache);
downloadTask.execute();
}
}
else if (FindMyBuffetApplication.sortBy == FindMyBuffetConstants.TAB_NAME_DISTANCE){
if (FindMyBuffetApplication.isDownloading) {
downloadTask.initilizeAsyncTask(
getFragmentManager(), xmlFragmentListView,
downloadTask,
fileCache,memoryCache);
downloadTask.execute();
}
}
listViewAdapter = new DisplayBuffetAdapter(arrayListBuffet, fileCache,memoryCache);
xmlFragmentListView.setAdapter(listViewAdapter);
}
private void sortListView(String strSortBy,String strOrder) {
arrayListBuffet.clear();
if (FindMyBuffetApplication.sortBy == FindMyBuffetConstants.TAB_NAME_RATING) {
SortBuffets(FindMyBuffetConstants.SORT_BY_RATING_1, strOrder);
} else if (FindMyBuffetApplication.sortBy == FindMyBuffetConstants.TAB_NAME_PRICE) {
SortBuffets(FindMyBuffetConstants.SORT_BY_PRICE_1, strOrder);
} else if (FindMyBuffetApplication.sortBy == FindMyBuffetConstants.TAB_NAME_DISTANCE) {
SortBuffets(FindMyBuffetConstants.SORT_BY_DISTANCE_1, strOrder);
}
listViewAdapter.notifyDataSetChanged();
}
/*#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
}
#Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
}*/
private void displayView() {
Fragment objFragment = getFragmentManager().findFragmentById(getId());
if (objFragment != null) {
getFragmentManager().beginTransaction().remove(objFragment).commit();
//objFragment = new SortBuffetRating();
objFragment = DisplayBuffet_Json_Fragment.newInstance(fileCache,memoryCache);
getFragmentManager().beginTransaction().add(R.id.frame_container, objFragment).commit();
} else {
//objFragment = new SortBuffetRating();
objFragment = DisplayBuffet_Json_Fragment.newInstance(fileCache,memoryCache);
getFragmentManager().beginTransaction().add(R.id.frame_container, objFragment).commit();
}
}
/*
* Displays data from SQLite
*/
private void SortBuffets(String strSortBy,String strOrder){
Cursor mCursor = database.rawQuery("select * from " + BuffetTable.TABLE_NAME_BUFFET + " order by " + strSortBy +" "+strOrder, null);
try {
// looping through all rows and adding to list
if (mCursor.moveToFirst()) {
do {
HashMap<String, String> map=new HashMap<String, String>();
map.put(BuffetTable.COLUMN_ID,mCursor.getString(0));
map.put(BuffetTable.COLUMN_BUF_OFF_ID,mCursor.getString(1));
map.put(BuffetTable.COLUMN_FROM_TIME,mCursor.getString(2));
map.put(BuffetTable.COLUMN_TO_TIME,mCursor.getString(3));
map.put(BuffetTable.COLUMN_ONLINE_PRICE,mCursor.getString(4));
map.put(BuffetTable.COLUMN_RESERVED_PRICE,mCursor.getString(5));
map.put(BuffetTable.COLUMN_BUF_IMAGE_FILE_NAME,mCursor.getString(6));
map.put(BuffetTable.COLUMN_RES_NAME,mCursor.getString(7));
map.put(BuffetTable.COLUMN_RATING,mCursor.getString(8));
map.put(BuffetTable.COLUMN_LATITUDE,mCursor.getString(9));
map.put(BuffetTable.COLUMN_LONGITUDE,mCursor.getString(10));
map.put(BuffetTable.COLUMN_BUF_TYPE_NAME,mCursor.getString(11));
arrayListBuffet.add(map);
} while (mCursor.moveToNext());
}
}catch (SQLiteException e){
Log.i(FindMyBuffetApplication.applicationName+"."+FindMyBuffetConstants.PACKAGE_NAME+"."+FindMyBuffetConstants.PACKAGE_NAME,"Error Druing Sorting Buffets "+ e.getMessage());
e.printStackTrace();
Toast.makeText(FindMyBuffetApplication.currentActivityContext, "Error Druing Sorting The Buffets By" +strSortBy,Toast.LENGTH_LONG).show();
}catch (Exception e) {
Log.i(FindMyBuffetApplication.applicationName+"."+FindMyBuffetConstants.PACKAGE_NAME+"."+FindMyBuffetConstants.PACKAGE_NAME,"Error Druing Sorting Buffets "+ e.getMessage());
e.printStackTrace();
Toast.makeText(FindMyBuffetApplication.currentActivityContext, "Error Druing Sorting The Buffets By" +strSortBy,Toast.LENGTH_LONG).show();
}finally {
// Release the memory
mCursor.close();
}
}
#Override
public void onDestroy() {
super.onDestroy();
database.close();
//layout = null; // now cleaning up!
//bundle = null;
/*fragment = null;
if (downloadTask != null && downloadTask.getStatus() != AsyncTask.Status.FINISHED)
downloadTask=null;*/
}
}
DisplayBuffetAdapter.java
public class DisplayBuffetAdapter extends BaseAdapter {
// Declare Variables
ImageLoader imageLoader;
ArrayList<HashMap<String, String>> arrayListBuffet;
LayoutInflater inflater;
FileCache fileCache=null;
MemoryCache memoryCache=null;
int tmpLoopCnt=0;
public DisplayBuffetAdapter(ArrayList<HashMap<String, String>> _arraylist,FileCache _fileCache,MemoryCache _memoryCache) {
this.arrayListBuffet = _arraylist;
this.fileCache=_fileCache;
this.memoryCache=_memoryCache;
this.imageLoader=new ImageLoader(FindMyBuffetApplication.currentActivityContext,fileCache,memoryCache);
tmpLoopCnt=0;
}
public int getCount() {
return arrayListBuffet.size();
}
public Object getItem(int position) {
return arrayListBuffet.get(position);
}
public long getItemId(int position) {
return position;
}
private class ViewHolder {
// Declare Variables
ImageView imgRestBuffLogo;
TextView txtResName;
TextView txtRestBufType;
TextView txtRestTime;
TextView txtRestDistance;
TextView txtReservePrice;
TextView txtOnlinePrice;
RatingBar restRatingBar;
Button btnOnlinePrice;
Button btnReservedPrice;
}
public View getView(int position, View convertView, ViewGroup parent) {
tmpLoopCnt = tmpLoopCnt + 1;
Log.i("LIST VIEW ADAPATER COUNT", ""+tmpLoopCnt);
ViewHolder holder;
LayoutInflater inflater;
if (convertView == null) {
inflater = (LayoutInflater) FindMyBuffetApplication.currentActivityContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.display_buffet_listview, null);
holder = new ViewHolder();
Typeface txtResnameFontFace=Typeface.createFromAsset(FindMyBuffetApplication.currentActivityContext.getAssets(), "Roboto-Bold.ttf");
Typeface txtRestBufTypeFontFace=Typeface.createFromAsset(FindMyBuffetApplication.currentActivityContext.getAssets(), "Roboto-Medium.ttf");
Typeface txtRestTimeFontFace=Typeface.createFromAsset(FindMyBuffetApplication.currentActivityContext.getAssets(), "Roboto-Bold.ttf");
//Typeface txtReservePrice=Typeface.createFromAsset(FindMyBuffetApplicationCls.currentActivityContext.getAssets(),"Roboto-Bold.ttf");
//Typeface txtOnlinePrice=Typeface.createFromAsset(FindMyBuffetApplicationCls.currentActivityContext.getAssets(),"Roboto-Bold.ttf");
Typeface btnPrice=Typeface.createFromAsset(FindMyBuffetApplication.currentActivityContext.getAssets(), "Roboto-Bold.ttf");
Typeface txtRestDistanceFontFace=Typeface.createFromAsset(FindMyBuffetApplication.currentActivityContext.getAssets(),"Roboto-Light.ttf");
// Locate the TextViews in listview_item.xml
holder.txtResName = (TextView) convertView.findViewById(R.id.txtRestName);
holder.txtResName.setTypeface(txtResnameFontFace);
holder.txtRestBufType = (TextView) convertView.findViewById(R.id.txtRestBufType);
holder.txtRestBufType.setTypeface(txtRestBufTypeFontFace);
holder.txtRestTime = (TextView) convertView.findViewById(R.id.txtRestTime);
holder.txtRestTime.setTypeface(txtRestTimeFontFace);
holder.txtRestDistance = (TextView) convertView.findViewById(R.id.txtRestDistance);
holder.txtRestDistance.setTypeface(txtRestDistanceFontFace);
holder.restRatingBar=(RatingBar) convertView.findViewById(R.id.restRatingBar);
//holder.txtReservePrice = (TextView) convertView.findViewById(R.id.txtReservePrice);
//holder.txtReservePrice.setTypeface(txtReservePrice);
//holder.txtOnlinePrice = (TextView) convertView.findViewById(R.id.txtOnlinePrice);
//holder.txtOnlinePrice.setTypeface(txtOnlinePrice);
holder.btnOnlinePrice=(Button) convertView.findViewById(R.id.btnOnlinePrice);
holder.btnOnlinePrice.setTypeface(btnPrice);
holder.btnReservedPrice=(Button) convertView.findViewById(R.id.btnReservedPrice);
holder.btnOnlinePrice.setTypeface(btnPrice);
// Locate the ImageView in listview_item.xml
holder.imgRestBuffLogo = (ImageView) convertView.findViewById(R.id.imgRestBuffetLogo);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
HashMap<String, String> objMap= arrayListBuffet.get(position);
holder.txtResName.setText(objMap.get(BuffetTable.COLUMN_RES_NAME));
holder.txtRestBufType.setText(objMap.get(BuffetTable.COLUMN_BUF_TYPE_NAME));
holder.restRatingBar.setRating(Float.valueOf(objMap.get(BuffetTable.COLUMN_RATING)));
holder.txtRestTime.setText(formatTime(objMap.get(BuffetTable.COLUMN_FROM_TIME))+" to "+formatTime(objMap.get(BuffetTable.COLUMN_TO_TIME)));
//txtOnlinePrice.setText(objMap.get("Online_Price"));
//txtReservePrice.setText(objMap.get("Reserved_Price"));
holder.btnOnlinePrice.setText(" Buy Now\n "+"Rs."+objMap.get(BuffetTable.COLUMN_ONLINE_PRICE)+" ");
holder.btnReservedPrice.setText(" Reserve\n "+"Rs."+objMap.get(BuffetTable.COLUMN_RESERVED_PRICE)+" ");
//double dist=objMap.get("Latitude")-objMap.get("Longitude");
//txtRestDistance.setText(String.valueOf(dist));
holder.txtRestDistance.setText(""+10+position+" Km");
String strUrl=FindMyBuffetApplication.URL+FindMyBuffetConstants.WEB_SERVER_PATH_BUF_IMAGE+objMap.get(BuffetTable.COLUMN_BUF_IMAGE_FILE_NAME);
imageLoader.DisplayImage(strUrl,holder.imgRestBuffLogo);
return convertView;
}
private String formatTime(String strTime){
//example For hour,minutes and seconds
// String strTime = "15:30:18 pm";
//SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss a");
strTime=strTime.substring(0,5)+" am";
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");
Date date = null;
try {
date = sdf.parse(strTime);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sdf.format(date);
}
}
in private void sortListView(
before calling notifyDataSetChanged, you should submit the new dataset to your adapter. Otherwise you are only chaining the data inside the fragment. You could this both creating a new Adapter and calling setListAdapter again, or creating a method inside the Adapter to update the dataset. For instance:
public void updateData(ArrayList<HashMap<String, String>> _arraylist) {
this.arrayListBuffet = _arraylist;
}
and call it before
listViewAdapter.notifyDataSetChanged();
When you sort you are in fact adding to arrayListBuffet but that may not be your only problem. What you're doing is sorting an array that's not inside the adapter, you need to pass the newly sorted data, in your case arrayListBuffet back to the adapter before calling notifyDataSetChanged
Why? Because if you don't, the data that the adapter is using is still the one from when you initialised it, and therefore you'll see no changes. In other words, you didn't really change the dataset it's using.
How? You can create a method in your adapter and pass the newly sorted data source as a parameter, replacing the original content, you can actually call the notifyDataSetChanged from within that same method.
Code
In your adapter:
public void updateDataSource(ArrayList<HashMap<String, String>> sortedArrayListBuffet) {
this.arrayListBuffet = sortedArrayListBuffet;
this.notifyDataSetChanged();
}
Related
I populated a GridView with a Custom Adapter of images. I added a button to sort the images. I'm trying to figure out how to do this properly. As of right now, I'm trying to delete all the images by using the clear() method and repopulating it with the sorted images. However, I can't seem to delete the images. It just adds to the sorted images to the original. Please help
public class MainActivity extends AppCompatActivity {
private ImageView mImageView;
private TextView mTextView;
String githubSearchResults;
String default_sort = "http://api.themoviedb.org/3/movie/top_rated?api_key=(MY OWN API KEY)";
ArrayList<String> listdata = new ArrayList<String>();
List<String> posterData = new ArrayList<String>();
JSONObject results;
private MovieAdapter movieAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = (ImageView) findViewById(R.id.movie_image);
getURL(default_sort);
}
JSONArray getResults(String JSONString) throws JSONException {
JSONObject movieResults = new JSONObject(JSONString);
JSONArray jArray = (JSONArray)movieResults.getJSONArray("results");
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
listdata.add(jArray.getString(i));
}
}
return jArray;
}
void getPosterPath() throws JSONException {
for(int i = 0;i<listdata.size();i++) {
results = new JSONObject(listdata.get(i));
String poster_path = results.getString("poster_path");
posterData.add(poster_path);
Log.d("myTag", poster_path);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.sort_popular, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.popular:
movieAdapter.clear();
movieAdapter.notifyDataSetChanged();
String sort_popular = "http://api.themoviedb.org/3/movie/popular?api_key=(MY OWN API KEY)";
getURL(sort_popular);
return true;
default:
super.onOptionsItemSelected(item);
}
return true;
}
private void getURL(String string){
URL getURL = NetworkUtils.buildUrl(string);
new GithubQueryTask().execute(getURL);
}
public class GithubQueryTask extends AsyncTask<URL, Void, String> {
// COMPLETED (2) Override the doInBackground method to perform the query. Return the results. (Hint: You've already written the code to perform the query)
#Override
protected String doInBackground(URL... params) {
URL searchUrl = params[0];
String githubSearchResults = null;
try {
githubSearchResults = NetworkUtils.getResponseFromHttpUrl(searchUrl);
getResults(githubSearchResults);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return githubSearchResults;
}
// COMPLETED (3) Override onPostExecute to display the results in the TextView
#Override
protected void onPostExecute(String githubSearchResults) {
try {
getPosterPath();
} catch (JSONException e) {
e.printStackTrace();
}
movieAdapter = new MovieAdapter(MainActivity.this, posterData);
GridView listView = (GridView) findViewById(R.id.listview_flavor);
listView.setAdapter(movieAdapter);
}
}
}
Here's my custom adapter:
public class MovieAdapter extends ArrayAdapter<String> {
private ImageView mImageView;
public MovieAdapter(Activity context, List<String> movieArray) {
super(context, 0, movieArray);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
String androidFlavor = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.activity_detail, parent, false);
}
mImageView= (ImageView) convertView.findViewById(R.id.movie_image);
Picasso.with(getContext()).load("http://image.tmdb.org/t/p/w185/"+androidFlavor).into(mImageView);
return convertView;
}
}
If I'm not mistaking, the problem is you never clear posterData list (what about listdata as well). You just keep adding to it. I would suggest to change the getPosterPath method like this:
void getPosterPath() throws JSONException {
posterData.Clear();
for(int i = 0;i<listdata.size();i++) {
results = new JSONObject(listdata.get(i));
String poster_path = results.getString("poster_path");
posterData.add(poster_path);
Log.d("myTag", poster_path);
}
movieAdapter.notifyDataSetChanged();
}
And in public boolean onOptionsItemSelected you don't need to call
movieAdapter.clear();
movieAdapter.notifyDataSetChanged();
since any change in the list the adapter is bound to should reflect in the adapter after getPosterPath() gets executed.
EDIT:
The reason you get this error is because
movieAdapter = new MovieAdapter(MainActivity.this, posterData);
happens after the call to getPosterPath().
Just alter the onPostExectute() a bit:
protected void onPostExecute(String githubSearchResults) {
movieAdapter = new MovieAdapter(MainActivity.this, posterData);
try {
getPosterPath();
} catch (JSONException e) {
e.printStackTrace();
}
GridView listView = (GridView) findViewById(R.id.listview_flavor);
listView.setAdapter(movieAdapter);
}
I've been working on an app that downloads thumbnails and text from Parse and adds it to ArrayLists which are then displayed through a custom adapter for a ListView. The issue here is, the thumbnails for the required content is sometimes misplaced. For example: In my profile, instead of my pic another pic downloaded from parse would be placed. How to fix it ?
MainActivity.java ( Downloads the content )
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (isParseInitialized == false) {
Parse.initialize(new Parse.Configuration.Builder(this)
.applicationId("AppId")
.clientKey("ClientKey")
.server("https://parseapi.back4app.com")
.build()
);
isParseInitialized = true;
}
catchVideos();
progressBar = (ProgressBar) findViewById(R.id.progressBar);
context = this;
listView = (ListView) findViewById(R.id.listView);
customAdapter = new CustomAdapter(MainActivity.this, titles, thumbnails, channel);
//progressBar.setVisibility(View.INVISIBLE);
final Handler handler = new Handler();
Runnable run = new Runnable() {
#Override
public void run() {
handler.postDelayed(this, 1000);
if (tapped == true) {
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Content");
query.whereEqualTo("Title", title);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if(e == null) {
for (ParseObject object : objects) {
Log.i("Info", object.getString("url"));
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(object.getString("url")));
startActivity(intent);
}
}
}
});
tapped = false;
}
}
};
handler.post(run);
}
public void catchVideos(){
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Content");
query.whereNotEqualTo("Status", null);
query.orderByDescending("createdAt");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if(e == null) {
if (!titles.isEmpty()) {
titles.clear();
}
if (!channel.isEmpty()) {
channel.clear();
}
if (!thumbnails.isEmpty()) {
thumbnails.clear();
}
for (ParseObject object : objects) {
titles.add(object.getString("Title"));
channel.add(object.getString("Channel"));
ParseFile file = (ParseFile) object.get("Thumbnail");
file.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] data, ParseException e) {
if (e == null) {
Bitmap thumbnail = BitmapFactory.decodeByteArray(data, 0, data.length);
thumbnails.add(thumbnail);
listView.setAdapter(customAdapter);
progressBar.setVisibility(View.INVISIBLE);
}
}
});
customAdapter.notifyDataSetChanged();
Log.i("Info", object.getString("Title"));
Log.i("Info", object.getString("url"));
}
}
}
});
}
CustomAdapter.java
public class CustomAdapter extends BaseAdapter{
ArrayList<String> result;
ArrayList<String> channelName;
Context context;
ArrayList<Bitmap> imageId;
private static LayoutInflater inflater=null;
public CustomAdapter(MainActivity mainActivity, ArrayList<String> titles, ArrayList<Bitmap> thumbnails, ArrayList<String> channel) {
// TODO Auto-generated constructor stub
result=titles;
channelName=channel;
context=mainActivity;
imageId=thumbnails;
inflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return result.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder
{
TextView tv;
TextView channelText;
ImageView img;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder=new Holder();
View rowView;
rowView = inflater.inflate(R.layout.custom_row, null);
holder.tv=(TextView) rowView.findViewById(R.id.textView1);
holder.channelText = (TextView) rowView.findViewById(R.id.channel);
holder.img=(ImageView) rowView.findViewById(R.id.imageView1);
try {
holder.img.setImageBitmap(imageId.get(position));
} catch (Exception e) {
e.printStackTrace();
}
holder.tv.setText(result.get(position));
holder.channelText.setText(channelName.get(position));
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(context, "You Clicked "+ result.get(position), Toast.LENGTH_LONG).show();
//Launch URL
MainActivity.tapped = true;
MainActivity.title = result.get(position);
}
});
return rowView;
}
}
You're adding each image to a list once it is downloaded. Later, you're iterating over the images in order. However, the order that they appear in the list won't necessarily be the same as the order you requested them. They're being loaded asynchronously, meaning that the code doesn't wait for the image to finish loading before moving on to the next one. If you start loading a large image and then start loading a small image immediately afterwards, the small one might finish downloading first. In the resulting list, the small image would appear before the larger one, even though it was requested second.
To fix the order of the list of images, you could use Futures. Instead of declaring thumbnails as a List<Bitmap>, make it a List<Future<Bitmap>>. Then, add all three items to the list at the same time.
titles.add(object.getString("Title"));
channel.add(object.getString("Channel"));
CompletableFuture<Bitmap> futureThumbnail = new CompletableFuture<>();
thumbnails.add(futureThumbnail);
That guarantees all three lists will be in the same order, regardless of how long the images take to download.
The next step is to fill in each future with the corresponding image.
ParseFile file = (ParseFile) object.get("Thumbnail");
file.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] data, ParseException e) {
if (e == null) {
Bitmap thumbnail = BitmapFactory.decodeByteArray(data, 0, data.length);
future.complete(thumbnail);
...
This method has the added benefit that you can wait for the images to finish downloading. To wait for all the images to download and put them in a list in the right order:
List<Bitmap> thumbnails = new ArrayList<>();
for (Future<Bitmap> future : futureThumbnails) {
thumbnails.add(future.get());
}
Or, if you prefer not to wait:
List<Bitmap> thumbnails = new ArrayList<>();
Bitmap defaultValue = null; // or preferably some other default value
for (Future<Bitmap> future : futureThumbnails) {
thumbnails.add(future.isDone() ? future.get() : defaultValue);
}
I have a list of musics, so I want user to set time to play music in particular time.
here I have a list view that has a text view (is invisible at first) and a button.
when I click on the button an alert dialog open to show device time and a time picker.
I subtract these times and sent the result to the Count Down Timer, In on Tick
i set my text view visible to show time to user until to finish the time.
all things are correct
user can play music after the time which sets.
but when I scroll the list view ,my text view (show the timer )disappeared.
here is my code:
public class Main extends Activity {
public static int hour_device, minute_device;
public static int hour_user, minute_user;
Splash splash;
ListView listView;
Adaptor adaptor;
private MediaPlayer mediaPlayer;
static View lastview = null;
static MyIndexStore indexStore;
List<String> lines1 = new ArrayList<String>();
List<String> lines2 = new ArrayList<String>();
static List<String> array_audio = new ArrayList<String>();
InputStream in;
BufferedReader reader;
String line = "1";
String[] tracks;
String[] names;
String[] infos;
HashMap<Integer,String> textMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
indexStore = new MyIndexStore(getApplicationContext());
setContentView(R.layout.main_activity);
splash = new Splash(this);
splash.set_identity("1");
initiate();
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.a1);
//lastview = null;
listView = (ListView) findViewById(R.id.list);
ReadText1();
names = lines1.toArray(new String[0]);// = {"track one","the seconnd track","a nice track","name name name","the seconnd track","a nice track","name name name"};
ReadText2();
infos = lines2.toArray(new String[0]);
tracks = array_audio.toArray(new String[0]);
adaptor = new Adaptor(getApplicationContext(), tracks, names, infos,textMap);
listView.setAdapter(adaptor);
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer arg0) {
if (lastview != null) {
ImageView play = (ImageView) lastview.findViewById(R.id.play_stop);
play.setImageResource(R.drawable.n_btn_play_unselected);
}
}
});
}
private static void initiate() {
Field[] fields = R.raw.class.getFields();
array_audio.clear();
for (int count = 0; count < fields.length; count++) {
array_audio.add("a" + (count + 1));
}
}
private void play(int index) {
mediaPlayer.release();
index++;
String s = "a" + index;
Resources resources = getResources();
final int resourceId = resources.getIdentifier(s, "raw", getPackageName());
try {
mediaPlayer = MediaPlayer.create(this, resourceId);
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onPause() {
mediaPlayer.release();
listView.invalidateViews();
super.onPause();
}
private void ReadText1() {
lines1.clear();
line = "1";
try {
in = this.getAssets().open("names.txt");
reader = new BufferedReader(new InputStreamReader(in));
while (line != null) {
line = reader.readLine();
if (line != null)
lines1.add(line);
else
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void ReadText2() {
lines2.clear();
line = "1";
try {
in = this.getAssets().open("infos.txt");
reader = new BufferedReader(new InputStreamReader(in));
while (line != null) {
line = reader.readLine();
if (line != null)
lines2.add(line);
else
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
public class Adaptor extends ArrayAdapter<String> {
private final Context context;
private final String[] tracks;
private final String[] names;
private final String[] infos;
private final HashMap<Integer,String> textMap;
Typeface type_face;
public Adaptor(Context context, String[] tracks, String[] names, String[] infos,HashMap<Integer,String> textMap) {
super(context, R.layout.track, tracks);
this.context = context;
this.tracks = tracks;
this.names = names;
this.infos = infos;
type_face = Typeface.createFromAsset(context.getAssets(), "BTitrBd.ttf");
this.textMap = textMap;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(R.layout.track, parent, false);
TextView name = (TextView) rowView.findViewById(R.id.track_name);
final TextView time = (TextView) rowView.findViewById(R.id.time);
//populate the textview from map
if(textMap!=null && textMap.get(new Integer(position))!=null){
time.setText(textMap.get(new Integer(position)));
}
name.setText(names[position]);
name.setTypeface(type_face);
name.setTypeface(type_face);
final ImageView ringtone = (ImageView) rowView.findViewById(R.id.ringtone);
if (position == indexStore.getindex())
ringtone.setImageResource(R.drawable.n_btn_ringtone_seted);
final ImageView play = (ImageView) rowView.findViewById(R.id.play_stop);
ringtone.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
LayoutInflater factory = LayoutInflater.from(Main.this);
final View deleteDialogView = factory.inflate(
R.layout.mylayout, null);
final AlertDialog deleteDialog = new AlertDialog.Builder(Main.this).create();
deleteDialog.setView(deleteDialogView);
TextView device_time = (TextView) deleteDialogView.findViewById(R.id.current_time);
Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
hour_device = hour;
minute_device = minute;
device_time.setText(hour_device + ":" + minute_device);
deleteDialogView.findViewById(R.id.set).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TimePicker timePicker = (TimePicker) deleteDialogView.findViewById(R.id.timepicker);
timePicker.setIs24HourView(true);
hour_user = timePicker.getCurrentHour();
minute_user = timePicker.getCurrentMinute();
String time1 = hour_device + ":" + minute_device;
String time2 = hour_user + ":" + minute_user;
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
Date date1 = null;
try {
date1 = format.parse(time1);
} catch (ParseException e) {
e.printStackTrace();
}
Date date2 = null;
try {
date2 = format.parse(time2);
} catch (ParseException e) {
e.printStackTrace();
}
long result = date2.getTime() - date1.getTime();
new CountDownTimer(result, 1000) {
public void onTick(long millisUntilFinished) {
time.setText(("seconds remaining: " + millisUntilFinished / 1000));
//create HashMap<Integer,String> textMap at the constructer of the adapter
//now fill this info into it
textMap.put(new Integer(position),"seconds remaining: " + millisUntilFinished / 1000);
//notify about the data change
notifyDataSetChanged();
}
public void onFinish() {
time.setVisibility(View.INVISIBLE);
Toast.makeText(getApplicationContext(), "finish", Toast.LENGTH_LONG).show();
if (rowView != lastview || mediaPlayer == null) {
play(position);
if (lastview != null)
lastview = rowView;
} else {
play.setImageResource(R.drawable.n_btn_play_unselected);
mediaPlayer.release();
lastview = null;
}
}
}.start();
deleteDialog.dismiss();
}
});
deleteDialog.show();
}
});
play.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (rowView != lastview || mediaPlayer == null) {
play(position);
if (lastview != null)
lastview = rowView;
} else {
play.setImageResource(R.drawable.n_btn_play_unselected);
mediaPlayer.release();
lastview = null;
}
}
});
return rowView;
}
}
}
I need help, any suggestion?
I'm new with android:-)
Update your countdown timer like this
new CountDownTimer(result, 1000) {
public void onTick(long millisUntilFinished) {
time.setText(("seconds remaining: " + millisUntilFinished / 1000));
//create HashMap<Integer,String> textMap at the constructer of the adapter
//whenever you want to clear a record clear the hash map
//now fill this info into it
textMap.put(new Integer(position),"seconds remaining: " + millisUntilFinished / 1000);
//notify about the data change
notifyDataSetChanged();
}
public void onFinish() {
time.setVisibility(View.INVISIBLE);
Toast.makeText(getApplicationContext(), "finish", Toast.LENGTH_LONG).show();
if (rowView != lastview || mediaPlayer == null) {
play(position);
if (lastview != null)
lastview = rowView;
} else {
play.setImageResource(R.drawable.n_btn_play_unselected);
mediaPlayer.release();
lastview = null;
}
}
}.start();
At the place where you initiate the textView text;
final TextView time = (TextView) rowView.findViewById(R.id.time);
//populate the textview from map
if(textMap!=null && textMap.get(new Integer(position))!=null){
time.setText(textMap.get(new Integer(position)));
}
This continuous update might cause lag issues.
You must use Reclyclerview for this, textview is primitive for your requirement.
https://developer.android.com/training/material/lists-cards.html
I have a code to read the contacts from the inbuilt phone contacts and it displays all the contacts in a list view in my app.The user can select multiple contacts and display them in another activity.
This code works fine in Android API level 18 and above,but gives an error in the versions below API 18.
I'm attaching the code of the contact picker activity and its adapter.
Error Logcat
private void getSelectedContacts() {
// TODO Auto-generated method stub
StringBuffer sb = new StringBuffer();
dataBase=mHelper.getWritableDatabase();
ContentValues values=new ContentValues();
for (ContactObject bean : ContactsListClass.phoneList) {
if (bean.isSelected()) {
sb.append(bean.getName());
sb.append(bean.getNumber());
sb.append("1");
values.put(DbHelper.KEY_FNAME,bean.getName());
values.put(DbHelper.KEY_LNAME,bean.getNumber() );
values.put(DbHelper.KEY_INVITE,"1" );
dataBase.insert(DbHelper.TABLE_NAME, null, values);
}
}
dataBase.close();
String s = sb.toString().trim();
if (TextUtils.isEmpty(s)) {
Toast.makeText(context, "Select atleast one Contact",
Toast.LENGTH_SHORT).show();
} else {
s = s.substring(0, s.length() - 1);
/**
Toast.makeText(context, "Selected Contacts : " + s,
Toast.LENGTH_SHORT).show();
**/
Intent i = new Intent(Contacts_main.this, MainActivity.class);
i.putExtra("NAME", name);
i.putExtra("EVT_Name", event_name);
i.putExtra("EVT_Date", event_date);
startActivity(i);
}
}
private void addContactsInList() {
// TODO Auto-generated method stub
Thread thread = new Thread() {
#Override
public void run() {
showPB();
try {
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, null, null, null);
try {
ContactsListClass.phoneList.clear();
} catch (Exception e) {
}
while (phones.moveToNext()) {
String phoneName = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String phoneImage = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
//String pImage =
ContactObject cp = new ContactObject();
cp.setName(phoneName);
cp.setNumber(phoneNumber);
cp.setImage(phoneImage);
//cp.setImage(getResources(R.drawable.prof_active));
ContactsListClass.phoneList.add(cp);
}
phones.close();
lv = new ListView(context);
lv.setDividerHeight(0);
lv.setDivider(null);
lv.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
llContainer.addView(lv);
}
});
Collections.sort(ContactsListClass.phoneList,
new Comparator<ContactObject>() {
#Override
public int compare(ContactObject lhs,
ContactObject rhs) {
return lhs.getName().compareTo(
rhs.getName());
}
});
objAdapter = new ContactsAdapter(Contacts_main.this,
ContactsListClass.phoneList);
lv.setAdapter(objAdapter); //ERROR SHOWING HERE
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
CheckBox chk = (CheckBox) view
.findViewById(R.id.contactcheck);
ContactObject bean = ContactsListClass.phoneList
.get(position);
if (bean.isSelected()) {
bean.setSelected(false);
chk.setChecked(false);
} else {
bean.setSelected(true);
chk.setChecked(true);
}
}
});
} catch (Exception e) {
// e.printStackTrace();
//Toast.makeText(context, "Crash",Toast.LENGTH_SHORT).show();
}
hidePB();
}
};
thread.start();
}
Adapter Class:
Context mContext;
LayoutInflater inflater;
private List<ContactObject> mainDataList = null;
private List<ContactObject> mainInviteesList = null;
private ArrayList<ContactObject> arraylist;
private DbHelper mHelper;
private SQLiteDatabase dataBase;
public ContactsAdapter(Context context, List<ContactObject> mainDataList) {
mContext = context;
this.mainDataList = mainDataList;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<ContactObject>();
this.arraylist.addAll(mainDataList);
mHelper=new DbHelper(context);
}
static class ViewHolder {
protected TextView name;
protected TextView number;
protected CheckBox check;
protected ImageView image;
protected EditText invitees;
}
#Override
public int getCount() {
return mainDataList.size();
}
#Override
public ContactObject getItem(int position) {
return mainDataList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.list_row, null);
holder.name = (TextView) view.findViewById(R.id.contactname);
holder.number = (TextView) view.findViewById(R.id.contactno);
holder.check = (CheckBox) view.findViewById(R.id.contactcheck);
holder.image = (ImageView) view.findViewById(R.id.contactimage);
holder.invitees = (EditText) view.findViewById(R.id.editInvites);
view.setTag(holder);
view.setTag(R.id.contactname, holder.name);
view.setTag(R.id.contactno, holder.number);
view.setTag(R.id.contactcheck, holder.check);
view.setTag(R.id.editInvites, holder.invitees);
holder.check
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton vw,
boolean isChecked) {
int getPosition = (Integer) vw.getTag();
mainDataList.get(getPosition).setSelected(
vw.isChecked());
/**
dataBase=mHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(DbHelper.KEY_FNAME,mainDataList.get(getPosition).getName());
values.put(DbHelper.KEY_LNAME,mainDataList.get(getPosition).getNumber());
values.put(DbHelper.KEY_INVITE,"1" );
dataBase.insert(DbHelper.TABLE_NAME, null, values);
dataBase.close();
**/
}
});
// holder.invitees.addTextChangedListener(watcher);
} else {
holder = (ViewHolder) view.getTag();
}
holder.check.setTag(position);
//holder.invitees.setTag(position);
holder.name.setText(mainDataList.get(position).getName());
holder.number.setText(mainDataList.get(position).getNumber());
if(getByteContactPhoto(mainDataList.get(position).getImage())==null){
holder.image.setImageResource(R.drawable.prof_active);
}else{
holder.image.setImageBitmap(getByteContactPhoto(mainDataList.get(position).getImage()));
}
holder.check.setChecked(mainDataList.get(position).isSelected());
return view;
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
mainDataList.clear();
if (charText.length() == 0) {
mainDataList.addAll(arraylist);
} else {
for (ContactObject wp : arraylist) {
if (wp.getName().toLowerCase(Locale.getDefault())
.contains(charText)) {
mainDataList.add(wp);
}
}
}
notifyDataSetChanged();
}
public Bitmap getByteContactPhoto(String contactId) {
Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, Long.parseLong(contactId));
Uri photoUri = Uri.withAppendedPath(contactUri, Contacts.Photo.CONTENT_DIRECTORY);
Cursor cursor = mContext.getContentResolver().query(photoUri,
new String[] {Contacts.Photo.DATA15}, null, null, null);
if (cursor == null) {
return null;
}
try {
if (cursor.moveToFirst()) {
byte[] data = cursor.getBlob(0);
if (data != null) {
return BitmapFactory.decodeStream( new ByteArrayInputStream(data));
}
}
} finally {
cursor.close();
}
return null;
}
}
I have problem to set data into listview. Problem occurs after set message, message is set first after come 8th message from thread.
**below is my whole code :****(Here is my "Activity and adapter")**
public class Inboxreadmsg extends ActionBarActivity {
// <strong>Here is my global variable</strong>
ListView lv;
Handler h;
Custom_Inbox_Adapter ccAdpt;
Custom_Inbox_Adapter inadapter;
Runnable checker;
List<Dataset> dataset;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.messagesublistlayout);
// map id from layout</strong>
lv =(ListView)findViewById(R.id.readmessagelist);
/*****************************call thread of webservice with database****************************/
runThread();
startHandler();
/*****************************call thread of webservice with database****************************/
}
public void runThread()
{
h=new Handler();
checker=new Runnable()
{
#Override
public void run() {
// call webservice for fetch data
forthread();
h.postDelayed(checker,15000);
}
};
}
public void forthread()
{
// call webservice to fetch data
new InboxReadChat(null, InboxReadChat.TotalMessagesOfSingleSenderUser.geturl( recipientid,InAppUserid), InboxReadChat.TYPE_GET, InboxReadChat.TYPE_RECEIVE_MESSAGE_INBOX, new ServiceHitListenerInboxChat() {
#Override
public void onSuccess(Object Result, int id)
{
// After success of webservice response come this function
callFxnInSuccess(Result);
}
#Override
public void onError(String Error, int id)
{
// AfterError of webservice response come this function
// By this fxn set data from local database to listview
DBvaluesSet();
}
});
}
private void callFxnInSuccess(Object Result) {
dataset = new ArrayList<Dataset>();
String message="",alldatetime="",time="",date="",type="";
InboxDeliveredModel ibx=(InboxDeliveredModel) Result;
if(ibx.getTotalMessagesOfSingleSenderUser().size()>0)
{
// here webservice response data will add on local database
dbObject.Open();
for(int i=0;i<ibx.getTotalMessagesOfSingleSenderUser().size();i++)
{
message =ibx.getTotalMessagesOfSingleSenderUser().get(i).getMessage();
.....
dbObject.InboxMessageAll(message,InAppUsermobile,time,recipientid,type,date);
}
dbObject.close();
// After add data into database call below fxn to fetch data from database and set data in listview with adapter
try
{
DBvaluesSet();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
public void DBvaluesSet() {
dataset = new ArrayList<Dataset>();
try
{
// By this code fetch data from local database
Cursor c;
dbObject.Open();
c=dbObject.getallmessages(recipientid);
int countRow = c.getCount();
int counter = 0;
while(c.moveToNext())
{
msgboxitem = c.getString(0);
// number = c.getString(1);
timeitem = c.getString(2);
typeitem = c.getString(4);
datedbitem = c.getString(5);
try {
dataset.add(db.new Dataset(datedbitem, msgboxitem, timeitem, typeitem));
} catch (Exception e) {
e.printStackTrace();
}
}
dbObject.close();
// by below set data into listview into adapter
lv.setAdapter(ccAdpt=new Custom_Inbox_Adapter( getApplicationContext(),dataset,R.layout.row));
ccAdpt.notifyDataSetChanged();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Here my adapter coding...
public class Custom_Inbox_Adapter extends BaseAdapter{
private Context gContext;
private List<Dataset> gData;
private int rEsource;
public Custom_Inbox_Adapter(Context cnt, List<Dataset> data ,int resource){
this.gData = data;
this.gContext = cnt;
this.rEsource = resource;
}
#Override
public int getCount() {
return gData.size();
}
#Override
public Dataset getItem(int position) {
return gData.get(position);
}
#Override
public long getItemId(int position) {> return gData.get(position).hashCode();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) gContext.getSystemService(gContext.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(rEsource, null);
TextView txtReceiveMsg = (TextView) convertView.findViewById(R.id.ReceiveMsg);
TextView txtReceiveTime = (TextView) convertView.findViewById(R.id.ReceiveTime);
TextView txtSendMsg = (TextView) convertView.findViewById(R.id.sendMsg);
TextView txtSendTime = (TextView) convertView.findViewById(R.id.senttime);
TextView date = (TextView) convertView.findViewById(R.id.date);
// layout text chat
RelativeLayout relSend = (RelativeLayout) convertView.findViewById(R.id.LinearReceive);
RelativeLayout relreceive = (RelativeLayout) convertView.findViewById(R.id.LinearSend);
// layout date chat
RelativeLayout LinearDATE= (RelativeLayout) convertView.findViewById(R.id.LinearDATE);
if(position == 0){
fetchdata= gData.get(position).getDate().trim();
date.setText(fetchdata);
}
else{
fetchdata = gData.get(position).getDate().trim();
dd = gData.get((position-1)).getDate().trim();
if(fetchdata.equalsIgnoreCase(dd))
{
LinearDATE.setVisibility(View.GONE);
}
else
{
LinearDATE.setVisibility(View.VISIBLE);
Log.w("INBOX READ", "INBOX_READ_ADAPTER::::(date for position '1'):"+fetchdata);
date.setText(fetchdata);
}
}
relreceive.setVisibility(View.GONE);
relSend.setVisibility(View.VISIBLE);
//txtReceiveNumber.setText(number);
txtReceiveMsg.setText(cutmsg);
txtReceiveTime.setText(time);
}
return convertView;
}
}