Update ListView Record Duplicated Android - android

I put a limit of 15 records to be displayed in my listview. The 15 records successfully displayed but when i clicked on load more button, it add the previous 15 records and the new records too. Here is my async task where more records is being added. I use articlesAdapter.notifyDataSetChanged(); set too but the issue remains. i believe it has something to do with articlesFiltered.size()/15)+1.
public class ActusScreen extends BaseActivity implements OnClickListener {
private DisplayImageOptions options;
ImageLoader imageLoader;
String link;
//...
final int NONE=0;
final int THEME=1;
final int SEARCH=2;
final int THEME_TO_SEARCH=3;
final int SEARCH_RESULTS=4;
final int THEME_TO_SEARCH_RESULTS=5;
int MODE=NONE;
public ArrayList<Article> articles;
public ArrayList<Article> articlesFiltered;
public ArrayList<Theme> themes;
public ArrayList<Theme> themeFiltered;
public static int titleIndex=0;
static boolean original_view = false;
RelativeLayout adLayout;
ListView themesList;
RelativeLayout searchLayout;
EditText searchField;
Button back, theme;
StringBuilder builder;
ScrollView scrollme;
ThemesAdapter themeAdapter;
ArticlesAdapter articlesAdapter;
TextView header_text;
ActusScreen context;
ProgressDialog pd;
ImageView image_actus;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.actus);
context=this;
back=(Button)findViewById(R.id.envoye);
back.setOnClickListener(this);
back.setVisibility(View.GONE);
theme=(Button)findViewById(R.id.theme);
theme.setOnClickListener(this);
Button search=(Button)findViewById(R.id.search);
search.setOnClickListener(this);
header_text = (TextView)findViewById(R.id.text_titre);
header_text.setText(getResources().getText(R.string.actus).toString());
adLayout=(RelativeLayout)findViewById(R.id.adLayout);
themeAdapter=new ThemesAdapter(this);
themesList=(ListView)findViewById(R.id.themesList);
themesList.setAdapter(themeAdapter);
themesList.setVisibility(View.GONE);
SelectedArticle.mtypo=1;
articlesAdapter=new ArticlesAdapter(this);
ListView articlesList=(ListView)findViewById(R.id.articlesList);
articlesList.setAdapter(articlesAdapter);
searchLayout=(RelativeLayout)findViewById(R.id.searchLayout);
searchLayout.setVisibility(View.GONE);
searchField=(EditText)findViewById(R.id.keyword);
Button valid=(Button)findViewById(R.id.valid);
valid.setOnClickListener(this);
new GetAllArticlesTask().execute();
image_actus = (ImageView)findViewById(R.id.image);
image_actus.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String url = link;
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
options = new DisplayImageOptions.Builder()
// .showStubImage(R.drawable.ic_launcher)
.displayer(new RoundedBitmapDisplayer(3))
.cacheInMemory()
.cacheOnDisc()
.build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(getApplicationContext()));
new backTask().execute("");
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
//FavoriteScreen.flagx=1;
super.onStart();
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.envoye:
back();
break;
case R.id.theme:
if(themesList.getVisibility()==View.VISIBLE)
themesList.setVisibility(View.GONE);
else
themesList.setVisibility(View.VISIBLE);
break;
case R.id.search:
search();
break;
case R.id.valid:
searchLayout.setVisibility(View.GONE);
if(MODE==SEARCH)
MODE=SEARCH_RESULTS;
else
MODE=THEME_TO_SEARCH_RESULTS;
filterArticles();
break;
}
}
public void search(){
switch(MODE){
case SEARCH_RESULTS:
searchLayout.setVisibility(View.VISIBLE);
MODE=SEARCH;
break;
case THEME_TO_SEARCH_RESULTS:
searchLayout.setVisibility(View.VISIBLE);
MODE=THEME_TO_SEARCH;
break;
case THEME:
searchLayout.setVisibility(View.VISIBLE);
MODE=THEME_TO_SEARCH;
break;
case NONE:
searchLayout.setVisibility(View.VISIBLE);
back.setVisibility(View.VISIBLE);
theme.setVisibility(View.GONE);
MODE=SEARCH;
break;
}
}
public void back(){
switch(MODE){
case SEARCH_RESULTS:
searchLayout.setVisibility(View.VISIBLE);
MODE=SEARCH;
break;
case THEME_TO_SEARCH_RESULTS:
searchLayout.setVisibility(View.VISIBLE);
MODE=THEME_TO_SEARCH;
break;
case THEME:
back.setVisibility(View.GONE);
theme.setVisibility(View.VISIBLE);
/*
*
Intent intent = getIntent();
finish();
startActivity(intent);
*/
articlesAdapter=new ArticlesAdapter(this);
ListView articlesList=(ListView)findViewById(R.id.articlesList);
articlesList.setAdapter(articlesAdapter);
//ActusScreen.titleIndex=0;
ArticlesAdapter.mode = true;
titleIndex=0;
new GetAllArticlesTask().execute();
header_text.setText(getResources().getText(R.string.actus).toString());
MODE=NONE;
break;
case SEARCH:
searchLayout.setVisibility(View.GONE);
back.setVisibility(View.GONE);
theme.setVisibility(View.VISIBLE);
MODE=NONE;
copyArticles();
articlesAdapter.notifyDataSetChanged();
break;
case THEME_TO_SEARCH:
searchLayout.setVisibility(View.GONE);
MODE=THEME;
copyArticles();
articlesAdapter.notifyDataSetChanged();
break;
}
}
private void copyArticles() {
if(articles!=null){
if(articlesFiltered==null)
articlesFiltered=new ArrayList<Article>();
else
articlesFiltered.clear();
for(Article a: articles)
articlesFiltered.add(a);
}
}
public void filterArticles(){
String key=searchField.getText().toString().toLowerCase();
if(key.length()>0){
if(articlesFiltered!=null){
articlesFiltered.clear();
System.gc();
}
for(Article a: articles){
if(a.name.toLowerCase().contains(key))
articlesFiltered.add(a);
}
articlesAdapter.notifyDataSetChanged();
}
}
private class GetAllArticlesTask extends AsyncTask<Void, Void, Void> {
#Override
public Void doInBackground(Void... params) {
if(Globals.themes==null)
Globals.themes=HTTPFunctions.getThemesList();
if(articles!=null){
articles.clear();
System.gc();
}
articles=HTTPFunctions.getAllArticles();
copyArticles();
return null;
}
#Override
public void onPreExecute() {
pd = ProgressDialog.show(context, "", context.getResources().getString(R.string.loading), true, false);
}
#Override
public void onPostExecute(Void result) {
pd.dismiss();
articlesAdapter.notifyDataSetChanged();
themeAdapter.notifyDataSetChanged();
}
}
private class GetThemeArticlesTask extends AsyncTask<String, Void, Void> {
#Override
public Void doInBackground(String... params) {
if(articles!=null){
articles.clear();
System.gc();
}
articles=HTTPFunctions.getThemeArticles(params[0]);
//begin 06/03; articles.theme_id not set by HTTPFunctions when a specific theme is selected; need to set it explicitly
for (Article a : articles)
a.theme_id=params[0];
//end
System.out.println("theme article: "+ HTTPFunctions.getThemeArticles(params[0]));
copyArticles();
return null;
}
#Override
public void onPreExecute() {
pd = ProgressDialog.show(context, "", context.getResources().getString(R.string.loading), true, false);
}
#Override
public void onPostExecute(Void result) {
pd.dismiss();
articlesAdapter.notifyDataSetChanged();
}
}
private class GetMoreArticlesTask extends AsyncTask<Void, Void, Void> {
#Override
public Void doInBackground(Void... params) {
ArrayList<Article>moreArticles=HTTPFunctions.getMoreArticles(addOne((articlesFiltered.size()/15)));
if(moreArticles!=null){
articles.addAll(articles);
copyArticles();
}
return null;
}
#Override
public void onPreExecute() {
pd = ProgressDialog.show(context, "", context.getResources().getString(R.string.loading), true, false);
}
#Override
public void onPostExecute(Void result) {
pd.dismiss();
articlesAdapter.notifyDataSetChanged();
}
}
public void articleSelected(int id){
Globals.copyArticles(articlesFiltered);
Intent i=new Intent(context, SelectedArticle.class);
i.putExtra("id", id);
//begin
//i.putExtra("title", ArticlesAdapter.selected);
if (titleIndex==0){
String title=Util.getTitleName(articlesFiltered.get(id).type, articlesFiltered.get(id).theme_id);
i.putExtra("title", title);
}
else{
String title=ArticlesAdapter.selected.toUpperCase();
i.putExtra("title", title);
}
//end
context.startActivity(i);
}
public void themeSelected(int id){
themesList.setVisibility(View.GONE);
MODE=THEME;
theme.setVisibility(View.GONE);
back.setVisibility(View.VISIBLE);
ArticlesAdapter.mode = false;
//begin 06/03
//ArticlesAdapter.selected=Globals.themes.get(id).name;
//header_text.setText(Globals.themes.get(id).name.toUpperCase());
Spanned name=Html.fromHtml(Globals.themes.get(id).name);
System.out.println("spanned name: "+ name);
ArticlesAdapter.selected=name.toString().toUpperCase();
header_text.setText(name.toString().toUpperCase());
//end
System.out.println("theme_name: "+ Globals.themes.get(id).name);
new GetThemeArticlesTask().execute(Globals.themes.get(id).id);
}
public void loadMore(){
new GetMoreArticlesTask().execute();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
if (original_view==true){
new GetAllArticlesTask().execute();
theme.setVisibility(View.VISIBLE);
back.setVisibility(View.GONE);
header_text.setText(getResources().getText(R.string.actus).toString());
original_view=false;
}
super.onResume();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
SelectedReglementation.setview=true;
super.onPause();
}
class backTask extends AsyncTask<String, Void, ArrayList<Post>> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected ArrayList<Post> doInBackground(String... urls) {
ArrayList<Post> newpostarraylist=new ArrayList<Post>();
try{
URL url = new URL("");
BufferedReader reader = null;
builder = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
for (String line; (line = reader.readLine()) != null;) {
builder.append(line.trim());
}
} finally {
if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
}
System.out.println("Builder: "+ builder);
}catch(Exception ex){}
return newpostarraylist;
}
#Override
protected void onPostExecute(ArrayList<Post> result) {
String[] banner_image = builder.toString().split(";");
imageLoader.displayImage(banner_image[2], image_actus,options);
link = banner_image[1];
}
}
public int addOne(int i){
return i+1;
}
}
and My article adapter
public class ArticlesAdapter extends BaseAdapter {
ActusScreen main;
ImageLoader imageLoader;
String imageUrl="";
public static String selected="";
public static boolean mode=false;
int x=0;
//disable a.theme_id null pointer wh
public static int bine=0;
public ArticlesAdapter(ActusScreen m) {
main=m;
imageLoader=new ImageLoader(m);
}
public int getCount() {
if(main.articlesFiltered!=null)
return main.articlesFiltered.size();
return 0;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView==null) {
convertView=newView(position, parent);
holder = new ViewHolder();
holder.image=(ImageView)convertView.findViewById(R.id.image);
holder.remove=(ImageView)convertView.findViewById(R.id.remove);
holder.title=(TextView)convertView.findViewById(R.id.title);
holder.text_title=(TextView)convertView.findViewById(R.id.text_title);
holder.more=(RelativeLayout)convertView.findViewById(R.id.moreLayout);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Article a=main.articlesFiltered.get(position);
imageLoader.DisplayImage(String.format(imageUrl, a.image), holder.image);
String str = a.name;
int length = str.length();
String newStr = a.name;
if (length>65)
newStr = str.replaceAll("^(.{74})(.*)$","$1...");
holder.title.setText(Html.fromHtml(newStr));
holder.text_title.setText(selected.toUpperCase());
holder.remove.setVisibility(View.GONE);
if (holder.text_title.equals(null))
holder.text_title.setText("t");
if(position==main.articlesFiltered.size()-1 && main.articlesFiltered.size()<=45 && main.articlesFiltered.size()%15==0)
holder.more.setVisibility(View.VISIBLE);
else
holder.more.setVisibility(View.GONE);
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
main.articleSelected(position);
SelectedArticle.mtypo=1;
}
});
holder.more.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
main.loadMore();
}
});
if (ActusScreen.titleIndex==0){
...
}
}
return(convertView);
}
private View newView(int position, ViewGroup parent) {
return(main.getLayoutInflater().inflate(R.layout.articles_row, parent, false));
}
class ViewHolder {
ImageView image, remove;
TextView title;
TextView text_title;
RelativeLayout more;
}
}
UPDATE
and the HttpFunction getMoreArticles()
public static ArrayList<Article> getMoreArticles(int page){
String url=LAST_ARTICLE_URL;
if(url.endsWith(".php"))
url+="?page="+page;
else
url+="&page="+page;
String response=getResponse(url);
if(!ERROR.equals(response)){
return JsonParsingFunctions.parseArticles(response);
}
return null;
}

