How to assing an Image to Imageview based on a query results? - android

Good afternoon everyone,
I have a quick question. I have a query result that I store in a list/array and I am trying to display the appropriate image in the imageview. The query provides a name of the image that is stored in the resource folder(res/drawable). I am getting error syntax. I am not sure how to solve this issue. I have a database that stores the name of the image in a field (database) called spic.
I have tried this code:
how to work with images and database in android?
but it doesnt work in this class. I am not sure is it because this class is "extends ArrayAdapter {" instead of "extends Activity {"
here is my code:
zCustomUsersAdapter class:
package com.example.yao;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class zCustomUsersAdapter extends ArrayAdapter<YAOYVD> {
public zCustomUsersAdapter(Context context, List<YAOYVD> users) {
super(context, 0, users);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
// User user = getItem(position);
YAOYVD user = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.zitem_user, parent, false);
}
// Lookup view for data population
TextView tvName = (TextView) convertView.findViewById(R.id.tvName);
TextView tvHome = (TextView) convertView.findViewById(R.id.tvHometown);
ImageView tvImage = (ImageView) convertView.findViewById(R.id.ivUserIcon);
// Populate the data into the template view using the data object
tvName.setText(String.valueOf(user.getID_YAO()));
//.name);
tvHome.setText(String.valueOf(user.getNAME_YAO()));
//.hometown);
// tvImage.setBackgroundResource( getResourceID (String.valueOf(user.getSPIC_YAO()), "drawable",getApplicationContext() ));
// Return the completed view to render on screen
tvImage.setBackgroundResource(user.getSPIC_YAO()); //getSpic_YAO this is string in the YAO class. getSpic_YAO retrive the name of the image in the drawable folder.
return convertView;
}
}
zCustomListActivity
package com.example.yao;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.database.SQLException;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
public class zCustomListActivity extends Activity {
private YAOGetDataSource2 datasource;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.zactivity_custom_list);
//calling the method to create the database from asset folder
copydbfromassest();
// datasource = new YAODeckListDataSource(this);
datasource = new YAOGetDataSource2(this);
datasource.open();
populateUsersList();
}
private void populateUsersList() {
// Construct the data source
//List<YAOYVD> values = datasource.SQLYVDTABLESEARCH();
List<YAOYVD> arrayOfUsers = datasource.SQLYVDTABLESEARCH();
//.getUsers();
// Create the adapter to convert the array to views
zCustomUsersAdapter adapter = new zCustomUsersAdapter(this, arrayOfUsers);
// Attach the adapter to a ListView
ListView listView = (ListView) findViewById(R.id.lvUsers);
listView.setAdapter(adapter);
}
//#Override
public void onClick(View view) {
// TODO Auto-generated method stub
}
//database open and close
#Override
protected void onResume() {
datasource.open();
super.onResume();
}
#Override
protected void onPause() {
datasource.close();
super.onPause();
}
#Override
protected void onDestroy(){
datasource.close();
super.onDestroy();
}
/****
* new things to considered
*/
///copy the database from assest folder
private void copydbfromassest() {
// TODO Auto-generated method stub
YAOMySQLiteHelper myhelper = new YAOMySQLiteHelper (this);
try{
//create datbase
myhelper.importIfNotExist();
}catch (IOException e){
throw new Error("Unable to Create the Database ");
}
try{
myhelper.openDataBase();
}catch (SQLException sqle){
throw sqle;
}
}
}

You need to retrieve the resource identifier associated with that image's name. For this, you will need to get your app's Resources, which requires a context.
Context ctx = getContext();
int resId = ctx.getResources().getIdentifier(user.getSPIC_YAO(), "drawable", ctx.getPackageName());
if(resId != 0){
tvImage.setBackgroundResource(resId);
}

Related

gridview custom adapter search

