Add new items to a ListView from a database - android

Recently I learned how to get informations from a database with Volley library.So I know now how to receive data from a php script in an Activity.
My problem is to display the data on my Activity, I'll explain it :
I have a project that is to create the app of a website which have news articles.
So in my database I have a table called article which contain a lot of articles. Of course I don't want to load them all at the start of the activity, so I wrote a php script which send articles to the app 5 by 5. The script is Ok.
In my request class which does a volley StringRequest, I receive these articles like this : String titles[] = new String[numberOfArticlesIWantToLoad]and String texts[] = new String[numberOfArticlesIWantToLoad].
With a Callback I send them to my activity and I display them in a ListView whith an Adapter.
The adapter works well but I don't know how can I load more items from my database and display them below the articles previously loaded... when I do again the request in my database (which send to my activity the 5 next articles) and I call again the adapter, new articles are displayed but not the former...
I know that I'm not far from the answer I expect...
First of all, is my script good for what I need ?
Secondly, what do I have to change in my Adapter to load next articles below former articles ?
That would help me a lot, thanks by advance for the time you would take on my issue !
Here is my adapter :
public class MonAdapter extends ArrayAdapter<String>{
private final Context context;
private String[] values;
private String[] values2;
public MonAdapter(Context context, String[] values, String[] values2) {
super(context, -1, values);
this.context = context;
this.values = values;
this.values2 = values2;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.list_layout, parent, false);
TextView titre = (TextView) rowView.findViewById(R.id.titre);
TextView article = (TextView) rowView.findViewById(R.id.article);
titre.setText(values[position]);
article.setText(values2[position]);
return rowView;
}
public void addItems(String[] titres, String[] texts){
String[] listTitres = new String[this.values.length + titres.length];
String[] listTexts = new String[this.values2.length + texts.length];
for(int i=0;i<this.values.length;i++){
listTitres[i] = this.values[i];
listTexts[i] = this.values2[i];
}
for(int i=0;i<titres.length;i++){
listTitres[this.values.length+i] = titres[i];
listTexts[this.values.length+i] = texts[i];
}
this.values = listTitres;
this.values2 = listTexts;
}
}
And here is my activity, from where I call the StringRequest (in MyRequest class) and the Adapter :
I tried to do my best to remove irrevelant code, I hope it's not too long
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
footerLayout = (RelativeLayout)getLayoutInflater().inflate(R.layout.footer_layout, null);
pb_charger = (ProgressBar)footerLayout.findViewById(R.id.pb_charger);
text = (TextView)findViewById(R.id.text);
pb_loader = (ProgressBar)findViewById(R.id.pb_loader);
list = (ListView)findViewById(R.id.list);
btn_charger = (Button)footerLayout.findViewById(R.id.btn_charger);
queue = VolleySingleton.getInstance(this).getRequestQueue();
request = new MyRequest(this, queue);
request.getArticles(nombreCharger, NOMBRE_ARTICLE_CHARGER, new MyRequest.GetArticlesCallback() {
#Override
public void onSuccess(String[] listeTitres, String[] listeArticles, boolean fin) {
*Some irrelevant code*
final MonAdapter adapterTitres = new MonAdapter(getApplicationContext(), listeTitres, listeArticles);
list.setAdapter(adapterTitres);
adapterTitres.notifyDataSetChanged();
list.addFooterView(footerLayout);
// list.removeFooterView(footerLayout);
}
nombreCharger++;
}
#Override
public void onError(String error, String id) {
}
});
btn_charger.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btn_charger.setVisibility(View.INVISIBLE);
pb_charger.setVisibility(View.VISIBLE);
list.removeFooterView(footerLayout);
request.getArticles(nombreCharger, NOMBRE_ARTICLE_CHARGER, new MyRequest.GetArticlesCallback() {
#Override
public void onSuccess(String[] listeTitres, String[] listeArticles, boolean fin) {
*Some irrelevant code*
MonAdapter a = (MonAdapter) list.getAdapter();
a.addItems(listeTitres, listeArticles);
list.addFooterView(footerLayout);
list.setAdapter(a);
a.notifyDataSetChanged();
}
nombreCharger++;
}
#Override
public void onError(String error, String id) {
}
});
}
});
}
EDIT :
Here is the error since changes :
04-12 22:47:34.640 12584-12584/com.example.thib.databaseaffichage E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.thib.databaseaffichage, PID: 12584
java.lang.ClassCastException: android.widget.HeaderViewListAdapter cannot be cast to com.example.thib.databaseaffichage.MonAdapter
at com.example.thib.databaseaffichage.MainActivity$2$1.onSuccess(MainActivity.java:142)
at com.example.thib.databaseaffichage.myrequest.MyRequest$1.onResponse(MyRequest.java:63)
at com.example.thib.databaseaffichage.myrequest.MyRequest$1.onResponse(MyRequest.java:39)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:67)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5292)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)