What is happening is concatenation in the method call. articlesFiltered.size()/15 is giving 1, then the +1 is not ADDING 1, it is concatenating 1, i.e 1+1 = 11 NOT 2. You could create a method
public int addOne(int i){
return i+1;
}
and use
ArrayList<Article>moreArticles=HTTPFunctions.getMoreArticles(addOne((articlesFiltered.size()/15)));
That should work providing the rest of the code is good

what variable is your adapter?
you notify your adapter but i don't see that you add datas to your articlesAdapter

Related

How to sort recyclerView, Bold item if unread and unbold if item opened?

I have 2 Activities in my application.
activityMain contain 3 Fragments
The third fragment is a conversations list. This is a recylerView where each Item leads to a specific chat.
activityConversation contains a Chat.
First, i would like to sort the conversations in the the recyclerView in order of "Last actives". The most recent active should be displayed on top of the list, the second last active on second postition etc...
Secondly, each Item of the recyclerView contains a Textview. For each item, I would like to display the last message posted in the related chat in this Texview.
Finally, i would like to display these Item textViews in Bold since the conversation has not been opened until the last chat update.
Has anyone an Idea to help me achieve that?
Here my Chat Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_conversation);
getWindow().setBackgroundDrawableResource(R.drawable._background_black_lchatxxxhdpi) ;
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
LinearLayout leftNav = (LinearLayout)findViewById(R.id.conv_left_nav);
LinearLayout helperAdmin = (LinearLayout) getLayoutInflater().inflate(R.layout.list_participant_admin, leftNav, false);
leftNav.addView(helperAdmin);
final EditText input_post = (EditText)findViewById(R.id.input_post);
context = this;
input_post.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
ImageButton btn_submit = (ImageButton)findViewById(R.id.btn_submit);
btn_submit.setEnabled(!TextUtils.isEmpty(s.toString().trim()));
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
Intent intent = getIntent();
if (intent.hasExtra("conversationId"))
conversationId = intent.getStringExtra("conversationId");
rpcHelper = new RPCHelper(context, this);
String unique_device_id = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
Log.i("US", unique_device_id);
rpcHelper.loginOrRegister(unique_device_id, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
refreshConversation();
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
}
#Override
public void onPreExecute() {
}
});
dbHelper = new DataBaseHelper(context, "us", null, Statics.DB_VERSION);
userInConv = dbHelper.dbReader.getUserInConversation(Integer.parseInt(conversationId));
storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
leftRecycler = (RecyclerView) helperAdmin.findViewById(R.id.conv_left_recycler);
//mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
leftLayoutManager = new LinearLayoutManager(this);
leftRecycler.setLayoutManager(leftLayoutManager);
leftAdapter = new ConvLeftAdapter(userInConv, storageDir, Integer.parseInt(conversationId));
leftRecycler.setAdapter(leftAdapter);
helpersImg = new View[3];
helpers = new DataBaseReader.User[3];
photos = dbHelper.dbReader.getPhotosInConversation(Integer.parseInt(conversationId));
photoRecycler = (RecyclerView) findViewById(R.id.photo_recycler);
photoLayoutManager = new GridLayoutManager(this, Math.max(photos.length, 1));
photoRecycler.setLayoutManager(photoLayoutManager);
rightAdapter = new ConvRightAdapter(photos, storageDir, context);
photoRecycler.setAdapter(rightAdapter);
IntentFilter filter = new IntentFilter(Statics.ACTION_NEW_POST);
this.registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context ctx, Intent intent) {
Log.d("new", " message");
refreshConversation();
}
}, filter);
}
#Override
public void onNewIntent(Intent intent){
if (intent.hasExtra("conversationId"))
conversationId = intent.getStringExtra("conversationId");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_conversation, menu);
DataBaseReader.Conversation conversation = dbHelper.dbReader.getConversation(conversationId);
DataBaseReader.User owner = dbHelper.dbReader.getConversationOwner(conversationId);
final ImageView owner_img = (ImageView)findViewById(R.id.img_userprofilpic);
TextView owner_name = (TextView)findViewById(R.id.lbl_username_owner);
TextView owner_city = (TextView)findViewById(R.id.lbl_usercity_owner);
TextView conversation_question = (TextView)findViewById(R.id.question_text);
owner_name.setText(owner.name);
owner_city.setText(owner.city);
conversation_question.setText(conversation.question.text);
conversation_question.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView text = (TextView)findViewById(R.id.question_text);
int maxLines = TextViewCompat.getMaxLines(text);
if (maxLines==2){
text.setMaxLines(Integer.MAX_VALUE);
}
else{
text.setMaxLines(2);
}
}
});
rpcHelper.getPhoto(storageDir + "/", owner.photo, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
owner_img.setImageBitmap(bm);
}
#Override
public void onPreExecute() {
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
public void refreshConversation(){
dbHelper.dbSyncer.syncPosts(rpcHelper.user_id, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
DataBaseReader.Post[] posts = dbHelper.dbReader.getPosts(conversationId);
postsRecycler = (RecyclerView) findViewById(R.id.posts_recycler);
postsLayoutManager = new LinearLayoutManager(context);
postsRecycler.setLayoutManager(postsLayoutManager);
postsAdapter = new PostsAdapter(posts, storageDir, rpcHelper);
postsRecycler.setAdapter(postsAdapter);
postsRecycler.scrollToPosition(postsAdapter.getItemCount() - 1);
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
}
#Override
public void onPreExecute() {
}
});
/*
rpcHelper.getPosts(conversationId, new AsyncResponseListener(){
#Override
public void onResponse(JSONArray response) throws JSONException {
LinearLayout posts_root = (LinearLayout) findViewById(R.id.posts_root);
posts_root.removeAllViews();
for (int i = 0; i < response.length(); i++){
Log.d("Conv refresh", response.get(i) + "");
final JSONObject jConversation = (JSONObject) response.get(i);
LinearLayout post;
if (jConversation.getString("userId") == rpcHelper.user_id) {
post = (LinearLayout) getLayoutInflater().inflate(R.layout.item_chatpost_sent, posts_root, false);
}
else{
post = (LinearLayout) getLayoutInflater().inflate(R.layout.item_chatpost_received, posts_root, false);
((TextView)post.findViewById(R.id.post_name_)).setText(jConversation.getString("name"));
}
((TextView)post.findViewById(R.id.lbl_message_chat)).setText(jConversation.getString("text"));
posts_root.addView(post);
}
hideProcessDialog();
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
}
#Override
public void onPreExecute() {
}
});*/
}
public void onSubmit(View v){
final EditText input_post = (EditText)findViewById(R.id.input_post);
String post_text = input_post.getText().toString();
rpcHelper.post(conversationId, post_text, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
refreshConversation();
input_post.setText("");
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
}
#Override
public void onPreExecute() {
}
});
}
Button no = (Button)alertDialog.findViewById(R.id.btn_cancel);
no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
helpersImg[0] = null;
helpersImg[1] = null;
helpersImg[2] = null;
helpers[0] = null;
helpers[1] = null;
helpers[2] = null;
alertDialog.dismiss();
}
});
}
public void onSelectUser(View v){
View vi = snapHelper.findSnapView(participantsLayoutManager);
if (helpersImg[0] == vi || helpersImg[1] == vi || helpersImg[2] == vi)
return;
Log.i("get helper Id", ""+ participantsAdapter.selectedUserId);
ImageView photo = (ImageView) vi.findViewById(R.id.img_userprofilpic);
photo.setDrawingCacheEnabled(true);
Bitmap bmap = photo.getDrawingCache();
ImageView helperImage = null;
if (helpersImg[0] == null) {
helperImage = (ImageView) alertDialog.findViewById(R.id.reward_dialog_helper0);
helpersImg[0] = vi;
helperImage.setImageBitmap(bmap);
photo.setColorFilter(Color.rgb(123, 123, 123), android.graphics.PorterDuff.Mode.MULTIPLY);
helpers[0] = userInConv[participantsAdapter.selectedUserId];
}
else if (helpersImg[1] == null){
helperImage = (ImageView) alertDialog.findViewById(R.id.reward_dialog_helper1);
helpersImg[1] = vi;
helperImage.setImageBitmap(bmap);
photo.setColorFilter(Color.rgb(123, 123, 123), android.graphics.PorterDuff.Mode.MULTIPLY);
helpers[1] = userInConv[participantsAdapter.selectedUserId];
}
else if (helpersImg[2] == null){
helperImage = (ImageView) alertDialog.findViewById(R.id.reward_dialog_helper2);
helpersImg[2] = vi;
helperImage.setImageBitmap(bmap);
photo.setColorFilter(Color.rgb(123, 123, 123), android.graphics.PorterDuff.Mode.MULTIPLY);
helpers[1] = userInConv[participantsAdapter.selectedUserId];
}
else{
return;
}
}
/**private void showTipDialog(){
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
LayoutInflater inflater = LayoutInflater.from(context);
final View dialogView = inflater.inflate(R.layout.dialog_add_tip, null);
final EditText value = (EditText) dialogView.findViewById(R.id.tip_value);
final SeekBar sb = (SeekBar) dialogView.findViewById(R.id.seekBar);
sb.setMax(50);
sb.setProgress(5);
sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
progress = (Math.round(progress/5 ))*5;
seekBar.setProgress(progress);
value.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
value.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Convert text to integer. Do you already use editText.setInputType(InputType.TYPE_CLASS_NUMBER), don't you?
Integer enteredProgress = Integer.valueOf(s.toString());
sb.setProgress(enteredProgress);
}
#Override
public void afterTextChanged(Editable s) {}});
dialogBuilder.setView(dialogView);
alertDialog = dialogBuilder.create();
alertDialog.show();
Button ok = (Button)alertDialog.findViewById(R.id.btn_ok);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
Button no = (Button)alertDialog.findViewById(R.id.btn_no);
no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
}*/
public void removeHelper(View v){
int index = 0;
if (v == alertDialog.findViewById(R.id.reward_dialog_helper0)){
index = 0;
}
else if (v == alertDialog.findViewById(R.id.reward_dialog_helper1)){
index = 1;
}
else if (v == alertDialog.findViewById(R.id.reward_dialog_helper2)){
index = 2;
}
if (helpersImg[index] == null){
return;
}
ImageView photo = (ImageView) helpersImg[index].findViewById(R.id.img_userprofilpic);
photo.setDrawingCacheEnabled(true);
photo.clearColorFilter();
helpersImg[index] = null;
helpers[index] = null;
ImageView imv = (ImageView)v;
imv.setImageResource(R.drawable.stroke_rounded_corners_white);
}
private void showProcessDialog(){
pd = new ProgressDialog(this);
pd.setTitle("Processing");
pd.setMessage("Please wait...");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
}
private void hideProcessDialog(){
pd.hide();
}
#Override
public void onInternetConnectionLost() {
}
#Override
public void onInternetConnectionFound() {
}
public void onTakePicture(View v){
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, Statics.REQUEST_IMAGE_CAPTURE);
}
}
public void onTakePictureFromGallery(View v){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), Statics.REQUEST_PROFILE_IMAGE_GALLERY);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Bitmap imageBitmap;
if ((requestCode == Statics.REQUEST_IMAGE_CAPTURE || requestCode == Statics.REQUEST_IMAGE_CAPTURE_0
|| requestCode == Statics.REQUEST_IMAGE_CAPTURE_1 || requestCode == Statics.REQUEST_IMAGE_CAPTURE_2) && resultCode == RESULT_OK && data != null) {
Bundle extras = data.getExtras();
if (extras == null){
return;
}
imageBitmap = (Bitmap) extras.get("data");
addPhoto(imageBitmap);
}
else if (requestCode == Statics.REQUEST_PROFILE_IMAGE_GALLERY && resultCode == RESULT_OK){
try {
imageBitmap = getBitmapFromUri(data.getData());
addPhoto(imageBitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void addPhoto(Bitmap image) {
DataBaseReader.Conversation c = dbHelper.dbReader.getConversation(conversationId);
String encodedImage = encodeBitmap(image);
rpcHelper.addPhotosToQuestion("" + c.question.id, encodedImage, null, null, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
dbHelper.dbSyncer.sync(rpcHelper.user_id, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
photos = dbHelper.dbReader.getPhotosInConversation(Integer.parseInt(conversationId));
photoRecycler = (RecyclerView) findViewById(R.id.photo_recycler);
photoLayoutManager = new GridLayoutManager(context, Math.max(photos.length, 1));
photoRecycler.setLayoutManager(photoLayoutManager);
rightAdapter = new ConvRightAdapter(photos, storageDir, context);
photoRecycler.setAdapter(rightAdapter);
}
#Override
public void onResponse() {
photos = dbHelper.dbReader.getPhotosInConversation(Integer.parseInt(conversationId));
photoRecycler = (RecyclerView) findViewById(R.id.photo_recycler);
photoLayoutManager = new GridLayoutManager(context, Math.max(photos.length, 1));
photoRecycler.setLayoutManager(photoLayoutManager);
rightAdapter = new ConvRightAdapter(photos, storageDir, context);
photoRecycler.setAdapter(rightAdapter);
}
#Override
public void onResponse(Bitmap bm) {
}
#Override
public void onPreExecute() {
}
});
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
}
#Override
public void onPreExecute() {
}
});
}
private String encodeBitmap(Bitmap bitmap){
try{
bitmap = Bitmap.createScaledBitmap(bitmap, Statics.BITMAP_WIDTH, Statics.BITMAP_HEIGHT, true);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream);
final byte[] imageInByte = stream.toByteArray();
return Base64.encodeToString(imageInByte, Base64.DEFAULT);
}
catch(Exception e){
return "";
}
}
private Bitmap getBitmapFromUri(Uri uri) throws IOException {
ParcelFileDescriptor parcelFileDescriptor =
getContentResolver().openFileDescriptor(uri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
return image;
}
}
This is my Fragment with conversations List:
public class ConversationFragment extends Fragment {
private View v;
private OnFragmentInteractionListener mListener;
public ConversationFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #return A new instance of fragment ConversationFragment.
*/
// TODO: Rename and change types and number of parameters
public static ConversationFragment newInstance() {
ConversationFragment fragment = new ConversationFragment();
Bundle args = new Bundle();
//args.putString(ARG_PARAM1, param1);
//args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
if (v == null) {
v = inflater.inflate(R.layout.fragment_conversation, container, false);
}
final SwipeRefreshLayout swipeRefresh = (SwipeRefreshLayout)v.findViewById(R.id.swiperefreshconv);
swipeRefresh.post(new Runnable() {
#Override
public void run() {
swipeRefresh.setRefreshing(true);
}
});
swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mListener.syncDb();
}
});
return v;
}
#Override
public void onStart(){
super.onStart();
mListener.refreshConversations();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
}
This is my Conversation Adapter:
public class ConversationsAdapter extends RecyclerView.Adapter {
private final File mStorageDir;
private final RPCHelper mRPCHelper;
private DataBaseReader.Conversation[] mDataset;
Context context;
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public static class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public View mView;
public ViewHolder(View v) {
super(v);
mView = v;
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public ConversationsAdapter(DataBaseReader.Conversation[] myDataset, File storageDir) {
mDataset = myDataset;
mStorageDir = storageDir;
mRPCHelper = new RPCHelper();
}
// Create new views (invoked by the layout manager)
#Override
public ConversationsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_conversations, parent, false);
ViewHolder vh = new ViewHolder(v);
context = parent.getContext();
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
Log.d("recy", "bind called");
TextView username = (TextView)holder.mView.findViewById(R.id.lbl_username);
final TextView message = (TextView)holder.mView.findViewById(R.id.question_text);
TextView date_and_time = (TextView)holder.mView.findViewById(R.id.lbl_date_and_time);
ImageView status_pending = (ImageView)holder.mView.findViewById(R.id.lbl_status_conversation_pending);
ImageView status_in = (ImageView)holder.mView.findViewById(R.id.lbl_status_conversation_in);
TextView keyword0 = (TextView)holder.mView.findViewById(R.id.post_keywords0);
TextView keyword1 = (TextView)holder.mView.findViewById(R.id.post_keywords1);
TextView keyword2 = (TextView)holder.mView.findViewById(R.id.post_keywords2);
ImageView userprofilpic = (ImageView)holder.mView.findViewById(R.id.img_userprofilpic);
LinearLayout answer_info = (LinearLayout) holder.mView.findViewById(R.id.answer_info);
Button delete_coversation = (Button) holder.mView.findViewById(R.id.btn_confirm_delete);
userprofilpic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, UserProfileActivity.class);
i.putExtra("userId", mDataset[position].question.userId);
context.startActivity(i);
}
});
username.setText(mDataset[position].question.userName);
message.setText(mDataset[position].question.text);
keyword0.setText(mDataset[position].question.keywords[0]);
keyword1.setText(mDataset[position].question.keywords[1]);
keyword2.setText(mDataset[position].question.keywords[2]);
addImgToView(mDataset[position].question.photo, userprofilpic);
if (Integer.parseInt(mDataset[position].confirmed) == 1) {
status_pending.setEnabled(false);
status_pending.setVisibility(View.GONE);
status_in.setVisibility(View.VISIBLE);
answer_info.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
message.setTypeface(Typeface.DEFAULT);
message.onSaveInstanceState();
int convId = mDataset[position].id;
Intent i = new Intent(context, ConversationActivity.class);
i.putExtra("conversationId", "" + convId);
context.startActivity(i);
}
});
}
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDataset.length;
}
private void addImgToView(final String uri, final ImageView v){
mRPCHelper.getPhoto(mStorageDir + "/", uri, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
v.setImageBitmap(bm);
}
#Override
public void onPreExecute() {
}
});
}
}
Thank you in advance for your time.
maintain a flag in data level to know is it read or unread,based on that you can apply the styles.
There is two way to do this.
First you can ask to backend to write server side to query to handle last activity bases of timestamp .In this case you have to send your particular timestamp to server when you open particular conversation .
Other you can make local database ex-(sql database) and handle it in your own code by updating query when you reading or undreading conversation.