i have grid view , and custom adapter i want to search the items that are in the grid view by a search view ,,,
the thing is i don't know how to implement a search view along with a custom adopter ,, because i have a click event in the custom adapter which is when the user clicks an item it downloads a pdf file form internet ,, how can i add search view that will search the grid view items in with the custom adapter click even running ,
i am new usually i copy and paste the code i am 30% new .
this is my main activity
package com.alhaddadsoft.ammar.gridview;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.SearchView;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
GridView gv;
GridView gv1;
TextView newtext;
Context context;
ArrayList prgmName;
public static String [] prgmNameList={"احمد عبده ماهر","احمد داوود","احمد صبحي منصور","لكشف الموروث اقرأ هذا أولا","الختان للذكور والاناث","الصادق النيهوم","الطريق إلى بيت المقدس","اوشو","بن فرناس","جمال البنا","جورج طرابيشي","زكريا اوزون", "سلامه موسى","سلسلة عندما نَطَقَ السراة","عبد الرزاق جبران","عبد الله القصيمي","علي الوردي","علي شريعتي","فاضل الربيعي","فرج فوده","كمال الصليبي","محمد اركون","محمد شحرور","محمد علي المحمود","محمود ابو ريه","نيازي عز الدين","هشام جعيط"
,"أبو الأعلى المودودي - الخلافة والملك","أسوار الصمت قراءة في الحقوق المدنية في السعودية لـ د. وليد الماجد","احمد امين - فجر الاسلام","اعمدة الحكمة السبعة . لورنس العرب","الارهابى ",
" الاسلام واصول الحكم -- على عبد الرازق","الاسلام وجراب الحاوي . شاكر النابلسي","الاضافة النوعية القرانية.مصطفى بوهندي",
"التأثير المسيحي في تفسير القران","التوراة اليهودية مكشوفة على حقيقتها","الخلافه الاسلاميه.محمد سعيد عشماوي","الدولة الاسلامية ،الجذور والتوحش عبدالباري عطوان","الدين واحتكار الحقيقه.واثق غازي","السادس من نوفمبر قيادة المراة للسيارة","السلطة في الاسلام لعبدالجواد حسين","السلفيون ايضا يدخلون النار.وليد طوغان","السنة بين الاصول والتاريخ ذويب رسالة دكتوراة","العقل الايماني","القران وثالوث الاستبداد.نشأت جعفر",
"القران ولغة السريان. احمد علي الجمل","اللاهوت العربى-يوسف زيدان","المؤمن الصادق - إيريك هوفر","الملوك المحتسبون حجم صغير","امي كاملة عقل ودين","انتكاسة المسلمين الى الوثنية - سيد القمني","بالداخل . اشرف فياض","بالداخل . اشرف فياض","تاريخ نجد . بن غنام مؤرخ محمد بن عبدالوهاب","تحرير المرأه من عهد الرساله","تزييف الاسلام.انور اسحاق","جغرافية التوراة _زياد منى","حتى لا يعود جهيمان . توما ... غهامر . ستيفان لاكروا",
"حكاية التدين السعودي . وحيد الغامدي","حواء والخطيئة","حوار حول القران وحده . محمد توفيق صدقي","رجم الزاني","طبائع الإستبداد ومصارع الإستعباد","عبد الرزاق عيد .. سدنة هياكل الوهم , نقد العقل الفقهي","عبيد بلا اغلال.تاريخ جزيرة العرب القريب","فتنة القول بتعليم البنات.عبدالله الوشمي","قدماء المصريين اول الموحدين","كارثة فلسطين . عبدالله التل","لعبة الامم","ما بعد الشيوخ ، انهيار ممالك الخليج","مابعد الصحوة.عبدالله الغذامي","مشكلة الحديث","معجزة اختيار اللفظ في القرآن",
"مقالة العبودية الطوعية","من يجرؤ على الكلام .بول فندلي","نقد الخطاب الديني لنصر ابو زيد","نقد الخطاب السلفي ابن تيمية نموذجا.رائد السمهوري","ورثة محمد .جذور الخلاف السني الشيعي"
};
public static int [] prgmImages={R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon
,R.drawable.book1,R.drawable.book2,R.drawable.book3,R.drawable.book4,R.drawable.book5,R.drawable.book6,R.drawable.book7,R.drawable.book8,R.drawable.book9,R.drawable.book10,R.drawable.book11,R.drawable.book12,R.drawable.book13,R.drawable.book14,R.drawable.book15,R.drawable.book16,R.drawable.book17,R.drawable.book18,R.drawable.book19,R.drawable.book20,R.drawable.book21_,R.drawable.book21,R.drawable.book22,R.drawable.book23,R.drawable.book24,R.drawable.book25,R.drawable.book26,R.drawable.book27,R.drawable.book28,R.drawable.book29,R.drawable.book30,R.drawable.book31,R.drawable.book32,R.drawable.book33,R.drawable.book34,R.drawable.book35,R.drawable.book36_,R.drawable.book36,R.drawable.book37,R.drawable.book38,R.drawable.book39,R.drawable.book40,R.drawable.book41,R.drawable.book42,R.drawable.book43,R.drawable.book44,R.drawable.book45,R.drawable.book46,R.drawable.book47,R.drawable.book48,R.drawable.book49,R.drawable.book50,
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gv=(GridView) findViewById(R.id.gridView1);
gv.setAdapter(new CustomAdapter(this, prgmNameList, prgmImages));
}
public void openactivity1(){
edittext();
//Intent i = new Intent(this, AhmedDaod.class);
// startActivity(i);
}
public void edittext(){
// newtext = (TextView)findViewById(R.id.textView5);
// newtext.setText("hello");
}
}
This is my CustomAdapter acteivity
package com.alhaddadsoft.ammar.gridview;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class CustomAdapter extends BaseAdapter {
String[] result;
Context context;
int[] imageId;
private static LayoutInflater inflater = null;
String dwnload_file_path;
String file_name;
String imageViewD;
String textViewD;
GridView gridview;
public CustomAdapter(MainActivity mainActivity, String[] prgmNameList, int[] prgmImages ) {
// TODO Auto-generated constructor stub
result = prgmNameList;
context = mainActivity;
imageId = prgmImages;
inflater = (LayoutInflater) context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return result.length;
}
#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;
ImageView img;
TextView edit ;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final Holder holder = new Holder();
View rowView;
rowView = inflater.inflate(R.layout.programlist, null);
holder.tv = (TextView) rowView.findViewById(R.id.textView1);
holder.img = (ImageView) rowView.findViewById(R.id.imageView1);
holder.tv.setText(result[position]);
holder.img.setImageResource(imageId[position]);
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Toast.makeText(context, "You Clicked " + result[position], Toast.LENGTH_LONG).show();
// String displayedText = ((TextView)((LinearLayout)myToast.getView()).getChildAt(0)).getText().toString();
try {
if (result[position].equals("أبو الأعلى المودودي - الخلافة والملك")) {
new AlertDialog.Builder(context)
.setTitle("تحميل الكتاب")
.setMessage("هل تريد تحميل الكتاب?")
.setPositiveButton("تحميل", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
dwnload_file_path = "http://www.jouhinabooks.com/get_file.php?id=470";
file_name = "book1.pdf";
imageViewD = "book1";
textViewD = result[position];
Downloadmethode();
}
})
.setNegativeButton("رجوع", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
//Intent intent= new Intent(context, AhmedDaod.class);
// intent.putextra("your_extra","your_class_value");
//context.startActivity(intent);
//MainActivity openactivity = new MainActivity();
// openactivity.openactivity1();
//edittext.setText("hello");
}
} catch (final Exception e) {
Toast.makeText(context, "error ", Toast.LENGTH_LONG).show();
}
}
});
return rowView;
}
public void Downloadmethode(){
Intent d = new Intent(context, DownloadBook.class);
d.putExtra("dwnload_file_path", dwnload_file_path);
d.putExtra("file_name", file_name);
d.putExtra("imageViewD",imageViewD);
d.putExtra("textViewD",textViewD);
context.startActivity(d);
}
}
This is how I implemented the search feature. Create two Lists, the searchList and the backUpList.
backUpList = loadMyData();
searchList.addAll(backUpList);
Now you have two lists that contain the same data. And because the lists contain only references to the objects there is no extra memory being used. Then feed the searchList to the adapter instead of the actual list.
adapter = new CustomAdapter(searchList*/,...other inputs*/);
gridView.setAdapter(adapter);
And now when you want to search in your data you empty your search list and search in you back up list. If an object should be shown then add it in your search list. Then notify the adapter and your search results are shown.
searchList.clear();
searchList.addAll(backUpList);
for(CustomObject object:backUpList){
if(meetsSearchCriteria(object)){
searchList.add(object);
}
}
adapter.notifyDataSetChanged();
And adjust the rest of your code to work with the searchList instead of the actual data list.
You must change your adapter to take an ArrayList of objects as input and not a table as your code shows. Tables do not support changes in their size after their creation.