where is the HeaderViewListAdapter in your project?
java.lang.ClassCastException: android.widget.HeaderViewListAdapter cannot be cast to com.example.thib.databaseaffichage.MonAdapter

Related

Why am i getting a nullpointerexception when I try to setAdapter?

I have a simple adapter that uses 2 String based array lists. For some reason I am getting a NullPointerException even though I am sure the information is being passed by.
My adapter:
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.ViewHolder> {
private ArrayList<String> names = new ArrayList<>();
private ArrayList<String> details = new ArrayList<>();
private Context mContext;
public MovieAdapter(ArrayList<String> names, ArrayList<String> details, Context mContext) {
this.names = names;
this.details = details;
this.mContext = mContext;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.detail_view, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.name.setText(names.get(position));
holder.detail.setText(details.get(position));
}
#Override
public int getItemCount() {
return names.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView name;
private TextView detail;
private ConstraintLayout cl;
public ViewHolder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.name);
detail = itemView.findViewById(R.id.detial);
cl = itemView.findViewById(R.id.layout);
}
}
}
My REST call and recylerView initialization activity(added the REST call in case the problem is lying there):
// ArrayList<String> namesArray = new ArrayList<>(Arrays.asList("Rated:", "Released:", "Runtime:", "Genre:", , "Writer:", "Actors:", "Plot:", "Language:", "Country:"));
ArrayList<String> namesArray = new ArrayList<>();
namesArray.add("Rated:");
namesArray.add("Released:");
namesArray.add("Runtime:");
namesArray.add("Genre:");
namesArray.add("Director:");
namesArray.add("Writer:");
namesArray.add("Actors:");
namesArray.add("Plot");
namesArray.add("Language:");
namesArray.add("Country");
trazi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Call<Movie> call;
movieApi = ApiClient.getClient().create(MovieApi.class);
if (paramYear.getText().toString().matches("")) {
call = movieApi.getDetails(key, paramName.getText().toString(), null);
} else {
call = movieApi.getDetails(key, paramName.getText().toString(), Integer.parseInt(paramYear.getText().toString()));
}
call.enqueue(new Callback<Movie>() {
#Override
public void onResponse(Call<Movie> call, Response<Movie> response) {
Toast.makeText(getApplication().getApplicationContext(), " valja", Toast.LENGTH_LONG).show();
movie = response.body();
// ArrayList<String> details = new ArrayList<>(Arrays.asList(movie.getRated(), movie.getReleased(), movie.getRuntime(), movie.getGenre(), movie.getDirector(), movie.getWriter(), movie.getActors(), movie.getPlot(), movie.getLanguage(), movie.getCountry()));
ArrayList<String> details = new ArrayList<>();
details.add(movie.getRated());
details.add(movie.getReleased());
details.add(movie.getRuntime());
details.add(movie.getGenre());
details.add(movie.getDirector());
details.add(movie.getWriter());
details.add(movie.getActors());
details.add(movie.getPlot());
details.add(movie.getLanguage());
details.add(movie.getCountry());
Picasso.get().load(movie.getPoster()).fit().centerInside().into(image);
image.setVisibility(View.VISIBLE);
title.setText(movie.getTitle());
title.setVisibility(View.VISIBLE);
recyclerView = findViewById(R.id.layout);
movieAdapter = new MovieAdapter(namesArray, details, getApplication().getApplicationContext());
recyclerView.setAdapter(movieAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplication().getApplicationContext()));
}
So
Picasso.get().load(movie.getPoster()).fit().centerInside().into(image);
and
title.setText(movie.getTitle());
work perfectly so the information is passed to the adapter and I tried to initialize array lists on two different ways just in case. Still no success. Any ideas on where the problem is?
Edit:
My error log:
2020-05-24 17:20:22.600 27595-27595/com.example.cetvrtizadatak E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.cetvrtizadatak, PID: 27595
java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setAdapter(androidx.recyclerview.widget.RecyclerView$Adapter)' on a null object reference
at com.example.cetvrtizadatak.MainActivity$1$1.onResponse(MainActivity.java:115)
at retrofit2.DefaultCallAdapterFactory$ExecutorCallbackCall$1.lambda$onResponse$0$DefaultCallAdapterFactory$ExecutorCallbackCall$1(DefaultCallAdapterFactory.java:81)
at retrofit2.-$$Lambda$DefaultCallAdapterFactory$ExecutorCallbackCall$1$3wC8FyV4pyjrzrYL5U0mlYiviZw.run(Unknown Source:6)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6702)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:911)
Your NullPointerException is happening when you try to access a member of you recyclerView object, meaning that its value is probably null.
Looking at your code I can presume that the id you're passing is not of yout recyclerView but for an layout object.
Double check if in your layout xml file the id given to the recyclerView is the one you're referencing on you call to findViewById.