OnBack Button inside fragment

how i can add an onback pressed button. On this activity appears the image of the onBack pressed button but not works. i have tried some methods but i can not resolve my problem. Hope you can help me. Thank you
here is the code :
public class MyAdsActivity extends Fragment{
public static MyAdsActivity newInstance(String param1, String param2) {
MyAdsActivity fragment = new MyAdsActivity();
return fragment;
}
public MyAdsActivity() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
private OnFragmentInteractionListener mListener;
Toolbar toolbar;
ListView lsv;
List<CatAdd> catAddList;
CateAdDisplayAdapter adapter;
Typeface typeface;
String advertId;
public static boolean refreshFlag = false;
private SharedPreferences pref;
private AdView mAdView;
FloatingActionButton fabAddAds;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_myads, container, false);
typeface = Typeface.createFromAsset(getActivity().getAssets(), "fonts/GandhiSerif-Bold.otf");
fabAddAds = (FloatingActionButton) view.findViewById(R.id.fabAddAds);
mAdView = (AdView)view.findViewById(R.id.adView);
mAdView.loadAd(new AdRequest.Builder().build());
pref = this.getActivity().getSharedPreferences("loginpreference", getActivity().MODE_PRIVATE);
advertId = pref.getString("advertId","");
lsv = (ListView)view.findViewById(R.id.listView1);
catAddList = new ArrayList<CatAdd>();
fabAddAds.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getActivity() ,AddPostActivity.class));
}
});
new MyAdTask().execute();
lsv.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Intent intent = new Intent(getActivity(), BrowseMyDetailActivity.class);
intent.putExtra("adId", String.valueOf(catAddList.get(arg2).getAddid()));
startActivity(intent);
}
});
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
if (refreshFlag) {
refreshFlag = false;
new MyAdTask().execute();
}
}
class MyAdTask extends AsyncTask<Void, Void, Void>
{
String jsonStr = null;
CustomProgressDialog cd = new CustomProgressDialog();
#Override
protected void onPreExecute() {
super.onPreExecute();
cd.showdialog(getActivity(), "Loading.....");
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler sh = new ServiceHandler();
jsonStr = sh.makeServiceCall(String.format(Constants.MYADS_URL, advertId), ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray contacts = jsonObj.getJSONArray(Constants.TAG);
catAddList.clear();
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String adId = c.getString(Constants.CAT_ADID);
String adTitle = c.getString(Constants.CAT_ADTITLE);
String adDes = c.getString(Constants.CAT_ADDES);
String adcity= c.getString(Constants.CAT_CITY);
String adPrise= c.getString(Constants.CAT_PRICE);
JSONArray arrImages=c.getJSONArray("images");
ArrayList<String> imgArray=new ArrayList<String>();
for(int j=0;j<arrImages.length();j++)
{
JSONObject imgObj=arrImages.getJSONObject(j);
if(imgObj.has("imageName"))
{
imgArray.add(imgObj.getString("imageName"));
}
}
CatAdd v=new CatAdd();
v.setAddid(Integer.parseInt(adId));
v.setAdTitle(adTitle);
v.setAdDesc(adDes);
v.setAdPrice(adPrise);
v.setImglist(imgArray);
v.setAdCity(adcity);
catAddList.add(v);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
adapter = new CateAdDisplayAdapter(getActivity(), catAddList);
adapter.notifyDataSetChanged();
lsv.setAdapter(adapter);
cd.dismissdialog();
}
}
}
I can't understand you ... You have an Button and want when you click on it to close the activity or what ? If it's that, then write this code :
Button yourButton = (Button) view.findViewById(R.id.your_button_id);
yourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().onBackPressed();
}
});