cannot add column with 'put' method in Parse database

I'm developing real-time messenger application with Parse and want to display all of users in ListView. So I also want to reference if user is online or offline, I tried 'put' method to add column named "online" and put information about it. When it went wrong, I added that column myself, but it still did not work. Here it's what I tried in UserList class at all:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseUser;
import java.util.ArrayList;
import java.util.List;
public class UserList extends AppCompatActivity {
public static ArrayList<ParseUser> userList;
public static String TAG = "UserList";
public static ParseUser user = new ParseUser();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_list);
updateUserStatus(true);
}
#Override
protected void onDestroy() {
super.onDestroy();
updateUserStatus(false);
}
#Override
protected void onResume() {
super.onResume();
loadUserList();
}
private void updateUserStatus(boolean isOnline) {
user.put("online", isOnline);
user.saveEventually();
//System.out.println("getBoolean's result : " + user.getBoolean("online"));
}
private void loadUserList() {
ParseUser.getQuery().whereNotEqualTo("username", user.getUsername()).findInBackground(new FindCallback<ParseUser>() {
#Override
public void done(List<ParseUser> objects, ParseException e) {
if (objects != null) {
if (objects.size() == 0) System.out.println("No user found");
userList = new ArrayList<>(objects);
ListView list = (ListView) findViewById(R.id.userList);
list.setAdapter(new UserAdapter(UserList.this));
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
startActivity(new Intent(UserList.this, MainActivity.class));
finish();
}
});
}
else {
System.out.println("exception detected while loading user list");
e.printStackTrace();
}
}
});
}
}
UserAdapter class:
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.parse.ParseUser;
public class UserAdapter extends BaseAdapter {
public static String TAG = "UserAdapter";
public TextView labelname;
LayoutInflater layoutInflater;
public UserAdapter(Context context){
layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return UserList.userList.size();
}
#Override
public ParseUser getItem(int index) {
return UserList.userList.get(index);
}
#Override
public long getItemId(int index) {
return index;
}
#Override
public View getView(int pos, View v, ViewGroup group) {
ParseUser c = getItem(pos);
if (v == null) {
v = layoutInflater.inflate(R.layout.chat_item, null);
}
labelname = (TextView) v;
labelname.setText(c.getUsername());
labelname.setCompoundDrawablesWithIntrinsicBounds(c.getBoolean("online") ? R.drawable.ic_online
: R.drawable.ic_offline, 0, R.drawable.arrow, 0);
return v;
}
}
I tried saveInBackground with SaveCallback, but it throws exception named:
Caused by: java.lang.IllegalArgumentException: Cannot save a ParseUser until it has been signed up. Call signUp first
But I'm puzzled more than I was 1 hour ago. I authorize my user in another class and it seems not to be problem.
This was open bug of Parse. might be possible that not solved yet. look at this and this too.
instead of saveEventually() use saveInBackground()
and
you can't do like that
ParseUser user = new ParseUser();
if you want logged user than get like this
ParseUser user = ParseUser.getCurrentUser();
and before getting logged user you must do sign up