Parse.com Error: "This query has an outstanding network connection. You have to wait until it's done."

I am struggling with a very weird Parse (Parse.com) problem:
When I use the usual list.setAdapter(Adapter);, I get the Error: "This query has an outstanding network connection. You have to wait until it's done."
Here is my code:
private ParseQueryAdapter<ParseObject> Adapter;
private CommentListAdapter CommentListAdapter;
Adapter = new ParseQueryAdapter<ParseObject>(this, "Activity");
Adapter.setTextKey("title");
// Initialize the subclass of ParseQueryAdapter
CommentListAdapter = new CommentListAdapter(this);
// Initialize ListView and set initial view to Adapter
CommentList.setAdapter(Adapter);
Adapter.loadObjects();
if (CommentList.getAdapter() == Adapter) {
CommentList.setAdapter(CommentListAdapter);
CommentListAdapter.loadObjects();
}else{
CommentList.setAdapter(Adapter);
Adapter.loadObjects();
}
I get the error at "CommentList.setAdapter(Adapter);"
Here is my Adapter:
public class CommentListAdapter extends ParseQueryAdapter<ParseObject> {
private List<String> itemList;
private Context context;
public ParseImageView thumbnailFile;
public TextView UsernameView;
public TextView Comments;
public CommentListAdapter(Context context) {
// Use the QueryFactory to construct a PQA that will only show
// Todos marked as high-pri
super(context, new ParseQueryAdapter.QueryFactory<ParseObject>() {
public ParseQuery create() {
ParseQuery query = new ParseQuery("Activity");
query.whereEqualTo("photoId", CommentActivity.getPhoto());
query.whereEqualTo("type", "comment");
query.orderByAscending("created_at");
Log.e("Log", "Query: " + query.countInBackground().toString());
return query;
}
});
}
// Customize the layout by overriding getItemView
#Override
public View getItemView(ParseObject object, View v, ViewGroup parent) {
if (v == null) {
v = View.inflate(getContext(), R.layout.comment_list_items, null);
}
super.getItemView(object, v, parent);
Log.e("Log", "Comment: " + object.toString());
thumbnailFile = (ParseImageView) v.findViewById(R.id.user_thumbnail);
UsernameView = (TextView) v.findViewById(R.id.user_name);
Comments = (TextView) v.findViewById(R.id.comment);
String Content = object.toString();
Comments.setText(Content);
return v;
}
}
Please help me, this kind of error should occur in such a case, I don't know what to do..
If you need more of my code, just tell me.

IndexOutOfBoundsException issue with ArrayAdapter Class

