Drawable not displaying in ImageView - java

Hello I am running into a silly error and I think I might be missing something. I currently have a list of objects. The objects have a title, description and an image. The title and description display properly, but for some reason the Image won't. I added the objects on another activity and made a list, when the user selects the item they wanted to see it send the id to this new page where it pulls the object. I added a random image as jpg to the application to see if it pulse and it does, but it looks a little weird. Any ideas why the images won't be pulling from the list? Thank you in advance.
XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/img"
android:src="#drawable/img"
android:layout_alignParentTop="true"
android:layout_alignParentStart="false"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="News Title"
android:id="#+id/title"
android:layout_below="#+id/img"
android:layout_alignParentLeft="false"
android:layout_alignParentRight="false"
android:layout_centerInParent="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/desc"
android:layout_below="#+id/title"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" />
</RelativeLayout>
JAVA:
CustomOBJ selOBJ = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.det);
Bundle objID = getIntent().getExtras();
for(int x = 0; x < MainActivity.listobjs.size(); x++){
if (MainActivity.listobjs.get(x).getID().equals(objID.getString("object") )){
selOBJ = MainActivity.listobjs.get(x);
break;
}
}
TextView Title =(TextView)findViewById(R.id.title);
TextView description = (TextView)findViewById(R.id.desc);
ImageView objPic=(ImageView)findViewById(R.id.img);
Title.setText(selOBJ.getName());
description.setText(selOBJ.getDescription());
objPic.setImageDrawable(selOBJ.getObjPic());
}
CustomOBJ Class:
public class CustomOBJ {
private String objID;
private String name;
private String Description;
private Drawable objPic;
public CustomOBJ(String i, String n, String d, Drawable pic) {
objID = i;
name = n;
Description = d;
objPic = pic;
}
public String getID() { return objID; }
public String getName() {return name;}
public String getDescription() {return description;}
public Drawable getObjPic() {return objPic; }
}
MainActivity:
public void jsonTolist(){
//parse json data
try{
jArray = new JSONArray(welcome.result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag", "title:" + json_data.getString("title")
);
if(listobjs.isEmpty() || isNewsName(listobjs,json_data) == false){
Drawable drawable = LoadImageFromWebOperations(json_data.getString("img"));
selOBJ = new CustomOBJ(json_data.getString("id"), json_data.getString("title"), json_data.getString("desc"), drawable);
listobjs.add(selOBJ);
}
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
Load Images:
private Drawable LoadImageFromWebOperations(String url){
try{
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
}catch (Exception e) {
System.out.println("Exc="+e);
return null;
}
}

Sender Side:
Bundle d1 = new Bundle();
d1.putInt("d",0);
Receiver Side:
Bundle objID = getIntent().getExtras();
int x = objID .getInt("d");
if (MainActivity.listobjs.get(x).getID()
.equals(objID.getString("object") ))
{
selOBJ = MainActivity.listobjs.get(x);
}
Before doing this kindly check CustomOBJ class have a valid constructor or not.
ref this link also
How to get image from url website in imageview in android

Related

RecyclerView doesn't Update and shows on screen until Soft Keyboard is Open/Close

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.

How do I use jsoup to scrape images on android studio

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.

how to show default list in spinner in android

Recently I developed one app. In this, The values are retrieved from the MySQL data base into the spinner. The problem is that it crashes when internet is not present. My intention is, if the internet is not present show default values. Otherwise if the internet is available show the values from MySQL database.
public class MilkProduction extends AppCompatActivity implements Spinner.OnItemSelectedListener{
private EditText quantity;
private Button submit, cancel;
private TextView date_time;
Calendar calander;
SimpleDateFormat simpleDateFormat;
String time;
private AutoCompleteTextView animal_id;
private List<Animal> fruits ;
Boolean isInternetPresent = false;
private ConnectionDetector cd;
private Spinner spinner1;
private String shift_id;
private String product;
String shiftid="",intime="",outtime="";
//JSON Array
private JSONArray result;
//An ArrayList for Spinner Items
private ArrayList<String> students;
private Animal item ;
private Animal animal=new Animal();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
setContentView(R.layout.milk_production);
animal_id = (AutoCompleteTextView) findViewById(R.id.edt_animal_id);
quantity = (EditText) findViewById(R.id.edt_milkproduction_quan);
date_time = (TextView) findViewById(R.id.txt_timt_date_year);
submit = (Button) findViewById(R.id.btn_prodc_submit);
calander = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss a");
time = simpleDateFormat.format(calander.getTime());
date_time.setText(time);
date_time.setTextSize(15);
students = new ArrayList<String>();
spinner1 = (Spinner) findViewById(R.id.spinner);
spinner1.setOnItemSelectedListener(this);
cd = new ConnectionDetector(getApplicationContext());
//Calling the method that will fetch data
proautocomplete();
prodropdown();
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isInternetPresent = cd.isConnectingToInternet();
// check for Internet status
if (isInternetPresent) {
insertUser();
}
else{
showAlertDialog(MilkProduction.this, "Internet not available",
"Internet is not available in this device", false);
}
}
});
}
private void prodropdown() {
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(Config.ROOT_URL) //Setting the Root URL
.build(); //Finally building the adapter
//Creating object for our interface
AnimalAPI api = adapter.create(AnimalAPI.class);
api.insertUser1( new Callback<Response>() {
#Override
public void success(Response response, Response response2) {
String detailsString = Others.getStringFromRetrofitResponse(response);
try {
//Parsing the fetched Json String to JSON Object
JSONObject j = new JSONObject(detailsString);
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray(Config.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getStudents(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void failure(RetrofitError error) {
}
});
}
private void getStudents(JSONArray j) {
//Traversing through all the items in the json array
for(int i=0;i<j.length();i++){
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the student to array list
students.add(json.getString(Config.TAG_USERNAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner1.setAdapter(new ArrayAdapter<String>(MilkProduction.this, android.R.layout.simple_spinner_dropdown_item, students));
}
//Method to get student name of a particular position
private String getShiftid(int position){
String name="";
try {
//Getting object of given index
JSONObject json = result.getJSONObject(position);
//Fetching name from that object
// name = json.getString(Config.TAG_NAME);
name = animal.setShiftid(json.getString(Config.TAG_NAME));
} catch (JSONException e) {
e.printStackTrace();
}
//Returning the name
return name;
}
//Doing the same with this method as we did with getName()
private String getIntime(int position){
String course="";
try {
JSONObject json = result.getJSONObject(position);
// course = json.getString(Config.TAG_COURSE);
course= animal.setIntime(json.getString(Config.TAG_COURSE));
} catch (JSONException e) {
e.printStackTrace();
}
return course;
}
//Doing the same with this method as we did with getName()
private String getOuttime(int position){
String session="";
try {
JSONObject json = result.getJSONObject(position);
// session = json.getString(Config.TAG_SESSION);
session= animal.setOuttime(json.getString(Config.TAG_SESSION));
} catch (JSONException e) {
e.printStackTrace();
}
return session;
}
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
String spin = parent.getItemAtPosition(position).toString();
//Setting the values to textviews for a selected item
shiftid=(getShiftid(position));
intime=(getIntime(position));
outtime=(getOuttime(position));
}
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
shiftid="";
intime="";
outtime="";
}
private void insertUser() {
//While the app fetched data we are displaying a progress dialog
final ProgressDialog loading = ProgressDialog.show(this,"Loading","Please wait...",false,false);
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(Config.ROOT_URL) //Setting the Root URL
.build(); //Finally building the adapter
//Creating object for our interface
AnimalAPI api = adapter.create(AnimalAPI.class);
api.insertUser(
animal_id.getText().toString(),
quantity.getText().toString(),
date_time.getText().toString(),
spinner1.getSelectedItem().toString(),
" ",
shiftid,
intime,
outtime,
new Callback<Response>() {
#Override
public void success(Response result, Response response) {
//On success we will read the server's output using bufferedreader
loading.dismiss();
//Creating a bufferedreader object
BufferedReader reader = null;
//An string to store output from the server
String output = "";
try {
reader = new BufferedReader(new InputStreamReader(result.getBody().in()));
//Reading the output in the string
output = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
//Displaying the output as a toast
Toast.makeText(MilkProduction.this, output, Toast.LENGTH_LONG).show();
}
#Override
public void failure(RetrofitError error) {
//If any error occured displaying the error as toast
loading.dismiss();
Toast.makeText(MilkProduction.this, error.toString(), Toast.LENGTH_LONG).show();
}
}
);
}
}
Layout:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scrollView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/mm"
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="#dimen/dairy_layout_height"
android:orientation="vertical"
android:layout_gravity="center_horizontal"
android:gravity="center_vertical|center_horizontal"
android:layout_marginTop="25dp"
android:layout_marginRight="5dp"
android:layout_marginLeft="5dp"
android:background="#drawable/corner3"
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_margin="13dp"
android:layout_gravity="center"
>
<TextView
android:id="#+id/heder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Milk Production"
android:layout_gravity="center"
android:gravity="center"
android:layout_margin="5dp"
android:textSize="25sp"
android:textColor="#color/textcolour"
/>
<View
android:layout_width="250dp"
android:layout_height="2dip"
android:background="#023e64"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_margin="13dp"
android:layout_gravity="left"
android:layout_weight="1"
>
<TextView
android:id="#+id/txt_animal_shfit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Shift : "
android:textSize="20sp"
android:textColor="#color/textcolour"
android:layout_weight="0.40"
android:gravity="left"
android:layout_marginTop="12dp"
/>
<Spinner
android:layout_width="160dp"
android:layout_height="50dp"
android:id="#+id/spinner"
android:layout_gravity="center_horizontal"
android:spinnerMode="dialog"
android:prompt="#string/shift_prompt"
android:background="#android:drawable/btn_dropdown"
android:entries="#array/android_dropdown_arrays1"
style="#android:style/Widget.Holo.Light.Spinner"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_margin="13dp"
android:layout_gravity="left"
android:layout_weight="1"
>
<TextView
android:id="#+id/txt_animal_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Animal : "
android:textSize="20sp"
android:textColor="#color/textcolour"
android:layout_weight="0.40"
android:gravity="left"
/>
<AutoCompleteTextView
android:id="#+id/edt_animal_id"
android:layout_width="160dp"
android:layout_height="50dp"
android:background="#drawable/corner1"
android:layout_weight="0.60"
android:layout_alignParentLeft="true"
android:ems="10"
android:text="">
</AutoCompleteTextView>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_margin="13dp"
android:layout_gravity="left"
android:layout_weight="1"
>
<TextView
android:id="#+id/txt_milk"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Quantity : "
android:textSize="20sp"
android:textColor="#color/textcolour"
android:layout_weight="0.40"
android:gravity="left"
/>
<EditText
android:id="#+id/edt_milkproduction_quan"
android:layout_width="121dp"
android:layout_height="50dp"
android:background="#drawable/corner1"
android:layout_weight="0.60"
android:inputType="number"
android:ems="10"
/>
<TextView
android:id="#+id/txt_milk_quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Lts."
android:textSize="20sp"
android:textColor="#color/textcolour"
android:layout_weight="0.40"
android:gravity="right"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_margin="13dp"
android:layout_gravity="left"
>
<TextView
android:id="#+id/btn_prodc_submit"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Submit"
android:textSize="#dimen/button_sub_txt_size"
android:layout_margin="#dimen/button_layout_margin"
android:background="#drawable/btnbackground"
android:textColor="#color/textcolour"
/>
</LinearLayout>
</LinearLayout>
</ScrollView>
I think should try something like that to show the default values if no internet, else get the values of the sql
if(cd.isConnectingToInternet()){
prodropdown();
}else{
//Setting adapter to show the items in the spinner
List<String> spinnerArray = new ArrayList<String>();
spinnerArray.add("default value 1");
spinnerArray.add("default value 2");
spinnerArray.add("default value 3");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, spinnerArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter);
}

JSON Object to Spinner crash app

I have the following problem.
A date picker where i select a date, this gets put into an array with the username.The array used to get the users start times by using the GetMemberPatrolStartTimes in Parser.This returns the JSON object that is then sent to the patrol history which populates a spinner.
I can see that the spinner gets populated but as soon as i click to drop the spinner down i get the error that is attached in the file.
Now i can read the error, but using it to solve the problem i can not get right.
Appreciate all help, guidance and any constructive criticism
Error: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
This is being caught in a UncaughtException method
eyeWatchApi.java
public JSONObject GetMemberPatrolStartTimes(ArrayList<String> details)throws Exception {
JSONObject result = null;
JSONObject o = new JSONObject();
JSONObject p = new JSONObject();
o.put("interface","eyeWatchApi");
o.put("method", "GetMemberPatrolStartTimes");
p.put("details",mapObject(details));
o.put("parameters", p);
String s = o.toString();
String r = load(s);
result = new JSONObject(r);
return result;
}
Parser.java
public Object GetPatrolHistoryStartTimes(JSONObject object){
String[] id_Array;
String[] time_Array;
try{
JSONArray a = object.getJSONArray("Value");
id_Array = new String[a.length()];
time_Array = new String[a.length()];
for (int i = 0; i < a.length(); i++) {
JSONObject b = a.getJSONObject(i);
id_Array[i]=b.getString("startID");
time_Array[i]=b.getString("startTime");
return new Object[]{id_Array,time_Array};
}
}catch (JSONException e){
return e;
}catch (Exception e){
return e;
}
return null;
}
Patrol_History.java
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.patrol_history,container,false);
timeSpinner = (Spinner) view.findViewById(R.id.TimeSpinner);
timeSpinner.setOnItemSelectedListener(this);
}
#Override
public void onClick(View view)
{
switch(view.getId())
{
case R.id.load_polly_btn :
{
drawpoliline();
break;
}
case R.id.select_date_txt :
{
Date_Pick_Dialog picker = new Date_Pick_Dialog();
picker.setDatePickerDialogFragmentEvents(this);
picker.show(getFragmentManager(), "datePicker");
break;
}
default:
{
break;
}
}
}
#Override
public void onDateSelected(String _date) {
patrolHistoryManager = new PatrolHistoryManager(getActivity());
patrolHistoryManager.setDate(_date);
selectDate_tv.setText(_date);
date = _date;
new AsyncSendDetails().execute(date);
//new AsyncGetAvailibleSlots().execute(_date);
}
public class AsyncSendDetails extends AsyncTask<String, Void, Object[]> {
#Override
protected Object[] doInBackground(String... params) {
eyeWatchApi api = new eyeWatchApi();
Parser parser = new Parser();
detailsList = new ArrayList<String>();
detailsList.add(userName);
detailsList.add(params[0]);
Object[] ob = new Object[0];
try {
ob = (Object[]) parser.GetPatrolHistoryStartTimes(api.GetMemberPatrolStartTimes(detailsList));
} catch (Exception e) {
e.printStackTrace();
}
return ob;
}
#Override
protected void onPostExecute(Object[] ob) {
if(ob != null)
{
timeID = (String[]) ob[0];
times = (String[]) ob[1];
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(), R.layout.countries_spinner_item, times);
dataAdapter.setDropDownViewResource(R.layout.countries_spinner_item_droplist);
timeSpinner.setAdapter(dataAdapter);
}
else
{
Toast.makeText(getActivity(),"No Slots Available",Toast.LENGTH_LONG).show();
}
}
}
Layout File
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/black">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Select Date"
android:textAlignment="center"
android:textColor="#d32f2f"
android:cursorVisible="false"
android:shadowColor="#color/black"
android:id="#+id/select_date_txt"
android:layout_gravity="top|right"
android:text="02/05/2016"
android:paddingRight="15dp"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/white"
android:layout_below="#+id/select_date_txt"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/relativeLayout2" />
<Spinner
android:id="#+id/TimeSpinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#d32f2f"
android:layout_below="#+id/select_date_txt"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
</Spinner>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="2dp"
android:paddingBottom="2dp"
android:background="#color/primary"
android:id="#+id/relativeLayout"
android:layout_below="#+id/TimeSpinner"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/relativeLayout">
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_weight="0.73"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
</fragment>
<android.support.v7.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Load Lines"
android:id="#+id/load_polly_btn"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
</LinearLayout>
After almost a week of struggling i have just found the answer so i will be keeping it on here for all to see if there is a need for it
**Parser.java**
public Object GetPatrolHistoryStartTimes(JSONObject object){
String[] id_Array;
String[] time_Array;
try{
JSONArray a = object.getJSONArray("Value");
id_Array = new String[a.length()];
time_Array = new String[a.length()];
for (int i = 0; i < a.length(); i++) {
JSONObject b = a.getJSONObject(i);
id_Array[i]=b.getString("startID");
time_Array[i]=b.getString("startTime");
}
return new Object[]{id_Array,time_Array};
}catch (JSONException e){
return e;
}catch (Exception e){
return e;
}
return null;
}
The problem was that my return of the object should not have been inside the for statement but rather after it, after the loop has been completed

Selections disappear when scrolling in listview, along with strange behaviour

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
}

Categories