Android list view current position doesn't work properly

I'm Getting data from my database and pushing them into ListView to view all the data.
Inside my ListView I also have a TextView with the text "Like" in it. Now when I click the like text it will change to "Liked" and I'm updating my like status in my database.
Now my problem is that when i click the "Like" text, the text changes to "Liked" and also it is updated in DB. But also when I scroll through the List View, I can notice other lists' Like text is also changed to Liked. I'm not sure what's going wrong.
I've been trying to get around this problem for quite some days but had no success.
This is my adapter code. At the bottom you can see my onClickListener for the textview
package com.mytestapp.myapp;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ForumAdapter extends ArrayAdapter<DiscussionList> {
private static List<DiscussionList> items = null;
public ForumAdapter(Context context, List<DiscussionList> items) {
super(context, R.layout.custom_list, items);
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
public static DiscussionList getModelPosition(int position) {
return items.get(position);
}
public void refill(List<DiscussionList> items) {
items.clear();
items.addAll(items);
notifyDataSetChanged();
}
public static class ViewHolder {
WebView mywebviewholder;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
View v = convertView;
if (v == null) {
LayoutInflater li = LayoutInflater.from(getContext());
v = li.inflate(R.layout.custom_list, null);
} else {
holder = (ViewHolder) convertView.getTag();
}
DiscussionList app = items.get(position);
if (app != null) {
TextView titleText = (TextView) v.findViewById(R.id.dscTitle);
TextView categoryText = (TextView) v.findViewById(R.id.dscCategory);
TextView descriptionText = (TextView) v
.findViewById(R.id.dscDescription);
TextView timeText = (TextView) v.findViewById(R.id.dscTime);
TextView idText = (TextView) v.findViewById(R.id.dscDiscId);
final TextView likeText = (TextView) v.findViewById(R.id.likeText1);
String like_Status = app.getLikeStatus();
titleText.setText(app.getTitle());
categoryText.setText(app.getCategory());
descriptionText.setText(app.getDescription());
timeText.setText(app.getTime());
idText.setText(app.getDiscId());
if (like_Status == "null") {
likeText.setText("Like");
} else {
likeText.setText("Liked");
}
final String dId = app.getDiscId();
// onClick for image button inside list view
likeText.setTag(new Integer(position));
likeText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Integer myposition = (Integer) view.getTag();
// Toast.makeText(getContext(), "" + dId,
// Toast.LENGTH_SHORT)
// .show();
likeText.setText("Liked");
MainActivity val = new MainActivity();
val.updateLikeTable(dId);
}
});
}
return v;
}
}
And also this is my MainActivity.java file where i update the likes in database
package com.mytestapp.myapp;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ListActivity implements FetchDataListener {
public static String strTitle = "0", strCategory = "0",
strDescription = "0", strTime = "0", strDid = "0";
Collegemate_DB db = new Collegemate_DB(this);
int likeStatus = 1;
private ProgressDialog dialog;
public static String usId=null;
ImageButton imgButton;
List<DiscussionList> items = new ArrayList<DiscussionList>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_forum_topics);
usId = db.getCurrentuserId();
initView();
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
/*
* On click listener to get values from DiscussionList class and send it
* to another activity when clicking on the list item
*/
ListView forumList = getListView();
forumList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Get position of the clicked list item from adapter
String dTitle, dCategory, dDescription, dTime, dDid;
DiscussionList accessVar = ForumAdapter
.getModelPosition(position);
dTitle = accessVar.getTitle();
dCategory = accessVar.getCategory();
dDescription = accessVar.getDescription();
dTime = accessVar.getTime();
dDid = accessVar.getDiscId();
/*
* Storing the forum values in string and passing it to another
* activity
*/
String values[] = { dTitle, dCategory, dDescription, dTime,
dDid };
Intent i = new Intent(MainActivity.this, ForumFullView.class);
i.putExtra("sendData", values);
startActivity(i);
}
});
}
private void initView() {
// show progress dialog
Log.i("j","Inside Init");
dialog = ProgressDialog.show(this, "", "Loading...");
String url = "http://example.com/mypath/listData.php?currentUser_id="
+ usId;
Log.i("Fetch Url : ", url);
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
}
#Override
public void onFetchComplete(List<DiscussionList> data) {
// dismiss the progress dialog
if (dialog != null)
dialog.dismiss();
// create new adapter
ListView forumList = getListView();
// set the adapter to list
ForumAdapter adapter = new ForumAdapter(this, data);
if (forumList.getAdapter() == null) {
//final ForumAdapter adapter = new ForumAdapter(this, data);
forumList.setAdapter(adapter);
} else {
((ForumAdapter) forumList.getAdapter()).refill(items);
}
// setListAdapter(adapter);
}
#Override
public void onFetchFailure(String msg) {
// dismiss the progress dialog
if (dialog != null)
dialog.dismiss();
// show failure message
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
public void updateLikeTable(String dId,List<DiscussionList> items) {
try {
String likeUrl = "http://example.com/mypath/createlike.php?discId="
+ dId + "&userId=" + usId + "&like_status=" + likeStatus;
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(likeUrl));
client.execute(request);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Any help is appreciated.
Thanks in advance
The problem you're having is that the ListView widget recycles its views if it can. Once a view is off the screen from scrolling, it goes onto a garbage heap so that when a new view scrolls into place it can be reused, rather than requiring a fresh one to be inflated from scratch. That recycled view is the convertView parameter in the getView() method. When your ListView is first populating, convertView will always be null, since the garbage pile has nothing in it, so you're forced to inflate new views, but subsequent calls will likely have that parameter as non-null.
The practical result of this is that when a clicked view that's been set to "Liked" gets recycled, the TextView is still there and still populated with "Liked" rather than the presumed default of "Like". So if you click a view, then scroll down so it goes off the screen, it'll come back around and cause the bug you're seeing.
What you'll probably want to do to fix this is to set the text of likeText within getView() every time, based on what it is in your database. If the post has been liked, set it to "Liked", and if it hasn't, set it to "Like". It should just be one more line, assuming you have easy access to whether or not the post is liked from your DiscussionList object.
P.S. As a side note, hard-coded strings are typically frowned upon in Android, so you may want to move your "Liked" string into the resource files. It's not really necessary unless you're planning to do translations, but it's still good practice.

Listview not displaying the right image in android

In my app I have a listview. Each listview item contains an image view and several textviews. To display the image I use Drawable. But the images are displayed in the wrong row when scrolling. The image in a row changes several times until the right image appears. I have searched the web but I found nothing working for me. I am posting my code below. Please help me! Thanks in advance!
MainActivity.java
package com.makemyandroidapp.example.stacksites;
import java.io.FileNotFoundException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
private SitesAdapter mAdapter;
private ListView sitesList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("StackSites", "OnCreate()");
setContentView(R.layout.activity_main);
//Get reference to our ListView
sitesList = (ListView)findViewById(R.id.sitesList);
//Set the click listener to launch the browser when a row is clicked.
sitesList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int pos,long id) {
String posID = mAdapter.getItem(pos).getID();
Intent i = new Intent(getApplicationContext(), PositionDesc.class);
i.putExtra("posID", posID);
startActivity(i);
}
});
/*
* If network is available download the xml from the Internet.
* If not then try to use the local file from last time.
*/
if(isNetworkAvailable()){
Log.i("StackSites", "starting download Task");
SitesDownloadTask download = new SitesDownloadTask();
download.execute();
}else{
mAdapter = new SitesAdapter(getApplicationContext(), -1, SitesXmlPullParser.getStackSitesFromFile(MainActivity.this, "StackSites.xml"));
sitesList.setAdapter(mAdapter);
}
}
//Helper method to determine if Internet connection is available.
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
/*
* AsyncTask that will download the xml file for us and store it locally.
* After the download is done we'll parse the local file.
*/
private class SitesDownloadTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... arg0) {
//Download the file
try {
Downloader.DownloadFromUrl("https://duapune.com/mobile/listaeplote.php", openFileOutput("StackSites.xml", Context.MODE_PRIVATE));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result){
//setup our Adapter and set it to the ListView.
mAdapter = new SitesAdapter(MainActivity.this, -1, SitesXmlPullParser.getStackSitesFromFile(MainActivity.this, "StackSites.xml"));
sitesList.setAdapter(mAdapter);
Log.i("StackSites", "adapter size = "+ mAdapter.getCount());
}
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
Intent objIntent = new Intent(getApplication(), TabActivity.class);
finish();
startActivity(objIntent);
}
}
SitesAdapter.java
package com.makemyandroidapp.example.stacksites;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.view.View.OnClickListener;
/*
* Custom Adapter class that is responsible for holding the list of sites after they
* get parsed out of XML and building row views to display them on the screen.
*/
public class SitesAdapter extends ArrayAdapter<StackSite> {
//ImageLoader imageLoader;
//DisplayImageOptions options;
Context c;
String url1;
String url2;
Drawable backgr;
ImageView iconImg;
int posi;
RelativeLayout row;
public SitesAdapter(Context ctx, int textViewResourceId, List<StackSite> sites) {
super(ctx, textViewResourceId, sites);
c=ctx;
}
#Override
public View getView(int pos, View convertView, ViewGroup parent){
posi=pos;
row = (RelativeLayout)convertView;
Log.i("StackSites", "getView pos = " + pos);
if(null == row){
//No recycled View, we have to inflate one.
LayoutInflater inflater = (LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = (RelativeLayout)inflater.inflate(R.layout.row_site, null);
}
//Get our View References
final TextView kompaniaTxt = (TextView)row.findViewById(R.id.nameTxt);
TextView pozicioniTxt = (TextView)row.findViewById(R.id.aboutTxt);
final TextView kategoriaTxt = (TextView)row.findViewById(R.id.kategoriaTxt);
TextView qytetiTxt = (TextView)row.findViewById(R.id.qytetiTxt);
//final ProgressBar indicator = (ProgressBar)row.findViewById(R.id.progress);
kompaniaTxt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//String emri_komp=kompaniaTxt.getText().toString().replaceAll("\\s+","%20");
String emri_komp=kompaniaTxt.getText().toString();
Intent intent=new Intent(c,CompanyDesc.class);
intent.putExtra("emri_komp", emri_komp);
intent.putExtra("url1", url1);
c.startActivity(intent);
}
});
kategoriaTxt.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
String idKateg=getItem(posi).getIdKategoria();
Intent intent=new Intent(c,CategoryList.class);
intent.putExtra("idKateg", idKateg);
intent.putExtra("url2", url2);
c.startActivity(intent);
}
});
//Set the relavent text in our TextViews
kompaniaTxt.setText(getItem(pos).getKompania());
pozicioniTxt.setText(getItem(pos).getPozicioni());
kategoriaTxt.setText(getItem(pos).getKategoria());
qytetiTxt.setText(getItem(pos).getQyteti());
url1=getItem(pos).getImgUrl();
SitesDownloadTask download=new SitesDownloadTask();
download.execute();
return row;
}
private class SitesDownloadTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... arg0) {
try { iconImg = (ImageView)row.findViewById(R.id.iconImg);
backgr=drawable_from_url(url1,"kot");
//backgr=drawable_from_url("https://duapune.com/photos/duapune#duapune.com1349707357.png","kot");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result){
iconImg.setBackground(backgr);
}
Drawable drawable_from_url(String url, String src_name) throws
java.net.MalformedURLException, java.io.IOException
{System.out.println("uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu");
return Drawable.createFromStream(((java.io.InputStream)
new java.net.URL(url.trim()).getContent()), src_name);
}
}
}
Try this..
You have to use ViewHolder for that issue
private class ViewHolder {
ImageView iconImg;
TextView kompaniaTxt,pozicioniTxt,kategoriaTxt,qytetiTxt;
}
EDIT
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder holder;
if (convertView == null) {
view = getActivity().getLayoutInflater().inflate(R.layout.row_site, parent, false);
holder = new ViewHolder();
holder.iconImg = (ImageView) view.findViewById(R.id.iconImg);
holder.kompaniaTxt = (TextView) view.findViewById(R.id.nameTxt);
holder.pozicioniTxt = (TextView) view.findViewById(R.id.aboutTxt);
//holder.kategoriaTxt = (TextView) view.findViewById(R.id.kategoriaTxt);
holder.qytetiTxt = (TextView) view.findViewById(R.id.qytetiTxt);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.kompaniaTxt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//String emri_komp=kompaniaTxt.getText().toString().replaceAll("\\s+","%20");
String emri_komp=holder.kompaniaTxt.getText().toString();
Intent intent=new Intent(c,CompanyDesc.class);
intent.putExtra("emri_komp", emri_komp);
intent.putExtra("url1", url1);
c.startActivity(intent);
}
});
holder.kategoriaTxt.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
String idKateg=getItem(posi).getIdKategoria();
Intent intent=new Intent(c,CategoryList.class);
intent.putExtra("idKateg", idKateg);
intent.putExtra("url2", url2);
c.startActivity(intent);
}
});
//Set the relavent text in our TextViews
holder.kompaniaTxt.setText(getItem(pos).getKompania());
holder.pozicioniTxt.setText(getItem(pos).getPozicioni());
holder.kategoriaTxt.setText(getItem(pos).getKategoria());
holder.qytetiTxt.setText(getItem(pos).getQyteti());
url1=getItem(pos).getImgUrl();
SitesDownloadTask download=new SitesDownloadTask();
download.execute();
return view;
}
and onPostExecute
#Override
protected void onPostExecute(Void result){
holder.iconImg.setBackground(backgr);
}
EDIT
Instead of using SitesDownloadTask AsyncTask use Universal Image Loader lib
https://github.com/nostra13/Android-Universal-Image-Loader
lazy image loader
https://github.com/thest1/LazyList