android AsyncTask stays hanging running

Hi and thanks for your attention !,
can somebody help me?, my app stays with the progressdialog active and the asynctask stays hanging in running. I try to cancel the asynctask after execution it, but does not work.
public class MttoBitacoraFragment extends Fragment {
ListView lv;
AutoCompleteTextView actEmpleado,actEstatus, actDepto;
List<Autcompletecls> listEmpelado= new ArrayList<Autcompletecls>();
List<Autcompletecls> listEstatus= new ArrayList<Autcompletecls>();
List<Autcompletecls> listDepto= new ArrayList<Autcompletecls>();
AutocompleteAdapter adpEmpleado, adpEstatus, adpDepto;
ProgressDialog dialog;
WS webservice;
public MttoBitacoraFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view=inflater.inflate(R.layout.fragment_mtto_bitacora, container, false);
String[][] para = new String[0][0];
actEmpleado = (AutoCompleteTextView)view.findViewById(R.id.actMttoProblemaEmpleado);
actEstatus =(AutoCompleteTextView)view.findViewById(R.id.actMttoProblemaEstatus);
actDepto=(AutoCompleteTextView)view.findViewById(R.id.actMttoProblemaDepto);
ansyWS call = new ansyWS("ConEmpleadoDLL", para);
call.execute();
call.cancel(true);
while(call.getStatus() == AsyncTask.Status.RUNNING)
{
call.cancel(true);
}
if(call.getStatus() != null || call.getStatus() == AsyncTask.Status.RUNNING) {
call.cancel(true);
ansyWS call2 = new ansyWS("ConEstatusDLL",para);
call2.execute();
call2.cancel(true);
}
else {
ansyWS call2 = new ansyWS("ConEstatusDLL",para);
call2.execute();
call2.cancel(true);
}
actEmpleado.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Autcompletecls item = listEmpelado.get(position);
Toast.makeText(getContext(), item.getId(), Toast.LENGTH_SHORT).show();
}
});
actEstatus.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Autcompletecls item = listEstatus.get(position);
Toast.makeText(getContext(), item.getId(), Toast.LENGTH_SHORT).show();
}
});
return view;
}
class ansyWS extends AsyncTask<String,String,String>{
private volatile boolean running = true;
String[][] parametros;
String methodname;
SoapObject resultado;
public ansyWS(String _methodname, String[][] _parametros)
{
methodname = _methodname;
parametros = _parametros;
}
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(getActivity());
dialog.setMessage(getResources().getString(R.string.dialog_message_save));
dialog.setIndeterminate(false);
dialog.setCancelable(false);
dialog.show();
}
#Override
protected String doInBackground(String... params) {
webservice = new WS();
resultado = webservice. LlamaWS(methodname,parametros);
dialog.dismiss();
if (resultado != null) {
for (int i = 0; i < resultado.getPropertyCount(); i++) {
SoapObject datos = (SoapObject) resultado.getProperty(i);
switch (methodname) {
case "ConEmpleadoDLL":
listEmpelado.add(new Autcompletecls(datos.getProperty(0).toString(), datos.getProperty(1).toString()));
break;
case "ConEstatusDLL":
listEstatus.add(new Autcompletecls(datos.getProperty(0).toString(), datos.getProperty(1).toString()));
break;
}
}
return methodname;
} else {
return "error";
}
}
#Override
protected void onPostExecute(String s) {
while(running) {
switch (s) {
case "ConEmpleadoDLL":
actEmpleado.setThreshold(0);
adpEmpleado = new AutocompleteAdapter(getContext(), R.layout.activity_main, R.id.tv_autocomplete_text, listEmpelado);
actEmpleado.setAdapter(adpEmpleado);
break;
case "ConEstatusDLL":
actEstatus.setThreshold(0);
adpEstatus = new AutocompleteAdapter(getContext(), R.layout.activity_main, R.id.tv_autocomplete_text, listEstatus);
actEstatus.setAdapter(adpEstatus);
break;
}
}
cancel(true);
dialog.dismiss();
}
#Override
protected void onCancelled() {
running = false;
super.onCancelled();
}
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i("SomeTag", System.currentTimeMillis() / 100L + " onDestory()");
}
}

