I'm new in android apps in Java. The example app should let me choose currencies I want to have in the ListView. Every time I want to choose a currency from the list, the app crashes I get the error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.a5_listview, PID: 12333
java.lang.ClassCastException: androidx.appcompat.widget.AppCompatTextView cannot be cast to android.widget.CheckedTextView
at com.example.a5_listview.MainActivity$1.onItemClick(MainActivity.java:48)
MainActivity.java:
package com.example.a5_listview;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckedTextView;
import android.widget.ListView;
import android.widget.Toast;
import com.google.gson.Gson;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
List<nbpCurrency> currencies = new ArrayList<>();
ListView listView;
Context context;
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
context = this;
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CheckedTextView v = (CheckedTextView) view;
boolean isCurrentChoice = v.isChecked();
nbpCurrency currency = (nbpCurrency) listView.getItemAtPosition(position);
currency.setChosen(isCurrentChoice);
}
});
getCurrencies();
}
private void getCurrencies() {
progressDialog = ProgressDialog.show(context, "Getting currencies",
"Please wait...", true);
AsyncTask.execute(new Runnable() {
#Override
public void run() {
try {
URL nbpEndpoint =
new URL("http://api.nbp.pl/api/exchangerates/tables/a/");
HttpURLConnection nbpConnection =
(HttpURLConnection) nbpEndpoint.openConnection();
nbpConnection.setRequestProperty("Accept", "application/json");
if(nbpConnection.getResponseCode() == 200) {
InputStreamReader is =
new InputStreamReader(nbpConnection.getInputStream());
Gson gson = new Gson();
final nbpCurrencies[] nbpCurrenciesArray = gson.fromJson(is, nbpCurrencies[].class);
nbpConnection.disconnect();
runOnUiThread(new Runnable() {
#Override
public void run() {
currencies.addAll(Arrays.asList(nbpCurrenciesArray[0].getCurrencies()));
Collections.sort(currencies);
ArrayAdapter<nbpCurrency> arrayAdapter =
new ArrayAdapter<nbpCurrency>(context,
android.R.layout.simple_list_item_1, currencies);
listView.setAdapter(arrayAdapter);
selectChosen();
progressDialog.dismiss();
}
});
} else {
runOnUiThread(new Runnable() {
#Override
public void run() {
progressDialog.dismiss();
Toast.makeText(context, "There was a problem getting the data",
Toast.LENGTH_LONG).show();
}
});
}
} catch(Exception e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
#Override
public void run() {
progressDialog.dismiss();
Toast.makeText(context, "There was a problem getting the data",
Toast.LENGTH_LONG).show();
}
});
}
}
});
}
private void selectChosen() {
SharedPreferences pref =
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Set<String> chosenCurrenciesCodes = pref.getStringSet("currenciesCodes", new HashSet<String>());
for(int i = 0; i < currencies.size(); i++) {
nbpCurrency currency = currencies.get(i);
if(chosenCurrenciesCodes.contains(currency.getCode())) {
currency.setChosen(true);
listView.setItemChecked(i, true);
}
}
}
public void saveChosen(View view) {
SharedPreferences pref =
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Set<String> chosenCurrenciesCodes = new HashSet<>();
for(nbpCurrency currency : currencies) {
if(currency.isChosen()) {
chosenCurrenciesCodes.add(currency.getCode());
}
}
pref.edit().putStringSet("currenciesCodes", chosenCurrenciesCodes).apply();
}
}
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"
tools:context=".MainActivity">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toTopOf="#+id/button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</ListView>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:onClick="saveChosen"
android:text="Save"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
nbpCurrencies.java:
package com.example.a5_listview;
import com.google.gson.annotations.SerializedName;
public class nbpCurrencies {
private String table;
private String no;
private String effectiveDate;
#SerializedName(value = "rates")
private nbpCurrency[] currencies;
public String getTable() {
return table;
}
public void setTable(String table) {
this.table = table;
}
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
public String getEffectiveDate() {
return effectiveDate;
}
public void setEffectiveDate(String effectiveDate) {
this.effectiveDate = effectiveDate;
}
public nbpCurrency[] getCurrencies() {
return currencies;
}
public void setCurrencies(nbpCurrency[] currencies) {
this.currencies = currencies;
}
}
nbpCurrency.java:
package com.example.a5_listview;
class nbpCurrency implements Comparable<nbpCurrency> {
private String currency;
private String code;
private double mid;
private transient boolean chosen = false;
public nbpCurrency() {
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public double getMid() {
return mid;
}
public void setMid(double mid) {
this.mid = mid;
}
public boolean isChosen() {
return chosen;
}
public void setChosen(boolean chosen) {
this.chosen = chosen;
}
#Override
public String toString() {
return String.format("%s [%s: %.3f]", code, currency, mid);
}
#Override
public int compareTo(nbpCurrency nbpCurrency) {
return code.compareTo(nbpCurrency.getCode());
}
}
In logs I can see the line causing all of mess:
CheckedTextView v = (CheckedTextView) view;
What is cause of that error? I've looked through other answers on StackOverflow but I still can't find any solution. Maybe I just don't see an obvious mistake. Thanks for help.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CheckedTextView v = (CheckedTextView) view;
boolean isCurrentChoice = v.isChecked();
nbpCurrency currency = (nbpCurrency) listView.getItemAtPosition(position);
currency.setChosen(isCurrentChoice);
}
});
Here you set a ClickListener. The view field is returned from adapter and it is TextView. That's the way you get CastException. In this method you also get id and position fields and you can use them.
If you want to enable multi-choice, you need to build your ArrayAdapter with another layout like this:
ArrayAdapter<nbpCurrency> arrayAdapter =
new ArrayAdapter<nbpCurrency>(context,
android.R.layout.simple_list_item_multiple_choice, currencies);
Related
MY PROBLEM -
my cardview is going over the screen(can be seen in the image) even if the says matchparent.
my database node
Please help....... is this a bug or smth?
What am i doing = i m trying to retrieve the data from firebase in a recycler view, the data is being retrieved but the item of the recyclerview is giving problem, as the cardview is half outside the screen even if the cardview is set to matchparent and wrapcontent please help if possible
My recycler Item
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/Cdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hi"
android:textSize="50dp"
android:layout_gravity="center"
android:layout_marginTop="20dp"/>
</androidx.cardview.widget.CardView>
my Adapterclass
package com.sjsbhints.pdfmanager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
public class CAdapter extends FirebaseRecyclerAdapter<Cmodel,CAdapter.myViewHolder> {
/**
* Initialize a {#link RecyclerView.Adapter} that listens to a Firebase query. See
* {#link FirebaseRecyclerOptions} for configuration options.
*
* #param options
*/
public CAdapter(#NonNull FirebaseRecyclerOptions<Cmodel> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull myViewHolder holder, int position, #NonNull Cmodel model) {
// if(model.Cdate.isEmpty()){
// holder.Cdate.setText("Null");
// }
holder.Cdate.setText(model.getCdate());
// holder.Cheading.setText(model.getCheading());
// holder.Cbody.setText(model.getCbody());
}
#NonNull
#Override
public myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.circular_item,parent,false);
return new myViewHolder(view);
}
class myViewHolder extends RecyclerView.ViewHolder{
TextView Cdate,Cheading,Cbody,Ndate,Nheading,Nsheading,Nbody,Tdate,Tsubject,Ttopic,Ttdate;
public myViewHolder(#NonNull View itemView) {
super(itemView);
Cdate = itemView.findViewById(R.id.Cdate);
// Cheading = itemView.findViewById(R.id.cheading);
// Cbody = itemView.findViewById(R.id.cbody);
}
}
}
my model class
package com.sjsbhints.pdfmanager;
public class Cmodel {
String Cdate,Cheading,Cbody,Ndate,Nheading,Nsheading,Nbody,Tdate,Tsubject,Ttopic,Ttdate;
Cmodel(){
}
public Cmodel(String cdate, String cheading, String cbody, String ndate, String nheading, String nsheading, String nbody, String tdate, String tsubject, String ttopic, String ttdate) {
Cdate = cdate;
Cheading = cheading;
Cbody = cbody;
Ndate = ndate;
Nheading = nheading;
Nsheading = nsheading;
Nbody = nbody;
Tdate = tdate;
Tsubject = tsubject;
Ttopic = ttopic;
Ttdate = ttdate;
}
public String getCdate() {
return Cdate;
}
public void setCdate(String cdate) {
Cdate = cdate;
}
public String getCheading() {
return Cheading;
}
public void setCheading(String cheading) {
Cheading = cheading;
}
public String getCbody() {
return Cbody;
}
public void setCbody(String cbody) {
Cbody = cbody;
}
public String getNdate() {
return Ndate;
}
public void setNdate(String ndate) {
Ndate = ndate;
}
public String getNheading() {
return Nheading;
}
public void setNheading(String nheading) {
Nheading = nheading;
}
public String getNsheading() {
return Nsheading;
}
public void setNsheading(String nsheading) {
Nsheading = nsheading;
}
public String getNbody() {
return Nbody;
}
public void setNbody(String nbody) {
Nbody = nbody;
}
public String getTdate() {
return Tdate;
}
public void setTdate(String tdate) {
Tdate = tdate;
}
public String getTsubject() {
return Tsubject;
}
public void setTsubject(String tsubject) {
Tsubject = tsubject;
}
public String getTtopic() {
return Ttopic;
}
public void setTtopic(String ttopic) {
Ttopic = ttopic;
}
public String getTtdate() {
return Ttdate;
}
public void setTtdate(String ttdate) {
Ttdate = ttdate;
}
}
my MainActivity
package com.sjsbhints.pdfmanager;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.FirebaseDatabase;
public class CircularAct extends AppCompatActivity {
RecyclerView recyclerView;
CAdapter cAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_circular2);
recyclerView = findViewById(R.id.rv);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
FirebaseRecyclerOptions<Cmodel> options =
new FirebaseRecyclerOptions.Builder<Cmodel>()
.setQuery(FirebaseDatabase.getInstance().getReference().child("CircularData"), Cmodel.class)
.build();
cAdapter = new CAdapter(options);
recyclerView.setAdapter(cAdapter);
}
#Override
protected void onStart() {
super.onStart();
cAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
cAdapter.stopListening();
}
}
my mainactivity 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"
tools:context=".CircularAct">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rv"
android:layout_width="599dp"
android:layout_height="960dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Your CardView definitely matched the parent's width because it inherited the width of the RecyclerView since that's its parent.
Your RecyclerView, on the other hand, has a width of 599dp. The fixed size means that it will ignore the device's width. To match the device's width and height, set it to match_parent or use 0dp since you're using a constraint layout in your case.
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rv"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
I am trying to implement RecyclerView using ParseObject but on my screen nothing is showing up!
Following is the code for the activity where recycler view is to implemented.
AdminShowStudentId.java
package com.example.Aphexams;
import android.content.Intent;
import android.os.Bundle;
import android.app.Activity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Adapter;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.Toast;
import com.parse.FindCallback;
import com.parse.GetCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseQueryAdapter;
import java.util.ArrayList;
import java.util.List;
//import app.android.project.com.olexam.R;
public class AdminShowStudentId extends Activity {
private RecyclerView recycleerviewDetails;
private RecyclerView.LayoutManager layoutManager;
private StudentIdAdapter studentidAdapter;
private ArrayList<StudentId> studentidarraylist;
private boolean notComplete = true;
private String studId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_show_student_id);
final StudentId studentId=new StudentId();
studentidarraylist=new ArrayList<StudentId>();
if(notComplete) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("studAuth");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
for (ParseObject object : objects) {
String studentid = (String) object.get("StudUserName");
studentId.setStudentId(studentid);
studentidarraylist.add(studentId);
}
//is it fetching or not
} else {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
notComplete=false;
}
recycleerviewDetails=(RecyclerView)findViewById(R.id.studentidrecyclerview);
if (recycleerviewDetails != null)
{
recycleerviewDetails.setHasFixedSize(true);
}
/*fetching data from the database*/
studentidAdapter=new StudentIdAdapter(studentidarraylist);
recycleerviewDetails.setAdapter(studentidAdapter);
studentidAdapter.notifyDataSetChanged();
layoutManager=new GridLayoutManager(this,1);
recycleerviewDetails.setLayoutManager(layoutManager);
recycleerviewDetails.addOnItemTouchListener(new RecyclerViewListener(AdminShowStudentId.this,new RecyclerViewListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
studId=studentidarraylist.get(position).getStudentId();
Intent i=new Intent(AdminShowStudentId.this,ViewStudent.class);
i.putExtra("studId",studId);
}
}));
}
}
following is the code for StudentIdAdapter.java
package com.example.Aphexams;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by HP on 24-05-2018.
*/
public class StudentIdAdapter extends RecyclerView.Adapter<StudentIdAdapter.StudentIdViewHolder>
{
private List<StudentId> studentIdList;
public StudentIdAdapter(ArrayList<StudentId> studentidarraylist) {
this.studentIdList=studentidarraylist;
}
#Override
public StudentIdViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.studentid_row,parent,false);
StudentIdViewHolder studentIdViewHolder=new StudentIdViewHolder(view);
return studentIdViewHolder;
}
#Override
public void onBindViewHolder(StudentIdViewHolder holder, int position) {
StudentId studentid= studentIdList.get(position);
holder.tvStudentId.setText(studentid.getStudentId());
// holder.tvanswerdate.setText(answer.getAnswerdate());
}
#Override
public int getItemCount() {
return 0;
}
public class StudentIdViewHolder extends RecyclerView.ViewHolder
{
private TextView tvStudentId;
public StudentIdViewHolder(View itemView)
{
super(itemView);
tvStudentId=(TextView)itemView.findViewById(R.id.studentidtv);
}
}
}
following is the code for RecyclerViewListener.java
package com.example.Aphexams;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
/**
* Created by HP on 24-05-2018.
*/
public class RecyclerViewListener implements RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
GestureDetector mGestureDetector;
public interface OnItemClickListener
{
public void onItemClick(View view, int position);
}
public RecyclerViewListener(Context context, OnItemClickListener listener)
{
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener()
{
#Override public boolean onSingleTapUp(MotionEvent e)
{
return true;
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View childView = rv.findChildViewUnder(e.getX(),e.getY());
if(childView != null && mListener != null && mGestureDetector.onTouchEvent(e))
{
mListener.onItemClick(childView, rv.getChildAdapterPosition(childView));
return true;
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
Following is the code for StudentId.java
package com.example.Aphexams;
/**
* Created by HP on 24-05-2018.
*/
public class StudentId {
private String StudentId;
public String getStudentId() {
return StudentId;
}
public void setStudentId(String studentId) {
StudentId = studentId;
}
}
following is my code for layout of activity_admin_show_student_id.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView 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"
tools:context="com.example.Aphexams.AdminShowStudentId">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/studentidrecyclerview">
</android.support.v7.widget.RecyclerView>
</android.support.v4.widget.NestedScrollView>
following is the code for studentid
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="20dp"
android:id="#+id/studentidtv"
android:textSize="16dp"
android:text="now you see me!"/>
</LinearLayout>
I have tried to take some help from How to use ParseObjects with a RecyclerView?.
Taking a look at you code, I guess the error is that you set you adapter with a empty list at first, then you add items to your list in your FindCallback but you never tell the list to re-render the items.
Have you checked when you set you adapter if the list is actually populated? Because since your query is running in background, there is a chance the below lines will be execute before your query finishes.
studentidAdapter=new StudentIdAdapter(studentidarraylist);
recycleerviewDetails.setAdapter(studentidAdapter);
To achieve what you are trying to do, I guess you should call
studentidAdapter=new StudentIdAdapter(studentidarraylist);
recycleerviewDetails.setAdapter(studentidAdapter);
studentidAdapter.notifyDataSetChanged();
inside your FindCallback, when you are sure your list is populated.
So, I made the following changes in my code.
AdminShowStudentId.java
As suggested by Thiago Loddi
public class AdminShowStudentId extends Activity {
private RecyclerView recycleerviewDetails;
private RecyclerView.LayoutManager layoutManager;
private StudentIdAdapter studentidAdapter;
private ArrayList<StudentId> studentidarraylist;
private boolean notComplete = true;
private String studId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_show_student_id);
recycleerviewDetails=(RecyclerView)findViewById(R.id.studentidrecyclerview);
if (recycleerviewDetails != null)
{
recycleerviewDetails.setHasFixedSize(true);
}
layoutManager=new GridLayoutManager(this,1);
recycleerviewDetails.setLayoutManager(layoutManager);
studentidarraylist=new ArrayList<StudentId>();
if(notComplete) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("studAuth");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
for(int i=0;i<objects.size();i++)
{
String studentidstring = (String) objects.get(i).get("StudUserName");
StudentId studentId=new StudentId();
studentId.setStudentId(studentidstring);
studentidarraylist.add(studentId);
}
//Now the arraylist is populated!
for(int i=0;i<studentidarraylist.size();i++)
{
Toast.makeText(AdminShowStudentId.this,studentidarraylist.get(i).getStudentId() + " "+i, Toast.LENGTH_SHORT).show();
}
studentidAdapter=new StudentIdAdapter(studentidarraylist);
recycleerviewDetails.setAdapter(studentidAdapter);
studentidAdapter.notifyDataSetChanged();
recycleerviewDetails.addOnItemTouchListener(new RecyclerViewListener(AdminShowStudentId.this,new RecyclerViewListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
studId=studentidarraylist.get(position).getStudentId();
Intent i=new Intent(AdminShowStudentId.this,ViewStudent.class);
i.putExtra("studId",studId);
startActivity(i);
}
}));
} else {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
notComplete=false;
}
}
}
And It worked!!!
Spent hours trying to get this to work but to no avail :(
I have set up a searchfilter for my listview, which works fine. But each has a checkbox - when I check the checkbox either before or after filtering, it is not being remembered which makes the filter pointless. Would appreciate some guidance here.
My code:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.SearchView;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity implements
SearchView.OnQueryTextListener {
private AllStuffModel[] modelItems = AllStuff.allConditions;
private ListView conditionsView;
private SearchView search_view;
private AllStuffAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new AllStuffAdapter(this, new ArrayList<AllStuffModel>(Arrays.asList(modelItems)), this);
conditionsView = (ListView) findViewById(R.id.condition_list);
conditionsView.setAdapter(adapter);
search_view = (SearchView) findViewById(R.id.search_view);
search_view.setOnQueryTextListener(this);
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
}
AllStuffAdapter.java
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class AllStuffAdapter extends ArrayAdapter<AllStuffModel> implements Filterable {
private List<AllStuffModel> modelItems;
private List<AllStuffModel> filteredModelItems;
private Context context;
private MainActivity mainActivity;
private ValueFilter valueFilter;
#Override
public boolean hasStableIds() {
return true;
}
public AllStuffAdapter(Context context, List<AllStuffModel> resource, MainActivity mainActivity) {
super(context, R.layout.condition_row, resource);
this.context = context;
this.modelItems = resource;
this.mainActivity = mainActivity;
filteredModelItems = modelItems;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
convertView = inflater.inflate(R.layout.condition_row, parent, false);
TextView conditionText = (TextView) convertView.findViewById(R.id.condition_text);
final CheckBox conditionCheckBox = (CheckBox) convertView.findViewById(R.id.condition_checkbox);
conditionCheckBox.setId(position);
conditionText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!conditionCheckBox.isChecked()) {
conditionCheckBox.setChecked(true);
modelItems.get(position).setIsChecked(true);
}
else if(conditionCheckBox.isChecked()) {
conditionCheckBox.setChecked(false);
modelItems.get(position).setIsChecked(false);
}
System.out.println( modelItems.get(position).isChecked());
}
});
conditionText.setText(modelItems.get(position).getName());
conditionCheckBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckBox currentCheckBox = (CheckBox) v;
if (currentCheckBox.isChecked()) { // If checked set to true, else false
modelItems.get(position).setIsChecked(true);
} else if (!currentCheckBox.isChecked()) {
modelItems.get(position).setIsChecked(false);
}
System.out.println( modelItems.get(position).isChecked());
}
});
return convertView;
}
#Override
public int getCount() {
return modelItems.size();
}
#Override
public long getItemId(int position) {
return modelItems.indexOf(getItem(position));
}
#Override
public Filter getFilter() {
if (valueFilter == null) {
valueFilter = new ValueFilter();
}
return valueFilter;
}
private class ValueFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null && constraint.length() > 0) {
ArrayList<AllStuffModel> filterList = new ArrayList<AllStuffModel>();
for (int i = 0; i < filteredModelItems.size(); i++) {
if ((filteredModelItems.get(i).getName().toUpperCase())
.contains(constraint.toString().toUpperCase())) {
AllStuffModel allConditionsModel = new AllStuffModel(filteredModelItems.get(i).getCode(),filteredModelItems.get(i).getName());
allConditionsModel.setIsChecked(filteredModelItems.get(i).isChecked());
filterList.add(allConditionsModel);
}
}
results.count = filterList.size();
results.values = filterList;
} else {
results.count = filteredModelItems.size();
results.values = filteredModelItems;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
modelItems = (ArrayList<AllStuffModel>) results.values;
notifyDataSetChanged();
}
}
}
AllStuffModel.java
public class AllStuffModel {
private String name;
private String code;
private boolean isChecked;
public AllStuffModel(String code, String name) {
this.name = name;
this.code = code;
}
public String getName() {
return this.name;
}
public String getCode() {
return this.code;
}
public boolean isChecked() {
return isChecked;
}
public void setIsChecked(boolean isChecked) {
this.isChecked = isChecked;
}
}
AllStuff.java
public class AllStuff {
private AllStuff() {
}
public static final AllStuffModel[] allConditions = {
new AllStuffModel("ca", "Candy"),
new AllStuffModel("fo", "Football"),
new AllStuffModel("mu", "Music"),
new AllStuffModel("sn", "Snooker"),
};
}
condition_row.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:orientation="horizontal"
android:paddingTop="10dp">
<CheckBox
android:id="#+id/condition_checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="7dp" />
<TextView
android:id="#+id/condition_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:textColor="#DE000000"
android:textSize="17sp" />
</LinearLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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/scrollview_main"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<SearchView
android:id="#+id/search_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="2dp"
android:queryHint="Search...." />
<ListView
android:id="#+id/condition_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></ListView>
</LinearLayout>
</ScrollView>
What I have tried to do is use notifyDataSetChaanged() in my onClick methods in AllStuffAdapter, but this stops the checkbox from being checked completely.
TL/DR: How can I remember checkboxes checked with the search filter?
Try changing
conditionCheckBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckBox currentCheckBox = (CheckBox) v;
if (currentCheckBox.isChecked()) { // If checked set to true, else false
modelItems.get(position).setIsChecked(true);
} else if (!currentCheckBox.isChecked()) {
modelItems.get(position).setIsChecked(false);
}
System.out.println( modelItems.get(position).isChecked());
}
});
to
conditionCheckBox.setOnCheckedChangeListener(null);
conditionCheckBox.setChecked(modelItems.get(position).isChecked());
conditionCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
modelItems.get(position).setIsChecked(isChecked);
}
});
Thanks #faranjit, I believe adding this (with your changes) fully resolves the issues after modelItems.get(position).setIsChecked(isChecked);. Could this be verified please?
for(AllStuffModel item: filteredModelItems){
if(modelItems.get(position).getCode().equals(item.getCode())){
item.setIsChecked(isChecked);
}
}
We just update the list by matching the right item. Note: the code is something I set myself and I can always guarantee it will be unique.
I'm using an array adapter to populate a listview from an ArrayList. Per the below xml file, the listview contains a checkbox and two textviews. I'm also using a custom checkbox class that holds information from my ArrayList. My custom checkbox (ListCheckBox.java) class (below) has a method called get_is_complete and set_is_complete. The set_is_complete method is currently taking boloean values from my ArrayList and as a result generates a listview of checkboxes where the checkbox is either checked or unchecked depending on the value of Planet object which is passed in the ArrayList.
Everything works fine, however I need to change the boolean state of set_is_complete when a user clicks on the checkbox. I created the below setOnClickListener within my adapter class that works fine.
The problem is that initially the set_is_complete method needs to be evaluated based on inital values in the array, but the user should be able to change set_is_complete method when they click on the checkbox. I was thinking of the below of conditional statement, but I'm stuck on the condition. Please help.
Possible conditional statement, but I'm stuck on the condition.
if (condiition){
holder.chkBox.set_is_complete(p.isSelected());
}else{
holder.chkBox.set_is_complete(boolean_value);
}
single_list_view_item.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"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="false">
<com.example.chad.checkbox.ListCheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/chk_box"
android:layout_alignParentLeft="true"
android:textSize="40dp"
/>
<TextView
android:text="Mercury"
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/chk_box"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:text="570000000"
android:id="#+id/dist"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/name"
android:layout_toRightOf="#id/chk_box"
android:textSize="16sp"
android:textStyle="italic" />
</RelativeLayout>
Below is my PlanetAdpapter.java class
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import com.example.chad.checkbox.ListCheckBox;
/**
* Created by Chad on 3/23/2016.
*/
class Planet{
String name;
int distance;
boolean selected;
public Planet(String name, int distance, boolean selected) {
super();
this.name = name;
this.distance = distance;
this.selected = selected;
}
public String getName() {
return name;
}
public int getDistance() {
return distance;
}
public boolean isSelected() {
return selected;
}
public void setName(String name) {
this.name = name;
}
public void setDistance(int distance) {
this.distance = distance;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
public class PlanetAdapter extends ArrayAdapter<Planet> {
private List<Planet> planetList;
private Context context;
View v;
PlanetHolder holder;
Boolean boolean_value;
public PlanetAdapter(List<Planet> planetlist, Context context) {
super(context, R.layout.single_list_view_item, planetlist);
this.planetList = planetlist;
this.context = context;
}
private static class PlanetHolder{
public TextView planetName;
public TextView distView;
public ListCheckBox chkBox;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
//View v = convertView;
v = convertView;
//PlanetHolder holder = new PlanetHolder();
holder = new PlanetHolder();
if(v ==null){
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.single_list_view_item, null);
holder.planetName = (TextView)v.findViewById(R.id.name);
holder.distView = (TextView)v.findViewById(R.id.dist);
holder.chkBox = (ListCheckBox)v.findViewById(R.id.chk_box);
v.setTag(holder);
//holder.chkBox.setOnCheckedChangeListener((MainActivity) context);
}else{
holder = (PlanetHolder)v.getTag();
}
Planet p = planetList.get(position);
holder.planetName.setText(p.getName());
holder.distView.setText("" + p.getDistance());
holder.chkBox.set_is_complete(p.isSelected());
final PlanetHolder finalHolder = holder;
final String name;
name = p.getName();
holder.chkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (finalHolder.chkBox.isChecked()) {
boolean_value = true;
Toast.makeText(v.getContext(), name + "Is Checked -- " + boolean_value.toString(), Toast.LENGTH_LONG).show();
} else {
boolean_value = false;
Toast.makeText(v.getContext(), name + "Is Unchecked -- " + boolean_value.toString(), Toast.LENGTH_LONG).show();
}
}
});
holder.chkBox.setPlanet(p.getName());
holder.chkBox.setDistance(p.getDistance());
if(holder.chkBox.get_is_complete() == false){
holder.chkBox.setChecked(false);
}else{
holder.chkBox.setChecked(true);
}
holder.chkBox.setTag(p);
return v;
}
}
Below is my MainActivity.java Class
import android.app.Activity;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends Activity {
ListView lv;
ArrayList<Planet> planetList;
PlanetAdapter plAdapter;
View vv;
ListCheckBox chBox;
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv = (ListView) findViewById(R.id.listview);
displayPlanetList();
vv = lv.getAdapter().getView(0, null,null);
chBox = (ListCheckBox) vv.findViewById(R.id.chk_box);
String p = chBox.getPlanet();
Toast.makeText(getApplicationContext(), p, Toast.LENGTH_LONG).show();
b = (Button)findViewById(R.id.btn);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer c = plAdapter.getCount();
Integer lcount = lv.getCount();
vv = lv.getAdapter().getView(0, null, null);
chBox = (ListCheckBox) vv.findViewById(R.id.chk_box);
Boolean bb = chBox.get_is_complete();
String x = bb.toString();
Toast.makeText(getApplicationContext(), x, Toast.LENGTH_SHORT).show();
}
});
}
private void displayPlanetList(){
planetList = new ArrayList<Planet>();
planetList.add(new Planet("Mercury", 5700000, true));
planetList.add(new Planet("Venus", 2370000, false));
planetList.add(new Planet("Mars", 3500000, true));
planetList.add(new Planet("Jupiter", 5000000, false));
planetList.add(new Planet("Saturn", 7460000, true));
plAdapter = new PlanetAdapter(planetList, this);
lv.setAdapter(plAdapter);
}
}
Custom checkbox ListCheckBox.java
import android.annotation.TargetApi;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.CheckBox;
public class ListCheckBox extends CheckBox {
private String planet;
private Boolean is_complete;
private Integer distance;
public ListCheckBox(Context context) {
super(context);
//setButtonDrawable(new StateListDrawable());
}
public ListCheckBox(Context context, AttributeSet attrs) {
super(context, attrs);
//setButtonDrawable(new StateListDrawable());
}
public ListCheckBox(Context context, AttributeSet attrs, int defStyleAttr) {
super(context,attrs,defStyleAttr);
//setButtonDrawable(new StateListDrawable());
}
#TargetApi(21)
public ListCheckBox(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)
{super(context,attrs,defStyleAttr,defStyleRes);}
public String getPlanet(){
return planet;
}
public void setPlanet(String planet){
this.planet = planet;
}
public Boolean get_is_complete(){return is_complete;}
public void set_is_complete(Boolean is_complete){
this.is_complete = is_complete;
}
public Integer getDistance(){
return distance;
}
public void setDistance(Integer distance){
this.distance = distance;
}
}
I was able to figure it out. If I update the model directly via the below if statement within my Adapter class if works
final TaskHolder finalHolder = holder;
final String name;
name = t.getMy_task_name();
holder.chkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (finalHolder.chkBox.isChecked()) {
//boolean_value = true;
t.setMy_task_is_complete(true);
Toast.makeText(v.getContext(), name + "Is Checked -- " + t.getMy_task_is_complete().toString(), Toast.LENGTH_LONG).show();
} else {
//boolean_value = false;
t.setMy_task_is_complete(false);
Toast.makeText(v.getContext(), name + "Is Unchecked -- " + t.getMy_task_is_complete().toString(), Toast.LENGTH_LONG).show();
}
}
});
Below is the code for my model
public class Task {
Integer my_task_id;
String my_task_name;
Boolean my_task_is_complete;
Integer my_barcode;
public Task(){
}
public Task(Integer my_task_id, String my_task_name, Boolean my_task_is_complete, Integer my_barcode){
super();
this.my_task_id = my_task_id;
this.my_task_name = my_task_name;
this.my_task_is_complete = my_task_is_complete;
this.my_barcode = my_barcode;
}
public Integer getMy_task_id() {
return my_task_id;
}
public void setMy_task_id(Integer my_task_id) {
this.my_task_id = my_task_id;
}
public String getMy_task_name() {
return my_task_name;
}
public void setMy_task_name(String my_task_name) {
this.my_task_name = my_task_name;
}
public Boolean getMy_task_is_complete() {
return my_task_is_complete;
}
public void setMy_task_is_complete(Boolean my_task_is_complete) {
this.my_task_is_complete = my_task_is_complete;
}
public Integer getMy_barcode() {
return my_barcode;
}
public void setMy_barcode(Integer my_barcode) {
this.my_barcode = my_barcode;
}
}
I am trying to load a custom listview using Volley Networking library but there are no results while running the app and no errors on the code. The data come from a JSON file
JSON OUTPUT HERE
Below are my classes :
MainActivity.java
package info.androidhive.customlistviewvolley;
import info.androidhive.customlistviewvolley.adater.CustomListAdapter;
import info.androidhive.customlistviewvolley.app.AppController;
import info.androidhive.customlistviewvolley.model.CaseStudy;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.ListView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
public class MainActivity extends Activity {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
// Movies json url
private static final String url = "http://178.62.67.237/api/v1/residential/?format=json";
private ProgressDialog pDialog;
private List<CaseStudy> caseList = new ArrayList<CaseStudy>();
private ListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, caseList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// changing action bar color
getActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#1b1b1b")));
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
CaseStudy reference = new CaseStudy();
reference.setTitle(obj.getString("title"));
reference.setThumbnailUrl(obj.getString("image"));
reference.setPostcode(obj.getString("postcode"));
// adding movie to movies array
caseList.add(reference);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#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;
}
}
CaseStudy.java:
package info.androidhive.customlistviewvolley.model;
public class CaseStudy {
private String title;
private String thumbnailUrl;
private String postcode;
public CaseStudy() {
}
public CaseStudy(String name, String thumbnailUrl, String postcode) {
this.title = name;
this.thumbnailUrl = thumbnailUrl;
this.postcode = postcode;
}
public String getTitle() {
return title;
}
public void setTitle(String name) {
this.title = name;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
public String getPostcode() {
return postcode;
}
}
CustomListAdapter.java:
package info.androidhive.customlistviewvolley.adater;
import info.androidhive.customlistviewvolley.R;
import info.androidhive.customlistviewvolley.app.AppController;
import info.androidhive.customlistviewvolley.model.CaseStudy;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<CaseStudy> caseItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<CaseStudy> caseItems) {
this.activity = activity;
this.caseItems = caseItems;
}
#Override
public int getCount() {
return caseItems.size();
}
#Override
public Object getItem(int location) {
return caseItems.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.list_row_custom, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.thumbnail);
TextView title = (TextView) convertView.findViewById(R.id.title);
TextView postcode = (TextView) convertView.findViewById(R.id.postcode);
//TextView genre = (TextView) convertView.findViewById(R.id.genre);
//TextView year = (TextView) convertView.findViewById(R.id.releaseYear);
// getting movie data for the row
CaseStudy c = caseItems.get(position);
// thumbnail image
thumbNail.setImageUrl(c.getThumbnailUrl(), imageLoader);
// title
title.setText(c.getTitle());
postcode.setText(c.getPostcode());
// rating
//rating.setText("Rating: " + String.valueOf(m.getRating()));
// genre
//String genreStr = "";
//for (String str : m.getGenre()) {
// genreStr += str + ", ";
//}
//genreStr = genreStr.length() > 0 ? genreStr.substring(0,
// genreStr.length() - 2) : genreStr;
//genre.setText(genreStr);
// release year
//year.setText(String.valueOf(m.getYear()));
return convertView;
}
}
ist_row_custom.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:background="#drawable/list_row_selector"
android:padding="8dp" >
<!-- Thumbnail Image -->
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/thumbnail"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_alignParentLeft="true"
android:layout_marginRight="8dp" />
<!-- Title -->
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/thumbnail"
android:layout_toRightOf="#+id/thumbnail"
android:textSize="#dimen/title"
android:textStyle="bold" />
<!-- Postcode-->
<TextView
android:id="#+id/postcode"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/title"
android:layout_marginTop="1dip"
android:layout_toRightOf="#+id/thumbnail"
android:textSize="#dimen/rating" />
<!-- Genre -->
<!-- Release Year -->
</RelativeLayout>
Any ideas what I have done wrong?
You are referring to wrong xml in you MainActivity. Kindly create a new xml for ex activity_main.xml and initiate your list view there.
Also in your code you are Calling JSONArray however your Json output shows it Json Object. Kindly change your code to JSONObject as shown below
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
hidePDialog();
System.out.println("JsonObject++===---"+jsonObject);
try {
JSONArray response = jsonObject.getJSONArray("objects");
for(int i=0; i <response.length(); i++){
JSONObject obj = response.getJSONObject(i);
CaseStudy reference = new CaseStudy();
reference.setTitle(obj.getString("title"));
reference.setThumbnailUrl(obj.getString("image_path"));
reference.setPostcode(obj.getString("postcode"));
// adding movie to movies array
caseList.add(reference);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
System.out.println("error");
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError arg0) {
hidePDialog();
}
});
AppController.getInstance().addToRequestQueue(jsonObjectRequest, TAG);
According to your Json you should get 'image_path' not 'image' .
reference.setThumbnailUrl(obj.getString("image"));
use
reference.setThumbnailUrl(obj.getString("image_path"));