setAdapter is not calling getView.

I know this question has been asked several times, but the solutions have been specific to the askers' problems. Consequently, none of those solutions helped me, even though I tried following all of their suggestions.
So here goes.
I have a movies Activity like this. Notice that I have a MoviesAdapter inner class, that's supposed to populate the moviesDisplay ListView.
package com.example.midtermexam;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.database.DataSetObserver;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class MoviesActivity extends Activity {
public String url;
public ListView moviesDisplay;
public static ArrayList<Movie> thisMovies;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movies);
url=getIntent().getExtras().getString("url");
moviesDisplay = (ListView)findViewById(R.id.listView1);
new AsyncMoviesGet(this).execute(url);
}
public void populateListView()
{
Log.d("listview","adapter created");
Log.d("listview","Listview declared");
Log.d("listview","adapter populated");
moviesDisplay.setAdapter(new MoviesListAdapter());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.movies, menu);
return true;
}
private class MoviesListAdapter extends ArrayAdapter<Movie> {
public MoviesListAdapter() {
super(MoviesActivity.this, R.layout.movies_activity_listview, thisMovies);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Make sure we have a view to work with (may have been given null)
View movieView = convertView;
if (movieView == null) {
movieView = getLayoutInflater().inflate(R.layout.movies_activity_listview, parent, false);
}
// Find the car to work with.
return movieView;
}
}
}
The populateListView() method is called from an AsyncTask called AsyncMoviesGet, whose postExecute() looks like this.
#Override
protected void onPostExecute(ArrayList<Movie> result) {
if(result != null){
m.thisMovies = result;
m.populateListView();
Log.d("demo", result.toString());
} else{
Log.d("demo", "null result");
}
}
You can see the Log messages inside the populateListView() method. These 3 statements get executed. However, the setAdapter() function doesn't seem to call the "GetView" function.
Add stuff to ArrayAdapter at least, use mAdapter.addAll():
private MoviesListAdapter mAdapter;
. . . . . .
#Override
protected void onCreate(Bundle savedInstanceState) {
. . . . .
mAdapter = new MoviesListAdapter();
moviesDisplay.setAdapter(mAdapter);
}
. . . . .
protected void onPostExecute(ArrayList<Movie> result) {
if(result != null){
m.thisMovies = result;
mAdapter.clear();
mAdapter.addAll(result);
mAdapter.notifyDatasetInvalidated();
Log.d("demo", result.toString());
} else{
Log.d("demo", "null result");
}
}
You have to add a constructor to your Custom Adapter class, one that takes a context, resource id & a data structure containing the items you'd like to display, in this case your thisMovies.
public MoviesListAdapter(Context context, int resourceId,
ArrayList<String> viewItems)
{
super(context, resourceId, viewItems);
}
Then you have to construct your adapter based on the results you've received in your onPostExecute(). Before this is done, create an instance variable in the activity which will be used to store the adapter.
MoviesListAdapter mMovieAdapter = null;
Afterwards, construct it by changing this
moviesDisplay.setAdapter(new MoviesListAdapter());
to something like below
if(thisMovies != null && thisMovies.size() > 0) {
mMovieAdapter = new MoviesListAdapter(getApplicationContext(), R.layout.movies_activity_listview, thisMovies);
moviesDisplay.setAdapter(mMovieAdapter);
} else {
Log.w("MyApplication","onPostExecute() did not return any items!");
}
You should initialise and call adapter by this way..........this is just an e.g. you need to modify it according to your controls:
ListView lv = (ListView) v.findViewById(R.id.listview1);
ListViewAdapter adapter = new ListViewAdapter(container.getContext(),
android.R.layout.simple_list_item_1, R.id.textview1);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
And inside the custom adapter class, its constructor should also have these kind of parameters:
public ListViewAdapter(Context context,int resource, int textViewResourceId, List<YourObjectType> items) {
super(context,resource,textViewResourceId, items);
this.context1 = context;
// TODO Auto-generated constructor stub
}

Categories

Resources