I am trying to figure out why am I receiving the following error.
java.lang.IndexOutOfBoundsException: Invalid index 2, size is 2
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.modup.adapter.WorkoutCardsAdapter.getItem(WorkoutCardsAdapter.java:75)
at com.modup.fragment.CreateFragment$1.onPressed(CreateFragment.java:143)
at com.modup.adapter.WorkoutCardsAdapter$1.onClick(WorkoutCardsAdapter.java:62)
at android.view.View.performClick(View.java:4442)
at android.view.View$PerformClick.run(View.java:18473)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5105)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:608)
at dalvik.system.NativeStart.main(Native Method)
I have seen many posts on this topic, but they all seem to have the same answer, and after implementing those answers it seems as if the issue still persists.
My Case:
I have a class that extends ArrayAdapter<>, and this Adapter class is used to populate a ListView inside my fragment. Everything works fine, I can add views, and I can remove views (sort of), I can access the callback implemented.
The Problem:
It seems as if that when I add many views 3-4+ and start to remove them that I will eventually hit this exception.
Specific Cases:
If I start from the top view list item, and go down I don't seem to throw an error, and also I can sometimes go from the bottom up. The error seems to come in if I remove the views out of order (sometimes).
How can I fix this issue? Am I Overriding getCount() and getItem() incorrectly?
UPDATE:
When checking the position of the mCallback.onPress(position); it appears as if the position of the first item in the list is 0, and will remain 0 as long as I don't try to remove any list item below it. Once I remove a list item below it, the first list item will have a completely different position.
public class WorkoutCardsAdapter extends ArrayAdapter {
private LayoutInflater mInflater;
private String[] repArray, setArray, mgArray;
String TAG = WorkoutCardsAdapter.class.getCanonicalName();
Callback mCallback;
List<WorkoutView> mViews;
public WorkoutCardsAdapter(Context context, List<WorkoutView> views, Callback callback) {
super(context, 0, views);
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mCallback = callback;
this.mViews = views;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.single_workout_layout, parent, false);
holder = new ViewHolder();
holder.spinnerReps = (Spinner) convertView.findViewById(R.id.spinnerReps);
holder.spinnerSets = (Spinner) convertView.findViewById(R.id.spinnerSets);
holder.spinnerMuscleGroup = (Spinner) convertView.findViewById(R.id.spinnerWorkoutGroup);
holder.etWorkoutName = (EditText) convertView.findViewById(R.id.etWorkoutName);
holder.btnRemoveWorkout = (Button) convertView.findViewById(R.id.btnRemoveWorkout);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.btnRemoveWorkout.setTag(position);
mgArray = getContext().getResources().getStringArray(R.array.string_array_muscle_groups);
TextSpinnerAdapter adapter = new TextSpinnerAdapter(getContext(), R.layout.spinner_text_item, mgArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.spinnerMuscleGroup.setAdapter(adapter);
setArray = getContext().getResources().getStringArray(R.array.string_array_sets);
TextSpinnerAdapter adapter1 = new TextSpinnerAdapter(getContext(), R.layout.spinner_text_item, setArray);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.spinnerSets.setAdapter(adapter1);
repArray = getContext().getResources().getStringArray(R.array.string_array_reps);
TextSpinnerAdapter adapter2 = new TextSpinnerAdapter(getContext(), R.layout.spinner_text_item, repArray);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.spinnerReps.setAdapter(adapter2);
holder.btnRemoveWorkout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (Integer) v.getTag();
mCallback.onPressed(position);
}
});
return convertView;
}
#Override
public WorkoutView getItem(final int position) {
return mViews.get(position);
}
#Override
public int getCount() {
return mViews.size();
}
public interface Callback {
void onPressed(int pos);
}
private static class ViewHolder {
public Spinner spinnerMuscleGroup;
public Spinner spinnerSets;
public Spinner spinnerReps;
public EditText etWorkoutName;
public Button btnRemoveWorkout;
}
}
Here is the Adapter Implementation w/ Callback
mWorkoutCardsAdapter = new WorkoutCardsAdapter(getActivity(), mArrayList, new WorkoutCardsAdapter.Callback() {
#Override
public void onPressed(int pos) {
mWorkoutCardsAdapter.remove(mWorkoutCardsAdapter.getItem(pos));
mWorkoutCardsAdapter.notifyDataSetChanged();
}
});
In case it will help, this is how I add a new view on button press
workoutView = new WorkoutView(getActivity());
mWorkoutCardsAdapter.add(workoutView);
mWorkoutCardsAdapter.notifyDataSetChanged();
I believe the problem is that you're not caching the correct position with the corresponding Button, so the items being removed are getting mixed up. You can set the Button's tag to the position, and retrieve it from the View passed into the onClick() method, to ensure the right one is removed from the list.
holder.btnRemoveWorkout.setTag(position);
holder.btnRemoveWorkout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (Integer) v.getTag();
mCallback.onPressed(position);
}
});