ListView shows repeated data everytime the fragment is created

Here is the code of my fragment where i am accesing a web service in asynctask to fetch data and display in list also i am lazy loading the images..When the fragment is created for the first time the output is correct it displays 7 items in the list which it should , the problem is when the fragment is recreated after being destroyed the data is repeated i.e if it started for the second time the list shows 14 items (7 from earlier and 7 are again fetched) and this happens everytime it recreates , the no. of items in list is 7 more than the previous.. Although in On destroy i cleared the data of the adapter and the adapter.getCount() shows 0 but still this problem exists.
public class ServiceCarListFragment extends Fragment {
private String url;
private ArrayList<CarDetail> carDetailList = new ArrayList<CarDetail>();
private CarListAdapter adapter;
private ListView mList ;
private ProgressDialog progressDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Log.d("Services", "On Create");
url = getActivity().getIntent().getStringExtra("url");
adapter = new CarListAdapter(getActivity() , carDetailList);
new DownloadCarDetail().execute(url);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
Log.d("Services", "On CreateView");
View v = inflater.inflate(R.layout.fragment_service_car_list, container,false);
mList = (ListView)v.findViewById(R.id.list);
mList.setAdapter(adapter);
return v;
}
class DownloadCarDetail extends AsyncTask<String, String, ArrayList<CarDetail>>{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = ProgressDialog.show(getActivity(), null, "Loading...",true);
}
#Override
protected ArrayList<CarDetail> doInBackground(String... params) {
// TODO Auto-generated method stub
ArrayList<CarDetail> carDetailList = JsonParser.parseJson(params[0]);
return carDetailList;
}
#Override
protected void onPostExecute(ArrayList<CarDetail> carDetailList) {
// TODO Auto-generated method stub
//ServiceCarListFragment.this.carDetailList = carDetailList;
//adapter = new CarListAdapter(getActivity(),ServiceCarListFragment.this.carDetailList);
//mList.setAdapter(adapter);
progressDialog.dismiss();
ServiceCarListFragment.this.carDetailList.addAll(carDetailList);
adapter.notifyDataSetChanged();
for (CarDetail car : carDetailList) {
// START LOADING IMAGES FOR EACH STUDENT
car.loadImage(adapter);
}
}
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
carDetailList.clear();
adapter.notifyDataSetChanged();
Log.d("Services", String.valueOf(adapter.getCount()));
}
#Override
public void onDestroyView() {
// TODO Auto-generated method stub
super.onDestroyView();
Log.d("Services", "On DestroyView");
}
#Override
public void onDetach() {
// TODO Auto-generated method stub
super.onDetach();
Log.d("Services", "On Detach");
}
#Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
Log.d("Services", "On Attach");
}
}
This is the custom adapter i am using
public class CarListAdapter extends BaseAdapter {
private ArrayList<CarDetail> items = new ArrayList<CarDetail>();
private Context context;
public CarListAdapter(Context context , ArrayList<CarDetail> items) {
super();
this.context = context;
this.items = items;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return items.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Log.d("Inside", "GetView");
LayoutInflater mInflater = (LayoutInflater)context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
ViewHolder holder = null;
CarDetail car = items.get(position);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.car_list_row, parent , false);
holder = new ViewHolder();
holder.tvCarName = (TextView) convertView.findViewById(R.id.tvCarName);
holder.tvDailyPriceValue = (TextView) convertView.findViewById(R.id.tvWeeklyPriceValue);
holder.tvWeeklyPriceValue = (TextView) convertView.findViewById(R.id.tvWeeklyPriceValue);
holder.imgCar = (ImageView) convertView.findViewById(R.id.imgCar);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvCarName.setText(car.getCarName());
if (car.getImage() != null) {
holder.imgCar.setImageBitmap(car.getImage());
} else {
// MY DEFAULT IMAGE
holder.imgCar.setImageResource(R.drawable.ic_action_call);
}
return convertView;
}
static class ViewHolder {
TextView tvCarName;
TextView tvDailyPriceValue;
TextView tvWeeklyPriceValue;
ImageView imgCar;
}
}
This is the model class
public class CarDetail {
private String carId;
private String carName;
private String imageUrl;
private String thumbUrl;
private String dailyPrice;
private String weeklyPrice;
private String weekendPrice;
private String deposit;
private String minimumAge;
private String color;
private String make;
private String location;
private String bodyType;
private String fuelType;
private String transmission;
private String carType;
private String model;
private String description;
private Bitmap image;
private Bitmap thumbImage;
private CarListAdapter carAdapter;
public CarDetail() {
super();
// TODO Auto-generated constructor stub
}
public CarDetail(String carId, String carName, String imageUrl,
String thumbUrl, String dailyPrice, String weeklyPrice,
String weekendPrice, String deposit, String minimumAge,
String color, String make, String location, String bodyType,
String fuelType, String transmission, String carType, String model,
String description) {
super();
this.carId = carId;
this.carName = carName;
this.imageUrl = imageUrl;
this.thumbUrl = thumbUrl;
this.dailyPrice = dailyPrice;
this.weeklyPrice = weeklyPrice;
this.weekendPrice = weekendPrice;
this.deposit = deposit;
this.minimumAge = minimumAge;
this.color = color;
this.make = make;
this.location = location;
this.bodyType = bodyType;
this.fuelType = fuelType;
this.transmission = transmission;
this.carType = carType;
this.model = model;
this.description = description;
// TO BE LOADED LATER - OR CAN SET TO A DEFAULT IMAGE
this.image = null;
this.thumbImage = null;
}
public String getCarId() {
return carId;
}
public void setCarId(String carId) {
this.carId = carId;
}
public String getCarName() {
return carName;
}
public void setCarName(String carName) {
this.carName = carName;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getThumbUrl() {
return thumbUrl;
}
public void setThumbUrl(String thumbUrl) {
this.thumbUrl = thumbUrl;
}
public String getDailyPrice() {
return dailyPrice;
}
public void setDailyPrice(String dailyPrice) {
this.dailyPrice = dailyPrice;
}
public String getWeeklyPrice() {
return weeklyPrice;
}
public void setWeeklyPrice(String weeklyPrice) {
this.weeklyPrice = weeklyPrice;
}
public String getWeekendPrice() {
return weekendPrice;
}
public void setWeekendPrice(String weekendPrice) {
this.weekendPrice = weekendPrice;
}
public String getDeposit() {
return deposit;
}
public void setDeposit(String deposit) {
this.deposit = deposit;
}
public String getMinimumAge() {
return minimumAge;
}
public void setMinimumAge(String minimumAge) {
this.minimumAge = minimumAge;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getBodyType() {
return bodyType;
}
public void setBodyType(String bodyType) {
this.bodyType = bodyType;
}
public String getFuelType() {
return fuelType;
}
public void setFuelType(String fuelType) {
this.fuelType = fuelType;
}
public String getTransmission() {
return transmission;
}
public void setTransmission(String transmission) {
this.transmission = transmission;
}
public String getCarType() {
return carType;
}
public void setCarType(String carType) {
this.carType = carType;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Bitmap getImage() {
return image;
}
public void setImage(Bitmap image) {
this.image = image;
}
public Bitmap getThumbImage() {
return thumbImage;
}
public void setThumbImage(Bitmap thumbImage) {
this.thumbImage = thumbImage;
}
public void loadImage(CarListAdapter carAdapter) {
// HOLD A REFERENCE TO THE ADAPTER
this.carAdapter = carAdapter;
if (thumbUrl != null && !thumbUrl.equals("")) {
new ImageLoadTask().execute(thumbUrl);
}
}
// ASYNC TASK TO AVOID CHOKING UP UI THREAD
private class ImageLoadTask extends AsyncTask<String, String, Bitmap> {
#Override
protected void onPreExecute() {
Log.i("ImageLoadTask", "Loading image...");
}
// PARAM[0] IS IMG URL
protected Bitmap doInBackground(String... param) {
Log.i("ImageLoadTask", "Attempting to load image URL: " + param[0]);
try {
Bitmap b = JsonParser.downloadBitmap(param[0]);
return b;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
protected void onProgressUpdate(String... progress) {
// NO OP
}
protected void onPostExecute(Bitmap ret) {
if (ret != null) {
Log.i("ImageLoadTask", "Successfully loaded " + carName + " image");
image = ret;
if (carAdapter != null) {
// WHEN IMAGE IS LOADED NOTIFY THE ADAPTER
carAdapter.notifyDataSetChanged();
}
} else {
Log.e("ImageLoadTask", "Failed to load " + carName + " image");
}
}
}
You need to clear ArrayList Data just before your next call of Async Method.
In your case it would be carDetailLis.clear() new DownloadCarDetail().execute(url); or just check the flow and clear it.
I suggest to you to modify
ServiceCarListFragment.this.carDetailList.addAll(carDetailList);
in
ServiceCarListFragment.this.carDetailList = new ArrayList...
carDetailList.addAll
And you should verify if the length of carDetailList is the same after several calls to the server.

Unable to retrieve Array from Aync task in Activity Using Universal Image Loader for Android and Flickr

I am trying to fetch a list of photos from a photo set in flickr
using universal image loader
My Base Activity ImagePagerActivity calls FetchPhotos which extends Async Task.
Code Follows
public class ImagePagerActivity extends BaseActivity {
private static final String STATE_POSITION = "STATE_POSITION";
public static final String API_KEY="mykey";
public static final String USER_ID="myid";
DisplayImageOptions options;
private Photos thePhotoList;
ViewPager pager;
private String thePhotos="";
private final int[] timeout={3,10};
private String url="http://www.flickr.com/services/rest/?method=flickr.photosets.getPhotos&format=json&api_key="+API_KEY+"&photoset_id=111111111";
private String[] imageUrls;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ac_image_pager);
Bundle bundle = getIntent().getExtras();
String url="http://www.flickr.com/services/rest/?method=flickr.photosets.getPhotos&format=json&api_key="+API_KEY+"&photoset_id=72157633359614452";
setContentView(R.layout.pics);
try{
((ViewAnimator)findViewById(R.id.PictureAnimator)).removeAllViews();
}catch (Exception e) {}
thePhotoList = new Photos(url);
thePhotoList.execute();
imageUrls=thePhotoList.imageList;
//imageUrls = bundle.getStringArray(Extra.IMAGES);
int pagerPosition = bundle.getInt(Extra.IMAGE_POSITION, 0);
if (savedInstanceState != null) {
pagerPosition = savedInstanceState.getInt(STATE_POSITION);
}
options = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error)
.resetViewBeforeLoading()
.cacheOnDisc()
.imageScaleType(ImageScaleType.EXACTLY)
.bitmapConfig(Bitmap.Config.RGB_565)
.displayer(new FadeInBitmapDisplayer(300))
.build();
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(new ImagePagerAdapter(this.imageUrls));
pager.setCurrentItem(pagerPosition);
}
private class Photos extends com.flickr.FetchPhotos{
#Override
public void onFetchError() {}
public Photos(String url) {super(ImagePagerActivity.this, url);}
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putInt(STATE_POSITION, pager.getCurrentItem());
}
private class ImagePagerAdapter extends PagerAdapter {
private String[] images;
private LayoutInflater inflater;
ImagePagerAdapter(String[] images) {
this.images = images;
inflater = getLayoutInflater();
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((View) object);
}
#Override
public void finishUpdate(View container) {
}
#Override
public int getCount() {
return images.length;
}
#Override
public Object instantiateItem(ViewGroup view, int position) {
View imageLayout = inflater.inflate(R.layout.item_pager_image, view, false);
ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image);
final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);
imageLoader.displayImage(images[position], imageView, options, new SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
spinner.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
String message = null;
switch (failReason.getType()) {
case IO_ERROR:
message = "Input/Output error";
break;
case DECODING_ERROR:
message = "Image can't be decoded";
break;
case NETWORK_DENIED:
message = "Downloads are denied";
break;
case OUT_OF_MEMORY:
message = "Out Of Memory error";
break;
case UNKNOWN:
message = "Unknown error";
break;
}
Toast.makeText(ImagePagerActivity.this, message, Toast.LENGTH_SHORT).show();
spinner.setVisibility(View.GONE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
spinner.setVisibility(View.GONE);
}
});
((ViewPager) view).addView(imageLayout, 0);
return imageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
#Override
public Parcelable saveState() {
return null;
}
#Override
public void startUpdate(View container) {
}
}
}
next is the FetchPhotos class
public abstract class FetchPhotos extends AsyncTask<Void, Void, Boolean>{
private Context context;
private ProgressDialog pd;
private String thePhotos="";
private String url;
private final int[] timeout={3,10};
public ArrayList<PictureInfo> thePics;
public String[] imageList;
public FetchPhotos(Context context,String url) {
this.context=context;
this.url=url;
}
public String[] fillGalery(JSONObject theFeed) {
// TODO Auto-generated method stub
String[] imageUrls = null;
try{
JSONArray Categories=theFeed.getJSONArray("photo");
imageUrls=new String[Categories.length()];
for (int i=0;i<(Categories.length()>15?15:Categories.length());i++){
JSONObject pic = Categories.getJSONObject(i);
String url1="http://farm"+pic.getString("farm")+".staticflickr.com/"+pic.getString("server")+"/"+
pic.getString("id")+"_"+pic.getString("secret")+".jpg";
imageUrls[i]=url1;
System.out.println(imageUrls[i]);
}
return imageUrls;
}
catch(Exception e){
}
return imageUrls;
}
#Override
protected void onPreExecute() {
pd=ProgressDialog.show(context, "downloading", "please wait");
super.onPreExecute();
}
#Override
protected Boolean doInBackground(Void... arg0) {
try{
thePhotos = new Internet().GetRequest(url, null, timeout);
return true;
}catch (Exception e) {
return false;
}
}
#Override
protected void onPostExecute(Boolean result) {
pd.dismiss();
if(result){
try {
thePhotos=thePhotos.split("\\(")[1];
thePhotos.replace("\\)", "");
imageList=fillGalery(new JSONObject(thePhotos).getJSONObject("photoset"));
} catch (Exception e) {Log.e("karp", "photolist2: "+e.getMessage());onFetchError();onFetchError();}
}else{
onFetchError();
}
super.onPostExecute(result);
}
public abstract void onFetchError();
public void LoadPhoto(PictureInfo pi){
Log.d("karp", "LoadPhoto");
if(!(pi.executed)){
new LoadPics(pi).execute();
pi.executed=true;
}
}
private class LoadPics extends RemoteImage{
private ImageView ivTarget;
private ProgressBar pb;
public LoadPics(PictureInfo pi) {
super(pi.url);
this.ivTarget=pi.iv;
this.pb=pi.pb;
}
#Override
public void onSuccess(Bitmap remoteBitmap) {
try{
pb.setVisibility(View.INVISIBLE);
ivTarget.setImageBitmap(remoteBitmap);
}catch (Exception e) {}
}
#Override
public void onFail() {pb.setVisibility(View.INVISIBLE);}
}
}
I have created Photos class in Image Pager
and then Im trying to access fill gallery
Now Im trying to fill a string array with the image urls from flickr
using the method fillGallery that reurns a string array
In my base activity im calling
thePhotoList = new Photos(url);
thePhotoList.execute();
imageUrls=thePhotoList.imageList;
but try as i may i cant get an array in imageUrls which is a String Array.
When i use a hard coded string array with urls for images in it, the code works.
Any help would be really appreciated.
Im sure im doing something very silly as I am new to this.
Many thanks . Cheers!
I got it to work . Needed to add a listener interface , call the method from onPostExecute,
Implement it in the activity, access the variable in the implementation of the listeners abstract method. Should have researched a bit more before posting,but was stuck with the problem too long . Apologies.

Categories

Resources