I am creating application on android studio where I am web scraping data from the news site used in the code below, I am able to web scrape the text from the page and able to put them into a list but I want to know how I could retrieve the images from the site and put them in the list.
Fragment Class
final StringBuilder builder = new StringBuilder();
ArrayList<News> webnewss = new ArrayList<>();
try {
Document doc = Jsoup.connect("https://www.bbc.co.uk/search?q=little+aston&page=1").userAgent("Jsoup Scraper").get();
String heading = "div.ssrcss-v4rel9-PromoContent.e1f5wbog0 > div.ssrcss-l100ew-PromoContentSummary.e1f5wbog1 > p.ssrcss-1uw1j0b-PromoHeadline.e1f5wbog2";
Elements headerElements = doc.select(heading);
ArrayList<String> headerTitles = new ArrayList<>();
for (Element e : headerElements) {
headerTitles.add(e.text());
}
String description = "div.ssrcss-v4rel9-PromoContent.e1f5wbog0 > div.ssrcss-l100ew-PromoContentSummary.e1f5wbog1 > p:nth-child(2)";
Elements descriptionElements = doc.select(description);
ArrayList<String> descriptionTitles = new ArrayList<>();
for (Element e : descriptionElements) {
descriptionTitles.add(e.text());
}
String published = "div.ssrcss-v4rel9-PromoContent.e1f5wbog0 > div.ssrcss-3r6h34-PromoContentMetadata.e1f5wbog9 > div > dl > div:nth-child(1) > dd > span > span:nth-child(2)";
Elements publishedElements = doc.select(published);
ArrayList<String> publishedTitles = new ArrayList<>();
for (Element e : publishedElements) {
publishedTitles.add(e.text());
}
String url = "div.ssrcss-v4rel9-PromoContent.e1f5wbog0 > div.ssrcss-l100ew-PromoContentSummary.e1f5wbog1 > p.ssrcss-1uw1j0b-PromoHeadline.e1f5wbog2 > a";
Elements urlElements = doc.select(url);
ArrayList<String> urlTitles = new ArrayList<>();
for(Element e:urlElements) {
urlTitles.add(e.attr("href"));
}
for (int i = 0; i < headerTitles.size() && i < descriptionTitles.size() && i < publishedTitles.size() && i < urlTitles.size(); i++) {
News news = new News(headerTitles.get(i), descriptionTitles.get(i), publishedTitles.get(i), urlTitles.get(i));
webnewss.add(news);
}
} catch (IOException e) {
e.printStackTrace();
}
News Class
public class News {
public String heading;
public String description;
public String published;
public String link;
public News(String heading, String description, String published, String link){
this.heading = heading;
this.description = description;
this.published = published;
this.link = link;
}
list xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center_horizontal"
android:background="#drawable/customshape"
>
<TextView
android:id="#+id/textNews_headingTitle"
android:layout_width="360dp"
android:layout_height="wrap_content"
android:textSize="16dp"
android:textColor="#000000"
android:textStyle="bold"
android:paddingTop="10dp"
/>
<TextView
android:id="#+id/textNews_heading"
android:layout_width="360dp"
android:layout_height="wrap_content"
android:textSize="16dp"
android:textColor="#FFFFFF"
android:paddingBottom="2dp"/>
<TextView
android:id="#+id/textNews_descriptionTitle"
android:layout_width="360dp"
android:layout_height="wrap_content"
android:textSize="16dp"
android:textColor="#000000"
android:textStyle="bold"/>
<TextView
android:id="#+id/textNews_description"
android:layout_width="360dp"
android:layout_height="wrap_content"
android:textSize="16dp"
android:textColor="#FFFFFF"
android:paddingBottom="2dp"/>
<TextView
android:id="#+id/textNews_publishedTitle"
android:layout_width="360dp"
android:layout_height="wrap_content"
android:textSize="16dp"
android:textColor="#000000"
android:textStyle="bold"/>
<TextView
android:id="#+id/textNews_published"
android:layout_width="360dp"
android:layout_height="wrap_content"
android:textSize="16dp"
android:textColor="#FFFFFF"
android:paddingBottom="2dp"/>
<TextView
android:id="#+id/textNews_linkTitle"
android:layout_width="360dp"
android:layout_height="wrap_content"
android:textSize="18dp"
android:gravity="center"
android:textColor="#000000"
android:textStyle="bold"/>
<TextView
android:id="#+id/textNews_link"
android:layout_width="360dp"
android:layout_height="wrap_content"
android:textSize="16dp"
android:textColor="#FFFFFF"
android:paddingBottom="10dp"/>
</LinearLayout>
Adapter Class
public class ScrapingAdapter extends ArrayAdapter<News> {
private static class ViewHolder{
TextView newsTitleHeading;
TextView newsHeading;
TextView newsTitleDescription;
TextView newsDescription;
TextView newsTitlePublished;
TextView newsPublished;
TextView newsTitleLink;
TextView newsLink;
}
public ScrapingAdapter(Context context, ArrayList<News> newsInfo){
super(context, R.layout.news_layout, newsInfo);
}
#Override
public View getView(int position, #Nullable View view, #NonNull ViewGroup parent) {
News scraping = getItem(position);
ViewHolder viewHolder;
if(view == null){
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
view = inflater.inflate(R.layout.news_layout, parent, false);
viewHolder.newsTitleHeading = (TextView) view.findViewById(R.id.textNews_headingTitle);
viewHolder.newsHeading = (TextView) view.findViewById(R.id.textNews_heading);
viewHolder.newsTitleDescription = (TextView) view.findViewById(R.id.textNews_descriptionTitle);
viewHolder.newsDescription = (TextView) view.findViewById(R.id.textNews_description);
viewHolder.newsTitlePublished = (TextView) view.findViewById(R.id.textNews_publishedTitle);
viewHolder.newsPublished = (TextView) view.findViewById(R.id.textNews_published);
viewHolder.newsTitleLink = (TextView) view.findViewById(R.id.textNews_linkTitle);
viewHolder.newsLink = (TextView) view.findViewById(R.id.textNews_link);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.newsTitleHeading.setText("Title:");
viewHolder.newsHeading.setText(scraping.heading);
viewHolder.newsTitleDescription.setText("Description:");
viewHolder.newsDescription.setText(scraping.description);
viewHolder.newsTitlePublished.setText("Date Published:");
viewHolder.newsPublished.setText(scraping.published);
viewHolder.newsTitleLink.setText("Click here to open link");
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(getContext(), "You clicked" + scraping.heading, Toast.LENGTH_SHORT).show();
Intent openLinksIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(scraping.link));
getContext().startActivity(openLinksIntent);
}
});
return view;
}
}
You can try this to get image URLs. src will give all image URLs on that page.
ArrayList<String> imageLinkList = new ArrayList<>();
Elements e = doc.getElementsByTag("img");
for(Element el : e) {
String url = el.absUrl("src");
imageLinkList.add(url);
}
for (int i = 0; i < headerTitles.size() && i < descriptionTitles.size() && i < publishedTitles.size() && i < urlTitles.size() && imageLinkList.size(); i++) {
News news = new News(headerTitles.get(i), descriptionTitles.get(i), publishedTitles.get(i), urlTitles.get(i),imageLinkList.get(i));
webnewss.add(news);
}
public class News {
public String heading;
public String description;
public String published;
public String link;
public String imageLink;
public News(String heading, String description, String published, String link, String imageLink){
this.heading = heading;
this.description = description;
this.published = published;
this.link = link;
this.imageLink = imageLink;
}
Now your news object will have an image link. Add imageView in news_layout. Using Glide/Picasso render in adapter class.
Related
I have one problem with my RecyclerView - it doesn't update on the main screen after pressing on the button. It can only appear after close/open soft keeboard. I looked a lot of solutions overe here but nothing helped me. I have just a simple app which sends a request "String" to server and gets one JSON Object and next inserts it on RecyclerView. But the data in RecyclerView don't apear immediately. I'm in deadlock. Help me.
Code in the activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/sky"
tools:context=".MainActivity">
<EditText
android:id="#+id/editTextRequestCity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="#string/write_name_of_city_or_index"
android:inputType="textPersonName"
android:maxLength="30"
android:minHeight="48dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintBottom_toTopOf="#+id/recyclerViewListForecast"
app:layout_constraintEnd_toStartOf="#+id/buttonShowWeather"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/buttonShowWeather"
android:layout_width="54dp"
android:layout_height="48dp"
android:background="#drawable/search_city"
android:onClick="onClickShowWeather"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toTopOf="#+id/recyclerViewListForecast"
app:layout_constraintStart_toEndOf="#+id/editTextRequestCity"
app:layout_constraintTop_toTopOf="parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerViewListForecast"
app:layoutManager="LinearLayoutManager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/editTextRequestCity"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Code in the weather_item.xml:
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/cardViewItem"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="1dp"
app:cardCornerRadius="1dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/textViewDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:gravity="center"
android:background="#00FFFFFF"
android:textColor="#color/black"
android:textSize="15sp" />
<TextView
android:id="#+id/textViewTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:gravity="center"
android:textColor="#color/black"
android:textSize="15sp" />
<TextView
android:id="#+id/textViewFallout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:gravity="center"
android:textSize="15sp" />
<TextView
android:id="#+id/textViewDegree"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:gravity="center"
android:textColor="#color/black"
android:textSize="15sp" />
<TextView
android:id="#+id/textViewPressure"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:gravity="center"
android:textColor="#color/black"
android:textSize="15sp" />
<TextView
android:id="#+id/textViewHumidity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:gravity="center"
android:textColor="#color/black"
android:textSize="15sp" />
<TextView
android:id="#+id/textViewSpeedWind"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:gravity="center"
android:textColor="#color/black"
android:textSize="15sp" />
<TextView
android:id="#+id/textViewGustWind"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:gravity="center"
android:textColor="#color/black"
android:textSize="15sp" />
<TextView
android:id="#+id/textViewDirectionWind"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:gravity="center"
android:textSize="15sp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
Code in WeatherItem:
package com.example.forecast;
public class WeatherItem {
private String date;
private String time;
private String fallout;
private String degree;
private String pressure;
private String humidity;
private String speedWind;
private String gustWind;
private String directionWind;
public WeatherItem(String date, String time, String fallout, String degree, String pressure, String humidity, String speedWind, String gustWind, String directionWind) {
this.date = date;
this.time = time;
this.fallout = fallout;
this.degree = degree;
this.pressure = pressure;
this.humidity = humidity;
this.speedWind = speedWind;
this.gustWind = gustWind;
this.directionWind = directionWind;
}
public String getDate() {
return date;
}
public String getTime() {
return time;
}
public String getFallout() {
return fallout;
}
public String getDegree() {
return degree;
}
public String getPressure() {
return pressure;
}
public String getHumidity() {
return humidity;
}
public String getSpeedWind() {
return speedWind;
}
public String getGustWind() {
return gustWind;
}
public String getDirectionWind() {
return directionWind;
}
}
Code in WeatherAdapter:
package com.example.forecast;
public class WeatherAdapter extends RecyclerView.Adapter<WeatherAdapter.WeatherViewHolder> {
public ArrayList<WeatherItem> weatherItems;
Context context;
public WeatherAdapter(Context context, ArrayList <WeatherItem> weatherItems) {
this.context = context;
this.weatherItems = weatherItems;
}
#NonNull
#Override
public WeatherViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.weather_item, parent, false);
return new WeatherViewHolder(view);
}
#Override
public void onBindViewHolder(final WeatherViewHolder holder, int position) {
WeatherItem weatherItem = weatherItems.get(position);
holder.textViewDate.setText(weatherItem.getDate());
holder.textViewTime.setText(weatherItem.getTime());
holder.textView.setText(weatherItem.getFallout());
holder.textViewDegree.setText(weatherItem.getDegree());
holder.textViewPressure.setText(weatherItem.getPressure());
holder.textViewHumidity.setText(weatherItem.getHumidity());
holder.textViewSpeedWind.setText(weatherItem.getSpeedWind());
holder.textViewGustWind.setText(weatherItem.getGustWind());
holder.textViewDirectionWind.setText(weatherItem.getDirectionWind());
}
#Override
public int getItemCount() {
return weatherItems.size();
}
static class WeatherViewHolder extends RecyclerView.ViewHolder {
private TextView textViewDate;
private TextView textViewTime;
private TextView textView;
private TextView textViewDegree;
private TextView textViewPressure;
private TextView textViewHumidity;
private TextView textViewSpeedWind;
private TextView textViewGustWind;
private TextView textViewDirectionWind;
public WeatherViewHolder(#NonNull View itemView) {
super(itemView);
textViewDate = itemView.findViewById(R.id.textViewDate);
textViewTime = itemView.findViewById(R.id.textViewTime);
textView = itemView.findViewById(R.id.textViewFallout);
textViewDegree = itemView.findViewById(R.id.textViewDegree);
textViewPressure = itemView.findViewById(R.id.textViewPressure);
textViewHumidity = itemView.findViewById(R.id.textViewHumidity);
textViewSpeedWind = itemView.findViewById(R.id.textViewSpeedWind);
textViewGustWind = itemView.findViewById(R.id.textViewGustWind);
textViewDirectionWind = itemView.findViewById(R.id.textViewDirectionWind);
}
}
}
And finaly my code in MainActivity:
public class MainActivity extends AppCompatActivity {
EditText editTextRequestCity;
private RecyclerView recyclerViewListForecast;
WeatherAdapter adapter;
private ArrayList<WeatherItem> weatherItems = new ArrayList<>();
private final String WEATHER_URL = "https://api.openweathermap.org/data/2.5/forecast?q=%s&lang=ru&units=metric&appid=ce288368c68807e060c17369bfbef3b3";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextRequestCity = findViewById(R.id.editTextRequestCity);
recyclerViewListForecast = findViewById(R.id.recyclerViewListForecast);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
recyclerViewListForecast.setLayoutManager(linearLayoutManager);
adapter = new WeatherAdapter(getApplicationContext(), weatherItems = new ArrayList<>());
recyclerViewListForecast.setAdapter(adapter);
}
public void onClickShowWeather(View view) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
weatherItems.clear();
adapter.notifyDataSetChanged();
String city = editTextRequestCity.getText().toString().trim();
String request = String.format(WEATHER_URL,city);
DownLoadWeatherTask task = new DownLoadWeatherTask();
task.execute(request);
}
private class DownLoadWeatherTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... strings) {
URL url = null;
HttpURLConnection urlConnection = null;
StringBuilder result = new StringBuilder();
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
result.append(line);
line = reader.readLine();
}
return result.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s != null) {
try {
JSONObject jsonObjectMain = new JSONObject(s);
JSONArray jsonArray = jsonObjectMain.getJSONArray("list");
for (int i = 0; i < jsonArray.length(); i++) {
ArrayList<WeatherItem> weatherItemDay = new ArrayList<>();
JSONObject jsonObjectDay = jsonArray.getJSONObject(i);
String dateTime = jsonObjectDay.getString("dt_txt");
String date = dateTime.substring(0, 10).trim();
String time = dateTime.substring(11, 16).trim();
String fallout = jsonObjectDay.getJSONArray("weather").getJSONObject(0).getString("description").trim();
String degree = String.format("" + jsonObjectDay.getJSONObject("main").getInt("temp")).trim();
String pressure = String.format("" + jsonObjectDay.getJSONObject("main").getInt("pressure")).trim();
String humidity = String.format("" + jsonObjectDay.getJSONObject("main").getInt("humidity")).trim();
String speedWind = String.format("" + jsonObjectDay.getJSONObject("wind").getInt("speed")).trim();
String gustWind = String.format("" + jsonObjectDay.getJSONObject("wind").getInt("gust")).trim();
String directionWind = String.format("" + jsonObjectDay.getJSONObject("wind").getInt("deg")).trim();
weatherItems.add(new WeatherItem(date, time, fallout, degree, pressure, humidity, speedWind, gustWind, directionWind));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
Call notifyDataSetChanged() when you add a new item to your list. Based on your code, this needs to happen in onPostExecute for you.
You are already calling notifyDataSetChanged() in the onClick but this is before the task has finished, therefore the item doesn't show because it hasn't been added to the list yet.
I am using a loop to read all the spinner elements (inside a cardview) in the listview.
But the loop gives one item less i.e. the last item.
I have included all the source code.
What may be the problem?
Is there any other way to read all the items in listview?
Main Layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/ll_gpa"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<ListView
android:id="#+id/listSubs"
android:scrollbars="none"
android:layout_height="0dip"
android:layout_width="match_parent"
android:layout_weight="1"
/>
<Button
android:text="Calculate GPA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnGpa"
android:textAlignment="center"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</RelativeLayout>
Single Item Layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/cv_subject"
android:layout_marginBottom="2dp"
android:layout_marginTop="2dp"
>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="15dp"
android:id="#+id/rl_subject"
>
<TextView
android:id="#+id/subTitle"
android:textSize="16sp"
android:text="Subject"
android:layout_toStartOf="#+id/subGrade"
android:layout_toLeftOf="#+id/subGrade"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ellipsize="none"
/>
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:spinnerMode="dropdown"
android:dropDownWidth="40dp"
android:textAlignment="center"
android:entries="#array/grades"
android:id="#+id/subGrade"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
/>
</RelativeLayout>
</android.support.v7.widget.CardView>
MainActivity
public class MainActivity extends AppCompatActivity {
private static SubjectArrayAdapter adapter;
private ProgressDialog progress;
JsonArray subs = new JsonArray();
JsonArray dataGrades = new JsonArray();
ListView listView;
ArrayList<SubjectClass> subjects = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
res = new GetSubNames().execute();
subs = res.getAsJsonArray("subjects");
for (int i = 0; i < subs.size(); i++){
JsonObject temp = subs.get(i).getAsJsonObject();
subjects.add(new SubjectClass(temp.get("subCode").getAsString(), temp.get("subTitle").getAsString()));
}
adapter = new SubjectArrayAdapter(subjects,GpaActivity.this);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
Button btnGpa = (Button) findViewById(R.id.btnGpa);
btnGpa.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new CalcGPA().execute();
JsonArray temparr = new JsonArray();
for (int i = 0; i < listView.getChildCount(); i++) {
// Get row's spinner
View listItem = listView.getChildAt(i);
JsonObject temp = new JsonObject();
Spinner spinner = (Spinner) listItem.findViewById(R.id.subGrade);
temp.addProperty("subject",subjects.get(i).getCode());
temp.addProperty("grade", spinner.getSelectedItem().toString());
temparr.add(temp);
}
dataGrades = temparr;
}
});
}
}
Custom Class
class SubjectClass{
String title;
String code;
SubjectClass(String code, String title) {
this.code = code;
this.title = title;
}
String getTitle(){
return this.title;
}
String getCode(){
return this.code;
}
void setCode(String code){
this.code = code;
}
void setTitle(String title){
this.title = title;
}
}
Custom ArrayAdapter
public class SubjectArrayAdapter extends ArrayAdapter<SubjectClass>{
private ArrayList<SubjectClass> dataSet;
Context mContext;
// View lookup cache
private static class ViewHolder {
TextView txtName;
}
public SubjectArrayAdapter(ArrayList<SubjectClass> data, Context context) {
super(context, R.layout.item_subject, data);
this.dataSet = data;
this.mContext=context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
SubjectClass dataModel = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
final View result;
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.item_subject, parent, false);
viewHolder.txtName = (TextView) convertView.findViewById(R.id.subTitle);
result = convertView;
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
result = convertView;
}
viewHolder.txtName.setText(dataModel.getCode() + " " + dataModel.getTitle());
// Return the completed view to render on screen
return convertView;
}
}
for (int i = 0; i < listView.getCount(); i++) {
// Get row's spinner
View listItem = listView.getItemAtPosition(i);
JsonObject temp = new JsonObject();
Spinner spinner = (Spinner) listItem.findViewById(R.id.subGrade);
temp.addProperty("subject",subjects.get(i).getCode());
temp.addProperty("grade", spinner.getSelectedItem().toString());
temparr.add(temp);
}
Check for above code in main activity. Use .getCount() instead .getChildCount()
and use .getItemAtIndex() instead .getChildAt().
I hope this solves the issue.
I am trying to make an activity that provides a list of emergency phone numbers with the ability for the user to add their own custom entries and save them. For some reason, the ListView doesn't appear on the activity. I'm pretty sure I'm doing something wrong in the CustomAdapter class that I made to hold two text boxes in each segment of the ListView.
I'm also trying to set the listView to start a phone activity with the phone number of whatever segment was touched, and I'm unsure if I'm doing this correctly.
PhoneList.java :
public class PhoneList extends AppCompatActivity {
ArrayList<String> customList;
ArrayList<String> numList;
Bundle b;
TinyDB tinydb;
CustomAdapter dataAdapter;
ListView phoneListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_list);
phoneListView = (ListView)findViewById(R.id.listViewPhone);
Integer num = null;
String label = "";
customList = null;
numList = null;
tinydb = new TinyDB(this);
Button saveContact = (Button)(findViewById(R.id.button4));
b = new Bundle();
customList = tinydb.getListString("label");
ArrayList<Integer> temp = tinydb.getListInt("num");
for(int i = 0; i < temp.size(); i++){
numList.add(temp.get(i).toString());
}
saveContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText enteredLabel = (EditText)findViewById(R.id.editText2);
EditText enteredNum = (EditText)findViewById(R.id.editText);
String label = enteredLabel.getText().toString();
Integer num = Integer.parseInt(enteredNum.getText().toString());
b.putString("label",label);
b.putInt("num",num);
addPhoneItem();
}
});
ArrayList<String> phoneList = new ArrayList<>();
phoneList.add("Emergencies");
phoneList.add("Travel Info ");
phoneList.add("Poison Control ");
phoneList.add("AAA: 1(800)836-2582");
if(customList != null && customList.size() > 0) phoneList.addAll(customList);
ArrayList<String> numberList = new ArrayList<>();
numberList.add("911");
numberList.add("511");
numberList.add("18002221222");
numberList.add("18008362582");
if(numList != null && numList.size()>0) {
for (int i = 0; i < numList.size(); i++) {
numberList.add(numList.get(i).toString());
}
}
dataAdapter = new CustomAdapter(this,numberList,phoneList);
phoneListView.setAdapter(dataAdapter);
}
public void addPhoneItem(){
customList.add(b.getString("label"));
numList.add(b.getString("num"));
tinydb.putListString("label",customList);
tinydb.putListString("num",numList);
dataAdapter = new CustomAdapter(this,numList,customList);
phoneListView.setAdapter(dataAdapter);
}
private class CustomAdapter extends ArrayAdapter<String> {
ArrayList<String> labels;
ArrayList<String> nums;
Context context;
public CustomAdapter(Context context, ArrayList<String> n,ArrayList<String> l) {
super(context,R.layout.phone_item);
this.context = context;
labels = new ArrayList<String>();
labels.addAll(l);
nums = new ArrayList<String>();
nums.addAll(n);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
try {
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.phone_item, null);
holder = new ViewHolder();
holder.viewLabel = (TextView) convertView.findViewById(R.id.editText);
holder.viewNumber = (TextView) convertView.findViewById(R.id.editText2);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
String label = labels.get(position);
String num = nums.get(position);
holder.viewLabel.setText(label);
holder.viewNumber.setText(num);
holder.viewNumber.setTag(num);
holder.viewNumber.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String str = "tel:" + (EditText) v.getTag();
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(str));
try {
startActivity(intent);
} catch (Exception e) {
Toast.makeText(getContext(),"Exception Caught in CustomAdapter",Toast.LENGTH_SHORT).show();
}
}
});
}
catch(Exception e){
Toast.makeText(getContext(),"Exception caught",Toast.LENGTH_SHORT).show();
}
return convertView;
}
}
private class ViewHolder{
TextView viewLabel;
TextView viewNumber;
}
}
activity_phone_list.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res``/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.rvtripapp.dempsey.rvtripapp.PhoneList">
<ListView
android:layout_width="wrap_content"
android:layout_height="400dp"
android:id="#+id/listViewPhone"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<EditText
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:editable="true"
android:hint="Label" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/editText2"
android:layout_below="#+id/editText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="Phone Number" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+"
android:id="#+id/button4"
android:textSize="40dp"
android:background="#44fe66"
android:layout_alignBottom="#+id/editText2"
android:layout_alignRight="#+id/listView"
android:layout_alignEnd="#+id/listView" />
</RelativeLayout>
phone_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView3" />
</LinearLayout>
Any help is much appreciated, thank you.
Change the super keyword line to
super(context,R.layout.phone_item, n);
Have you tried to override the getCount method of the CustomAdapter class ?
#Override
public int getCount() {
return labels.size();
}
You are setting your custom adapter outside onCreate() try to set it inside the onCreate().
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I created a list view with one line of text for each textView in the list, and was wondering how i can create two lines of text for each item in the list view.
Im using an ArrayAdapter but i couldn't find any helpful documents on the android dev. site on how to create two lines. Additionally, I haven't seen any info. on how to be flexible with the list view- e.g. how do i make editText's inside the listView, or how do i change background color of list items. Can someone please help me bc ive been looking all over but to no avail. Thanks!!
here is a general answer ..that allows you to create your own list view items..
first of all you have to create your listview item for exemple my item is:
medecinListItem.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#dddddd"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:background="#drawable/bg_parent_rounded_corner"
android:orientation="vertical"
android:paddingBottom="20dp"
android:paddingTop="20dp" >
<RelativeLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView3"
android:maxWidth="40dp"
android:maxHeight="40dp"
android:minHeight="40dp"
android:minWidth="40dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="15dp" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingLeft="10dp"
android:layout_weight="4.08"
android:layout_toLeftOf="#+id/imageView"
android:layout_toStartOf="#+id/imageView"
android:layout_toRightOf="#+id/imageView3"
android:layout_toEndOf="#+id/imageView3">
<TextView
android:id="#+id/NomMed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15dp"
android:textStyle="bold" />
<TextView
android:id="#+id/SpeMed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#a0a3a7"
android:textSize="13dp" />
</LinearLayout>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:scaleType="fitXY"
android:src="#drawable/ic_action_navigation_more_vert"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
<TextView
android:id="#+id/NumMed"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:textColor="#0a80d1"
android:gravity="right" />
<TextView
android:id="#+id/AdreMed"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="5dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:gravity="right" />
</LinearLayout>
</LinearLayout>
screenshot of the listitem :
and use custom list adapter that allow you to inflate your items in the listview :
(here is my listAdapter)
public class MedecinListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<MedecinItem> MedecinItems;
public MedecinListAdapter(Activity activity, List<MedecinItem> MedecinItems) {
this.activity = activity;
this.MedecinItems = MedecinItems;
}
#Override
public int getCount() {
return MedecinItems.size();
}
#Override
public Object getItem(int location) {
return MedecinItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.medecin_list_item, null);
TextView nom = (TextView) convertView.findViewById(R.id.NomMed);
TextView specialite = (TextView) convertView
.findViewById(R.id.SpeMed);
TextView adresse = (TextView) convertView
.findViewById(R.id.AdreMed);
TextView numero = (TextView) convertView.findViewById(R.id.NumMed);
ImageView imageMed = (ImageView) convertView.findViewById(R.id.imageView3);
ImageView image = (ImageView) convertView.findViewById(R.id.imageView);
final MedecinItem item = MedecinItems.get(position);
nom.setText(item.getNom());
numero.setText(getString(R.string.numero)+":"+item.getNumero());
adresse.setText(getString(R.string.adresse)+":"+item.getAdresse());
if(Locale.getDefault().getLanguage().equals("ar"))
specialite.setText(avoirSpeEnArabe(item.getSpecialite()));
else
specialite.setText(item.getSpecialite());
String spe=avoirSpeEnFrancais(item.getSpecialite());
System.out.println("spe '"+spe+"'");
int id = getResources().getIdentifier(avoirSpe2(spe).toLowerCase(), "drawable", getPackageName());
imageMed.setImageResource(id);
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popup = new PopupMenu(MainActivity.context, v);
popup.getMenuInflater().inflate(R.menu.medecin_list_menu,
popup.getMenu());
popup.show();
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item2) {
line2=item.getNumero();
Emailm=avoirEmail(line2);
switch (item2.getItemId()) {
case R.id.Appeler:
Call(item.getNumero());
break;
case R.id.EnvoyerMsg:
msg(Emailm);
break;
case R.id.AfficherDet:
menuItem = "3";
Vider();
telecharger();
break;
case R.id.Afficher:
String Lat;
String Lon;
Cursor medecin = MainActivity.db.lireMedecin();
while (medecin.getPosition() < medecin.getCount()) {
if (medecin.getString(4).equals(line2)) {
Lat = medecin.getString(5);
Lon = medecin.getString(6);
Mapfrag2.map.addMarker(new MarkerOptions().position(new LatLng(Double.parseDouble(Lat), Double.parseDouble(Lon)))
.title(item.getNom())
.snippet(line2).icon(BitmapDescriptorFactory
.fromResource(Icone(medecin.getString(7).charAt(0)))));
MainActivity.vp.setCurrentItem(1, true);
CameraUpdate zoom = CameraUpdateFactory.zoomTo(15);
CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(Double.parseDouble(Lat), Double.parseDouble(Lon)));
Mapfrag2.map.moveCamera(center);
Mapfrag2.map.animateCamera(zoom);
}
medecin.moveToNext();
}
break;
case R.id.AvoirRdv:
telecharger();
menuItem = "2";
break;
default:
break;
}
return true;
}
});
}
});
if (!MedecinItems.get(position).anime){
Animation animation = AnimationUtils.loadAnimation(MainActivity.context, R.anim.fade_in);
convertView.startAnimation(animation);
MedecinItems.get(position).anime=true;}
return convertView;
}
}
and this is the MedecinItem:
public class MedecinItem {
private String id,nom, numero, adresse, specialite;
public boolean anime=false;
public MedecinItem(String id, String nom, String numero, String adresse,
String specialite) {
super();
this.id = id;
this.nom = nom;
this.numero = numero;
this.specialite = specialite;
this.adresse = adresse;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getSpecialite() {
return specialite;
}
public void setSpecialite(String specialite) {
this.specialite = specialite;
}
public String getNumero() {
return numero;
}
public void setNumero(String numero) {
this.numero = numero;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
}
use it like this:
List<MedecinItem> medecinItems=new ArrayList<MedecinItem>();
//here you add items to your list
MedecinListAdapter mla=new MedecinListAdapter(MainActivity.this,medecinItems);
((ListView) findViewById(R.id.listView)).setAdapter(mla);
and here is the simplest way to create the listView items with two lines..
first declare your list to store two lines items
List<Map<String, String>> list= new ArrayList<Map<String, String>>();
after that create two lines item and add it to that list like this :
Map<String, String> item= new HashMap<String, String>(2);
item.put("Line1", "Name : Charaf");
item.put("Line1","Phone number: 1234567");
list.add(item);
now show the previous items in the listview :
SimpleAdapter adapter = new SimpleAdapter(this, list,
android.R.layout.simple_list_item_2,
new String[] {"Line1", "Line2" },
new int[] {android.R.id.text1, android.R.id.text2 });
listView.setAdapter(Adapter);
to read data from listView ... for example when clickin on item.. add this:
Map<String, String> item= new HashMap<String, String>(2);
item=listview.getAdapter().getItem(position);
String name=item.get("Line1");
You will definitely need to subclass ArrayAdapter and override getView().
ArrayAdapter only knows how to handle one TextView per row . That is what i know as how i understood your question..
I have run into some strange issues with my listview. I created a list using listview, along with a custom adapter to display rows with a text field and multiple images. I beleive that I have that part working well. I also put two buttons at the bottom of the listview so that I can select rows and modify them using the two buttons. I implemented highlighting by simply changing the background color and then setting a boolean flag that is part of each row so I can know what rows are highlighted. Now I am experiencing two issues. The first is that if I select a row and then scroll so that row is outside of the screen, then the row becomes un-highlighted, which is bad. I only want a row to become un-highlighted if the user clicks on it again or if a command is issued. The second problem is that once the adapter is updated or a row moves out of view, if you try to click on a row it will immediately un-highlight itself; this only happens once. After that happens then you can click on the row and it will stay highlighted. I would very much appreciate some help with this.
Regards.
HelmetList.java
public class HelmetList
{
public HelmetList (String name, String address, String img_hel, String img_rec, String img_bat,
String img_dsk, String img_str, Boolean selected)
{
super();
this.name = name;
this.address = address;
this.img_hel = img_hel;
this.img_rec = img_rec;
this.img_bat = img_bat;
this.img_dsk = img_dsk;
this.img_str = img_str;
this.selected = selected;
}
private String name;
private String address;
private String img_hel;
private String img_rec;
private String img_bat;
private String img_dsk;
private String img_str;
private Boolean selected;
public String getName ()
{
return name;
}
public void setName (String s_name)
{
this.name = s_name;
}
public String getAddress ()
{
return address;
}
public void setAddress (String s_address)
{
this.address = s_address;
}
public String getImgHel ()
{
return img_hel;
}
public void setImgHel (String s_img_hel)
{
this.img_hel = s_img_hel;
}
public String getImgRec ()
{
return img_rec;
}
public void setImgRec (String s_img_rec)
{
this.img_rec = s_img_rec;
}
public String getImgBat ()
{
return img_bat;
}
public void setImgBat (String s_img_bat)
{
this.img_bat = s_img_bat;
}
public String getImgDsk ()
{
return img_dsk;
}
public void setImgDsk (String s_img_dsk)
{
this.img_dsk = s_img_dsk;
}
public String getImgStr ()
{
return img_str;
}
public void setImgStr (String s_img_str)
{
this.img_str = s_img_str;
}
public Boolean getSelected ()
{
return selected;
}
public void setSelected (Boolean s_selected)
{
this.selected = s_selected;
}
}
HelmetListAdapter.java
public class HelmetListAdapter extends ArrayAdapter<HelmetList>
{
private int resource;
private LayoutInflater inflater;
private Context context;
public HelmetListAdapter (Context p_context, int p_resource, List<HelmetList> p_objects)
{
super (p_context, p_resource, p_objects);
resource = p_resource;
inflater = LayoutInflater.from (p_context);
context = p_context;
}
#Override
public View getView (int position, View convertView, ViewGroup parent)
{
convertView = ( RelativeLayout ) inflater.inflate( resource, null );
HelmetList Helmet = getItem (position);
TextView hname = (TextView) convertView.findViewById(R.id.h_name);
hname.setText(Helmet.getName ());
TextView haddress = (TextView) convertView.findViewById(R.id.h_address);
haddress.setText(Helmet.getAddress ());
ImageView himage = (ImageView) convertView.findViewById(R.id.h_image);
String uri = "drawable/" + Helmet.getImgHel();
int imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());
Drawable image = context.getResources().getDrawable(imageResource);
himage.setImageDrawable(image);
ImageView hrec = (ImageView) convertView.findViewById(R.id.h_rec);
uri = "drawable/" + Helmet.getImgRec();
imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());
image = context.getResources().getDrawable(imageResource);
hrec.setImageDrawable(image);
ImageView hlbat = (ImageView) convertView.findViewById(R.id.h_lb);
uri = "drawable/" + Helmet.getImgBat();
imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());
image = context.getResources().getDrawable(imageResource);
hlbat.setImageDrawable(image);
ImageView hldsk = (ImageView) convertView.findViewById(R.id.h_ld);
uri = "drawable/" + Helmet.getImgDsk();
imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());
image = context.getResources().getDrawable(imageResource);
hldsk.setImageDrawable(image);
ImageView hstr = (ImageView) convertView.findViewById(R.id.h_str);
uri = "drawable/" + Helmet.getImgStr();
imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());
image = context.getResources().getDrawable(imageResource);
hstr.setImageDrawable(image);
return convertView;
}
}
MainActivity.java
public class MainActivity extends Activity
{
private ListView lvhelmets;
private HelmetListAdapter adhelmets;
private Context ctx;
List<Integer> selected;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ctx = this;
List<HelmetList> helmetlist = new ArrayList<HelmetList>();
helmetlist.add(new HelmetList("Bell", "11111", "helmetpic0", "rec",
"bat", "mm", "str", Boolean.FALSE));
helmetlist.add(new HelmetList("Shoei", "33333", "helmetpic1", "rec",
"bat", "mm", "str", Boolean.FALSE));
helmetlist.add(new HelmetList("Harley Davidson", "55555", "helmetpic2", "rec",
"bat", "mm", "str", Boolean.FALSE));
helmetlist.add(new HelmetList("Joe Rocket", "77777", "helmetpic3", "rec",
"bat", "mm", "str", Boolean.FALSE));
lvhelmets = (ListView) findViewById(R.id.Helmet_list);
lvhelmets.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
adhelmets = new HelmetListAdapter(ctx, R.layout.row_format, helmetlist);
lvhelmets.setAdapter (adhelmets);
Button price = (Button) findViewById(R.id.bPrice);
Button safety = (Button) findViewById(R.id.bSafety);
price.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
lvhelmets.setAdapter(adhelmets);
int count = lvhelmets.getCount();
for (int i = 0; i < count; i++)
{
HelmetList helmet = (HelmetList) lvhelmets.getItemAtPosition(i);
helmet.setSelected(Boolean.FALSE);
}
adhelmets.notifyDataSetChanged();
}
});
safety.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
lvhelmets.setAdapter(adhelmets);
int count = lvhelmets.getCount();
for (int i = 0; i < count; i++)
{
HelmetList helmet = (HelmetList) lvhelmets.getItemAtPosition(i);
helmet.setSelected(Boolean.FALSE);
}
adhelmets.notifyDataSetChanged();
}
});
lvhelmets.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
HelmetList helmet = (HelmetList) parent.getItemAtPosition(position);
if (!helmet.getSelected())
{
view.setBackgroundColor(Color.LTGRAY);
helmet.setSelected(Boolean.TRUE);
}
else
{
view.setBackgroundColor(Color.TRANSPARENT);
helmet.setSelected(Boolean.FALSE);
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/Helmet_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingTop="5dp"
android:choiceMode="multipleChoice"
android:layout_weight="1">
</ListView>
<LinearLayout
android:id="#+id/btnHolderLL"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/bPrice"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingRight="1dp"
android:paddingLeft="1dp"
android:textColor="#FFFFFF"
android:background="#222222"
android:text="Price"
android:clickable="true" />
<Button
android:id="#+id/bSafety"
android:layout_width="1dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingRight="1dp"
android:paddingLeft="1dp"
android:textColor="#FFFFFF"
android:background="#222222"
android:text="Safety"
android:clickable="true" />
</LinearLayout>
</LinearLayout>
row_format.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dip" >
<!-- ListRow Left side Thumbnail image -->
<LinearLayout android:id="#+id/thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="3dip"
android:layout_alignParentLeft="true"
android:layout_marginRight="5dip">
<ImageView
android:id="#+id/h_image"
android:layout_width="50dip"
android:layout_height="50dip"
android:layout_marginLeft="5dip"/>
</LinearLayout>
<TextView
android:id="#+id/h_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/thumbnail"
android:layout_toRightOf="#+id/thumbnail"
android:textColor="#040404"
android:typeface="sans"
android:textSize="20dip"
android:layout_marginTop="5dip"
android:textStyle="bold"/>
<TextView
android:id="#+id/h_address"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/h_name"
android:textColor="#343434"
android:textSize="12dip"
android:layout_marginTop="1dip"
android:layout_toRightOf="#+id/thumbnail" />
<ImageView
android:id="#+id/h_rec"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_alignParentRight="true"
android:layout_marginRight="5dp"
android:layout_centerVertical="true" />
<ImageView
android:id="#+id/h_lb"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_alignParentRight="true"
android:layout_marginRight="45dp"
android:layout_centerVertical="true" />
<ImageView
android:id="#+id/h_ld"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_alignParentRight="true"
android:layout_marginRight="85dp"
android:layout_centerVertical="true" />
<ImageView
android:id="#+id/h_str"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_alignParentRight="true"
android:layout_marginRight="125dp"
android:layout_centerVertical="true" />
</RelativeLayout>
This happens because of the view recycling.
In the method getView() of your adapter, add the following piece of code :
if (!helmet.getSelected()) {
convertView.setBackgroundColor(Color.LTGRAY);
} else {
convertView.setBackgroundColor(Color.TRANSPARENT);
}
You might want to rewrite your view recycling by the way; the one you implemented is not effective at all.
A first step would be to add this :
#Override
public View getView (int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(resource, parent, false);
}
// continue the rest of the cell data filling
}