i'm writing an android app that should fetch song data from a parse.com database and display it with a custom Listview.
I tried it the way Nitin suggested but still dont get any listview displayed.
Here is the new code:
package de.android;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.parse.FindCallback;
import com.parse.Parse;
import com.parse.ParseObject;
import com.parse.ParseQuery;
public class Lyrics extends ListActivity {
ImageButton back;
ListView songList;
TextView textAnzeige;
private ArrayList<String> Titelliste = new ArrayList<String>();
private ArrayList<String> Interpretliste = new ArrayList<String>();
private ArrayList<String> Dauerliste = new ArrayList<String>();
ProgressDialog dialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lyrics);
Parse.initialize(this, "hGxasGU6e0WQAOh5JIOGDfvFBKrYyBJKXIzxBfAG", "WsOPsXerpsFjsjekKKbZnnjAHvXy5PQHVQEB8Cqu");
initDataToView();
}
private void initDataToView() {
new getData().execute();
songList = (ListView)findViewById(android.R.id.list);
}
private class getData extends AsyncTask<Void, Void, SongAdapter>{
ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(Lyrics.this);
dialog.setMessage("Please wait, while loading!");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
Log.d("Parse", "PreExecute");
}
#Override
protected SongAdapter doInBackground(Void... params) {
ParseQuery pq = new ParseQuery("SongDatenbank");
pq.whereExists("Titel");
pq.findInBackground(new FindCallback() {
#Override
public void done(List<ParseObject> liederListe,
com.parse.ParseException e) {
if(e==null){
Log.d("Parse", "Objektliste empfangen");
ParseObject x;
for(int i=0;i<liederListe.size();i++){
x = liederListe.get(i);
Titelliste.add(x.getString("Titel"));
Dauerliste.add(x.getString("Dauer"));
Interpretliste.add(x.getString("Interpret"));
}
initDataToView();
x = liederListe.get(0);
Log.d("Parse", x.getString("Titel"));
Log.d("Parse", x.getString("Dauer"));
Log.d("Parse", x.getString("Interpret"));
}else{
Log.d("Parse", "Objektliste nicht empfangen");
}
}
});
return null;
}
protected void onPostExecute(SongAdapter result) {
songList.setAdapter(result);
dialog.dismiss();
Log.d("Parse", "Postexecute");
}
}
public class SongAdapter extends ArrayAdapter<String> {
private final Context context;
private final ArrayList<String> valuesTitel;
private final ArrayList<String> valuesInterpret;
private final ArrayList<String> valuesDauer;
public SongAdapter(Context context, ArrayList<String> valuesTitel, ArrayList<String> valuesInterpret, ArrayList<String> valuesDauer) {
super(context, R.layout.list_row);
this.context = context;
this.valuesTitel = valuesTitel;
this.valuesInterpret = valuesInterpret;
this.valuesDauer = valuesDauer;
}
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_row, parent, false);
ImageView imageView = (ImageView)rowView.findViewById(R.id.list_image);
TextView titelText = (TextView)rowView.findViewById(R.id.title);
TextView artistText = (TextView)rowView.findViewById(R.id.artist);
TextView duration = (TextView)rowView.findViewById(R.id.duration);
titelText.setText(valuesTitel.get(position));
artistText.setText(valuesInterpret.get(position));
duration.setText(valuesDauer.get(position));
Log.d("Parse", valuesTitel.get(position));
return rowView;
}
}}
I think the problem is in parsing the data and give them to the adapter as parameter.
Any idea how to that?
I would really appreciate it if someone could look through my code and help me with solving the problem.
thanks, Paul
I suggest you to make a Handler to update the user interface or use Asynctask
Update UI from Thread
check the link in the first answer it tells about long operation in doInBackground method you should fetch the data and in onPostExecute set the adapter
read the comments in the following code.
private class PrepareAdapter1 extends AsyncTask<Void,Void,ContactsListCursorAdapter > {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(viewContacts.this);
dialog.setMessage(getString(R.string.please_wait_while_loading));
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
/* (non-Javadoc)
* #see android.os.AsyncTask#doInBackground(Params[])
*/
#Override
protected ContactsListCursorAdapter doInBackground(Void... params) {
//do here parsing
return adapter1;
}
protected void onPostExecute(ContactsListCursorAdapter result) {
dialog.dismiss();
//Set Adapter
list.setAdapter(result);
}
}
Check R.layout.list_row. that is properly designed or not. i.e the layout is having the height and width as fill_parent. because from your code everything looks fine.
there is no getCount method in the Adapter class , try the following code
#Override
public int getCount()
{
return x.size();// number of datas in the list .
}
this method specifies the number of times the getView to be populated automatically .
............ One more suggession is that use extend BaseAdapter instead of ArrayAdapter<String>
Related
When I try to use setListAdapter to show my data this happens:
Cannot resolve method setListAdapter
This is my Activity:
package id.sch.smktelkom.www.crud;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.List;
public class CollectionActivity extends AppCompatActivity implements
FetchCollectListener {
String[] daftar;
ListView listView;
protected Cursor cursor;
Button search;
private ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_collection);
Button btn=(Button)findViewById(R.id.button2);
search = (Button) findViewById(R.id.cari);
initView();
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent inte = new Intent(CollectionActivity.this, MainActivity.class);
startActivity(inte);
}
});
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent c = new Intent(CollectionActivity.this, SearchV.class);
startActivity(c);
}
});
}
private void initView() {
// show progress dialog
dialog = ProgressDialog.show(CollectionActivity.this, "", "Loading...");
String url = "http://192.168.4.5/SqliteSync/readC.php";
FetchCollection task = new FetchCollection(this);
task.execute(url);
}
#Override
public void onFetchComplete(List<Collect> data) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
// create new adapter
CollectAdapter adapter = new CollectAdapter(this, data);
// set the adapter to list
setListAdapter(adapter);
}
#Override
public void onFetchFailure(String msg) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
// show failure message
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
}
And this is my Adapter:
package id.sch.smktelkom.www.crud;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.TextView;
import java.util.List;
public class CollectAdapter extends ArrayAdapter<Collect> {
private List<Collect> items;
private Context mContext;
public CollectAdapter(Context context, List<Collect> items) {
super(context, R.layout.item_collect, items);
this.items = items;
mContext = context;
}
#Override
public int getCount() {
return items.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null) {
LayoutInflater li = LayoutInflater.from(getContext());
v = li.inflate(R.layout.item_collect, null);
}
Collect app = items.get(position);
if(app != null) {
TextView id = (TextView) v.findViewById(R.id.txtpeminjam);
TextView name = (TextView) v.findViewById(R.id.txtpinjaman);
ImageButton btn = (ImageButton) v.findViewById(R.id.list_image);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent b = new Intent(mContext,LihatDataActivity.class);
mContext.startActivity(b);
}
});
if(id != null) id.setText(app.getNama());
if(name != null) name.setText(app.getPinjaman());
}
return v;
}
}
I don't know what's wrong with this and it's annoying me already.
I want to retrieve data from MySQL to my Android app and when I type setListAdapter suddenly it becomes red and shows some error.
Appreciate any help.
Instead of setListAdapter(adapter); call listView.setAdapter(adapter);
setListAdapter works for activities extending ListActivity
I see also that you should add in onCreate this:
ListView listView=(ListView)findViewById(R.id.listView);
if the name of the ListView is listView in xml
So after some advice from #AmitVikramSingh
I'm referencing my listview
public class CollectionActivity extends AppCompatActivity implements FetchCollectListener {
String[] daftar;
ListView listView;
protected Cursor cursor;
Button search;
private ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_collection);
Button btn=(Button)findViewById(R.id.button2);
search = (Button) findViewById(R.id.cari);
listView = findViewById(R.id.list);
And I change this from
#Override
public void onFetchComplete(List<Collect> data) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
// create new adapter
CollectAdapter adapter = new CollectAdapter(this, data);
// set the adapter to list
setListAdapter(adapter);
}
To this
#Override
public void onFetchComplete(List<Collect> data) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
// create new adapter
CollectAdapter adapter = new CollectAdapter(this, data);
// set the adapter to list
listView.setAdapter(adapter);
}
Big thanks to all who help me solving this problem
Good afternoon,
I'm still a beginner in programming, currently learning Android.
I am making a screen that captures some information from a website and moves to a list view. The code below works when I use only the main page of the site, when I try to move to page 2 instead of adding to the end of the Array, it overwrites the entire Array.
I have reached the limit of my knowledge, I can kick it a silly mistake in how they are built, but I could not reach the solution alone.
I'm sorry if I have any typos, I'm using a translator.
package br.com.testejsoup.eu.testejsoup;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private ListView conteudo;
String[] aniNomes;
String[] aniLinks;
ArrayAdapter<String> adaptador;
Document doc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
conteudo = findViewById(R.id.html_conteudo);
new doit().execute();
conteudo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int posicao = position;
Intent intent = new Intent(MainActivity.this, Episodio.class);
intent.putExtra("aniLinks", aniLinks[posicao]);
//Toast.makeText(getApplicationContext(), aniLinks[posicao], Toast.LENGTH_LONG).show();
startActivity(intent);
}
});
}
public class doit extends AsyncTask<Void, Void, Void>{
String URL = "http://www.URL.com/lancamentos?page=";
String nomeExp;
Elements nome;
Elements links;
int paginas = 5;
#Override
protected Void doInBackground(Void... voids) {
try {
for (int i=1; i<= paginas;i++) {
String new_URL = URL + i;
doc = Jsoup.connect(new_URL).get();
nome = doc.select("div.nome-thumb a.tt");
links = doc.select("div.nome-thumb a.tt");
aniNomes = new String[nome.size()];
aniLinks = new String[links.size()];
for(Element nomeTemp : nome){
nomeExp = nomeTemp.text();
adaptador.add(nomeExp);
}
}
for (int i = 0; i < nome.size(); i++) {
aniNomes[i] = nome.get(i).text();
}
for (int i = 0; i < links.size(); i++) {
aniLinks[i] = links.get(i).attr("abs:HREF");
}
adaptador = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, android.R.id.text1, aniNomes);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
conteudo.setAdapter(adaptador);
}
}
}
New code after the proposed modification.
THANKS FOR THE HELP!!!
package br.com.testejsoup.eu.testejsoup;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private ListView conteudo;
ArrayList<String> aniNomes = new ArrayList<>();
ArrayList<String> aniLinks = new ArrayList<>();
ArrayAdapter<String> adaptador;
Document doc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
conteudo = findViewById(R.id.html_conteudo);
new doit().execute();
conteudo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int posicao = position;
Intent intent = new Intent(MainActivity.this, Episodio.class);
intent.putExtra("aniLinks", aniLinks.get(position));
//Toast.makeText(getApplicationContext(), aniLinks[posicao], Toast.LENGTH_LONG).show();
startActivity(intent);
}
});
}
public class doit extends AsyncTask<Void, Void, Void>{
String URL = "http://www.URL.com/lancamentos?page=";
String nomeExp;
Elements nome;
Elements links;
int paginas = 5;
#Override
protected Void doInBackground(Void... voids) {
try {
for (int i=1; i<= paginas;i++) {
String new_URL = URL + i;
doc = Jsoup.connect(new_URL).get();
nome = doc.select("div.nome-thumb a.tt");
links = doc.select("div.nome-thumb a.tt");
for (Element nomeT : nome){
aniNomes.add(nomeT.text());
}
for (Element linkT : links){
aniLinks.add(linkT.attr("abs:HREF"));
}
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
adaptador = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, android.R.id.text1, aniNomes);
conteudo.setAdapter(adaptador);
}
}
}
Its because you're creating a new adapter in your asynctask and then in your onPostExecute method you're calling setAdapter which swaps out the old adapter and its entries with the new adapter and its new entries.
Rather than creating a new adapter in your asynctask I would just create an array/arraylist, add the new entries to it and then in your onPostExecute just append the entries from this array/list into the one and only adapter entry set.
I am using google book API to search a book with the title.It shows me the result for the first time. The next I search it clears the ListView but not showing the new search result.
There is a peculiar error. When I search a book it shows me 3 to 4 books whereas I have set MaxResult to 10. When I manually call the API in the browser I get 10 results.
Here is the code I am using.
public class MainActivity extends AppCompatActivity implements LoaderCallbacks<List<Book>>{
private static final int BOOK_ID = 1;
public static final String LOG_TAG = MainActivity.class.getName();
private static String book_url;
private BookAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bt=(Button)findViewById(R.id.search);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText searchTerm=(EditText)findViewById(R.id.search_book);
String search=searchTerm.getText().toString();
book_url="https://www.googleapis.com/books/v1/volumes?q="+search+"&maxResults=10";
LoaderManager loaderManager = getLoaderManager();
loaderManager.initLoader(BOOK_ID, null, MainActivity.this);
mAdapter=new BookAdapter(MainActivity.this,new ArrayList<Book>());
ListView bookListView=(ListView)findViewById(R.id.list);
mAdapter.notifyDataSetChanged();
bookListView.setAdapter(mAdapter);
}
});
}
public Loader<List<Book>> onCreateLoader(int i,Bundle bundle){
return new BookLoader(this,book_url);
}
public void onLoadFinished(Loader<List<Book>> loader,List<Book> books){
mAdapter.clear();
if(books!=null&&!books.isEmpty()){
mAdapter.addAll(books);
}
}
public void onLoaderReset(Loader<List<Book>> loader){
mAdapter.clear();
}
}
I tried notifyDataSetChanged(). But it doesn't work.
Here is the code for custom adapter
package com.example.android.booksearch;
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 java.util.List;
/**
* Created by AKSPAN12 on 19-07-2017.
*/
public class BookAdapter extends ArrayAdapter<Book> {
public BookAdapter(Context context, List<Book> books) {
super(context, 0,books);
}
public View getView(int position, View convertView, ViewGroup parent){
View listItemView=convertView;
if(listItemView==null){
listItemView= LayoutInflater.from(getContext()).inflate(R.layout.book_list,parent,false);
}
Book currentBook=getItem(position);
String author=currentBook.getAuthor();
TextView authorView=(TextView)listItemView.findViewById(R.id.book_author);
authorView.setText(author);
String bookName=currentBook.getBook();
TextView bookView=(TextView)listItemView.findViewById(R.id.book_name);
bookView.setText(bookName);
return listItemView;
}
}
It shows me the result for the first time. The next I search it clears the ListView but not showing the new search result.
You probably need to restart your loader.
I started to develop Android recently and I'm having difficulty in solving a thing probably much simpler than what I think.
I am creating a CRUD application that communicates with an online database, I can read and enter data, unfortunately I can't delete and modify the list once it is created.
To manage the data that use JSON and the row in the list that I add is made up of three fields: animal_id, animal_name, animal_type.
The activity data on which I read and on which I want to implement methods to modify and delete via listener is formed by the following code:
import java.sql.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class ListAnimalActivity extends ListActivity {
ArrayList<HashMap<String,?>> animalList;
JSONParser jParser = new JSONParser();
JSONArray animals = null;
Button button_add;
private static String url_read = "http://example.com/list_animals.php";
private static String url_delete = "http://example.com/delete_animal.php";
private static final String TAG_SUCCESS = "success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
load_ListAnimalActivity();
}
public void onResume(){
super.onResume();
load_ListAnimalActivity();
}
private void load_ListAnimalActivity(){
setContentView(R.layout.activity_list_animal);
animalList = new ArrayList<HashMap<String,?>>();
new Read_Object().execute();
final ListView listView = (ListView)findViewById(android.R.id.list);
final ListAdapter adapter = new SimpleAdapter(
ListAnimalActivity.this, animalList,
R.layout.row_list, new String[] { "animal_id",
"animal_name","animal_type"},
new int[] { R.id.animal_id, R.id.animal_name,R.id.animal_type });
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
AlertDialog.Builder adb = new AlertDialog.Builder(ListAnimalActivity.this);
adb.setTitle("Attenzione!");
adb.setMessage("Vuoi eliminare l\'elemento \"" + animalList.get(position)+ "\" ?");
final int posizione = position;
adb.setNegativeButton("Annulla",new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {}
});
adb.setPositiveButton("Elimina", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
new Delete_Object().execute();
}
});
adb.show();
}
});
button_add = (Button)findViewById(R.id.button_add);
button_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(ListAnimalActivity.this,CRUDAnimalActivity.class));
}
});
}
class Read_Object extends AsyncTask<String, String, String> {
private ProgressDialog progressMessage = new ProgressDialog(ListAnimalActivity.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
progressMessage.setMessage("Loading ...");
progressMessage.setIndeterminate(false);
progressMessage.setCancelable(false);
progressMessage.show();
}
protected String doInBackground(String... args) {
List params = new ArrayList();
JSONObject json = jParser.makeHttpRequest(url_read, "POST", params);
try{
Log.d("Animals: ", json.toString());
} catch (NullPointerException e){
e.printStackTrace();
}
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
animals = json.getJSONArray("animals");
for (int i = 0; i < animals.length(); i++) {
JSONObject c = animals.getJSONObject(i);
String id = c.getString("animal_id");
String name = c.getString("animal_name");
String type = c.getString("animal_type");
HashMap map = new HashMap();
map.put("animal_id", id);
map.put("animal_name", name);
map.put("animal_type", type);
animalList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (NullPointerException e){
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
progressMessage.dismiss();
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
ListAnimalActivity.this, animalList,
R.layout.row_list, new String[] { "animal_id",
"animal_name","animal_type"},
new int[] { R.id.animal_id, R.id.animal_name,R.id.animal_type });
setListAdapter(adapter);
}
});
}
}
class Delete_Object extends AsyncTask<String, String, String>{
private ProgressDialog progressMessage = new ProgressDialog(ListAnimalActivity.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
progressMessage.setMessage("Deleting ...");
progressMessage.setIndeterminate(false);
progressMessage.setCancelable(false);
progressMessage.show();
}
protected String doInBackground(String... args) {
/*
Code to delete
*/
return null;
}
protected void onPostExecute(String file_url){
}
}
}
When i click on a list Item, the listener show me the object in this format:
{animal_type=firstType, animal_name=firstName, animal_id=1}
So my question is:
How can I collect only animal_id from the array animalList > ?
Your animalList is an array list with HashMaps as its elements, so when you call animalList.get(position), it will return a HashMap. To retrieve an animal_id just use :
(animalList.get(position)).get(animal_id).toString();
you have to create a Modelclass/Pojo Class (Private variable and getters and setters) for Animals,
ArrayList<AnimalModel> animalsArrayList = new ArrayList<AnimalModel>();
add the Animals object/data to animalsArrayList and listview.setAdapter(animalsArrayList);
then
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Object object = speakerListView.getItemAtPosition(position);
AnimalModel animals_data = (AnimalModel) object;
id = animals_data.getAnimal_id()
// call delete Async with thid Id
}
});
You code looks pretty messy. If I were you I would create a Custom Adapter that extends the base adapter and takes as a parameter either a hashmap or a list that you pass in the constructor. There you can have different listeners. Also if you want to notify the activity you can have the "luxury" to pass an interface as a parameter and notify the activity when something changes.
Regarding the json part, I would create two new classes, one which is a Thread Manager that receives tasks and handles them further and another class where u make the http calls and the json parsing.
I have done a similar application that receives data from a nebula interface and displays them to the user.
I know this question has been asked several times, but the solutions have been specific to the askers' problems. Consequently, none of those solutions helped me, even though I tried following all of their suggestions.
So here goes.
I have a movies Activity like this. Notice that I have a MoviesAdapter inner class, that's supposed to populate the moviesDisplay ListView.
package com.example.midtermexam;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.database.DataSetObserver;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class MoviesActivity extends Activity {
public String url;
public ListView moviesDisplay;
public static ArrayList<Movie> thisMovies;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movies);
url=getIntent().getExtras().getString("url");
moviesDisplay = (ListView)findViewById(R.id.listView1);
new AsyncMoviesGet(this).execute(url);
}
public void populateListView()
{
Log.d("listview","adapter created");
Log.d("listview","Listview declared");
Log.d("listview","adapter populated");
moviesDisplay.setAdapter(new MoviesListAdapter());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.movies, menu);
return true;
}
private class MoviesListAdapter extends ArrayAdapter<Movie> {
public MoviesListAdapter() {
super(MoviesActivity.this, R.layout.movies_activity_listview, thisMovies);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Make sure we have a view to work with (may have been given null)
View movieView = convertView;
if (movieView == null) {
movieView = getLayoutInflater().inflate(R.layout.movies_activity_listview, parent, false);
}
// Find the car to work with.
return movieView;
}
}
}
The populateListView() method is called from an AsyncTask called AsyncMoviesGet, whose postExecute() looks like this.
#Override
protected void onPostExecute(ArrayList<Movie> result) {
if(result != null){
m.thisMovies = result;
m.populateListView();
Log.d("demo", result.toString());
} else{
Log.d("demo", "null result");
}
}
You can see the Log messages inside the populateListView() method. These 3 statements get executed. However, the setAdapter() function doesn't seem to call the "GetView" function.
Add stuff to ArrayAdapter at least, use mAdapter.addAll():
private MoviesListAdapter mAdapter;
. . . . . .
#Override
protected void onCreate(Bundle savedInstanceState) {
. . . . .
mAdapter = new MoviesListAdapter();
moviesDisplay.setAdapter(mAdapter);
}
. . . . .
protected void onPostExecute(ArrayList<Movie> result) {
if(result != null){
m.thisMovies = result;
mAdapter.clear();
mAdapter.addAll(result);
mAdapter.notifyDatasetInvalidated();
Log.d("demo", result.toString());
} else{
Log.d("demo", "null result");
}
}
You have to add a constructor to your Custom Adapter class, one that takes a context, resource id & a data structure containing the items you'd like to display, in this case your thisMovies.
public MoviesListAdapter(Context context, int resourceId,
ArrayList<String> viewItems)
{
super(context, resourceId, viewItems);
}
Then you have to construct your adapter based on the results you've received in your onPostExecute(). Before this is done, create an instance variable in the activity which will be used to store the adapter.
MoviesListAdapter mMovieAdapter = null;
Afterwards, construct it by changing this
moviesDisplay.setAdapter(new MoviesListAdapter());
to something like below
if(thisMovies != null && thisMovies.size() > 0) {
mMovieAdapter = new MoviesListAdapter(getApplicationContext(), R.layout.movies_activity_listview, thisMovies);
moviesDisplay.setAdapter(mMovieAdapter);
} else {
Log.w("MyApplication","onPostExecute() did not return any items!");
}
You should initialise and call adapter by this way..........this is just an e.g. you need to modify it according to your controls:
ListView lv = (ListView) v.findViewById(R.id.listview1);
ListViewAdapter adapter = new ListViewAdapter(container.getContext(),
android.R.layout.simple_list_item_1, R.id.textview1);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
And inside the custom adapter class, its constructor should also have these kind of parameters:
public ListViewAdapter(Context context,int resource, int textViewResourceId, List<YourObjectType> items) {
super(context,resource,textViewResourceId, items);
this.context1 = context;
// TODO Auto-generated constructor stub
}