Android notifyDatasetChange with SQLite cursor how to?

So I have 2 activities.
The first (ActivityOne) displays a listview with data from SQLite cursor, and a button.
On click of that button, I want to add an item to the listview, so I display the second activity (ActivityTwo), that contains a number of editTexts and a save Button, that does the saving in the Database.
But what I want is:
after saving the new item to the DB, the ActivityTwo should close and the ActivityOne should be displayed with the refreshed content from the DB
.
This seems a reasonable workflow. How do I achieve it?
Code for ActivityOne:
public class ActivityOne extends Activity {
private ArrayList<String> idclient = new ArrayList<String>();
private ArrayList<String> numeclient = new ArrayList<String>();
private ArrayList<String> tipclient = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView mylist = (ListView) findViewById(R.id.lv_clienti);
LoadList();
Button btnex = (Button) findViewById(R.id.btnNewCli);
btnex.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View aView)
{
Toast.makeText(getApplicationContext(), "Add new client... " , Toast.LENGTH_SHORT).show();
Intent toAnotherActivity = new Intent(aView.getContext(), NewClientActivity.class);
startActivity(toAnotherActivity);
}
}
);
}
public void LoadList(){
SQLiteDatabase db = new myDbHelper(getApplicationContext()).getWritableDatabase();
Cursor mCursor = db.rawQuery("select idclient,nameclient,typeclient from clienti order by numeclient" , null);
idclient.clear();
numeclient.clear();
tipclient.clear();
if (mCursor.moveToFirst()) {
do {
idclient.add(Integer.toString(mCursor.getInt(0)));
nameclient.add(mCursor.getString(1));
typeclient.add(mCursor.getString(2));
} while (mCursor.moveToNext());
}
DisplayClientiAdapter disadpt = new DisplayClientiAdapter(ClientiActivity.this,idclient,nameclient, typeclient);
ListView lv = (ListView) findViewById(R.id.lv_clienti);
lv.setAdapter(disadpt);
mCursor.close();
db.close();
}
}
And in the ActivityTwo, I have in a button click:
db.execSQL("insert into clients (idclient, nameclient,typeclient,...");
DisplayClientiAdapter da = new DisplayClientiAdapter(getApplicationContext());
da.notifyDataSetChanged();
finish();
Also the displayAdapter is something like:
public class DisplayClientiAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> idclient;
private ArrayList<String> numeclient;
private ArrayList<String> tipclient;
public DisplayClientiAdapter(Context c){
this.mContext = c;
}
public DisplayClientiAdapter(Context c, ArrayList<String> idclient, ArrayList<String> numeclient, ArrayList<String> tipclient) {
this.mContext = c;
this.idclient = idclient;
this.numeclient = numeclient;
this.tipclient = tipclient;
}
public int getCount() {
return idclient.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int pos, View child, ViewGroup parent) {
Holder mHolder;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.clienti_item, null);
mHolder = new Holder();
mHolder.txt_idclient = (TextView) child.findViewById(R.id.tv_cl_id);
mHolder.txt_numeclient = (TextView) child.findViewById(R.id.tv_cl_nume);
mHolder.txt_tipclient = (TextView) child.findViewById(R.id.tv_cl_tip);
child.setTag(mHolder);
} else {
mHolder = (Holder) child.getTag();
}
mHolder.txt_idclient.setText(idclient.get(pos));
mHolder.txt_numeclient.setText(numeclient.get(pos));
mHolder.txt_tipclient.setText(tipclient.get(pos));
return child;
}
public class Holder {
TextView txt_idclient;
TextView txt_numeclient;
TextView txt_tipclient;
}
Of course it does not work like this. The list is not refreshed... I assume it has to do with the displayAdapter !?!?!
I cannot call the LoadList method since it is static or something like that...
Please help.
Thank you
Its not a problem with your adapter. You have to call Loadlist() in onresume method instead of oncreate method in ActivityOne. It will work then.
First of all, have a look at this two articles:
http://www.doubleencore.com/2013/05/layout-inflation-as-intended/
http://www.doubleencore.com/2013/06/context/
You shouldn't inflate your views with null in your inflate method if you have parent view available.
Also, using application context for inflating may cause strange behaviour, as it may not use correct theme you may've set in app manifest for your Activity.
On the other hand - why don't you use CursorAdapter instead of BaseAdapter?
The problem with your adapter is, that you don't set the data in it! :)
///EDIT:
I checked the wrong activity - why do you create second adapter in there?
The easiest solution would be to move the LoadList() to onStart.
If you want to do it right, you should use ContentObserver and (probably) CursorAdapter.

Custom Spinner Crashing

I asked a question on here about a week or so ago about a custom spinner and got led to this guide. http://app-solut.com/blog/2011/03/using-custom-layouts-for-spinner-or-listview-entries-in-android/
I followed it and I've tried adapting it to work with my code and pull the results from a database onto the spinner but it keeps crashing.
This is the code for the spinner.
public class EditTeam extends Activity {
private final List<SpinnerEntry> spinnerContent = new LinkedList<SpinnerEntry>();
private Spinner D1Spinner;
private final ETSpinnerAdapter D1Adapter = new ETSpinnerAdapter(spinnerContent, this);
DataBaseHelper myDbHelper = new DataBaseHelper(this);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editteam);
myDbHelper = new DataBaseHelper(this);
myDbHelper.openDataBase();
fillSpinner();
}
private void fillSpinner() {
Cursor c = myDbHelper.FetchDrivers();
startManagingCursor(c);
// create an array to specify which fields we want to display
String[] from = new String[]{"FirstName", "LastName"};
// create an array of the display item we want to bind our data to
int[] to = new int[]{android.R.id.text1};
spinnerContent.add(new SpinnerEntry(1, null, "Test"));
//adapter.setDropDownViewResource( R.layout.spinner_entry_with_icon );
D1Spinner = (Spinner) findViewById(R.id.spr_Driver1);
D1Spinner.setAdapter((SpinnerAdapter) D1Adapter);
}
}
And I am using the two classes from that contacts example which are un-modified at the moment.
As you can see I'm trying to just manually add one item at the moment but it just crashes when you load it.
This seems to be the breaking point?
05-25 15:17:34.773: E/AndroidRuntime(241): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.f1manager.android/com.f1manager.android.EditTeam}: java.lang.ClassCastException: com.f1manager.android.ETSpinnerAdapter
Any ideas would be great.
Thanks.
ETSpinnerAdapter Code (Unmodified from the original code in the example):
public class ETSpinnerAdapter {
private final List<SpinnerEntry> content;
private final Activity activity;
public ETSpinnerAdapter(List<SpinnerEntry> content, Activity activity) {
super();
this.content = content;
this.activity = activity;
}
public int getCount() {
return content.size();
}
public SpinnerEntry getItem(int position) {
return content.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
final LayoutInflater inflater = activity.getLayoutInflater();
final View spinnerEntry = inflater.inflate(
R.layout.spinner_entry_with_icon, null); // initialize the layout from xml
final TextView contactName = (TextView) spinnerEntry
.findViewById(R.id.spinnerEntryContactName);
final ImageView contactImage = (ImageView) spinnerEntry
.findViewById(R.id.spinnerEntryContactPhoto);
final SpinnerEntry currentEntry = content.get(position);
contactName.setText(currentEntry.getContactName());
//contactImage.setImageBitmap(currentEntry.getContactPhoto());
return spinnerEntry;
}
}
It would seem like your ETSpinnerAdapter is not a SpinnerAdapter as your are getting a class cast exceptin. Maybe you can post your code for the ETSpinnerAdapter?

Categories

Resources