so I currently have a list of returned JSON objects as a ListView on my application, and I'm trying to make it so that I can click the object and then edit the details, however I'm at a bit of a loss as to why my setOnItemClickListener isn't working, code below
package mmu.tom.linkedviewproject;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
private ListView GetAllDevicesListView;
private JSONArray jsonArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.GetAllDevicesListView = (ListView) this.findViewById(R.id.GetAllDevicesListView);
new GetAllDevicesTask().execute(new ApiConnector());
GetAllDevicesTask.setOnItemClickListener (new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
try
{
//GetDevice that was clicked
JSONObject deviceClicked = jsonArray.getJSONObject(position);
//Send DeviceId
Intent showDetails = new Intent(getApplicationContext(), DeviceDetailsActivity.class);
showDetails.putExtra("deviceID", deviceClicked.getString("deviceID"));
}
catch(
JSONException e
)
{
e.printStackTrace();
}
}
});
}
public void setListAdapter(JSONArray jsonArray){
this.jsonArray = jsonArray;
this.GetAllDevicesListView.setAdapter((new GetAllDeviceListViewAdapter(jsonArray,this)));
}
private class GetAllDevicesTask extends AsyncTask<ApiConnector,Long,JSONArray>
{
#Override
protected JSONArray doInBackground(ApiConnector... params) {
// it is executed on Background thread
return params[0].GetAllDevicesState();
}
#Override
protected void onPostExecute(JSONArray jsonArray) {
setListAdapter(jsonArray);
}
}
}
You are not taking List view object.
Change to this.
GetAllDevicesListView.setOnItemClickListener (new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
try
{
//GetDevice that was clicked
JSONObject deviceClicked = jsonArray.getJSONObject(position);
//Send DeviceId
Intent showDetails = new Intent(getApplicationContext(), DeviceDetailsActivity.class);
showDetails.putExtra("deviceID", deviceClicked.getString("deviceID"));
}
catch(
JSONException e
)
{
e.printStackTrace();
}
}
});
You are not setting the setOnItemClickListener on a ListView but on a class name.
Change
GetAllDevicesTask.setOnItemClickListener (new AdapterView.OnItemClickListener() {
to
GetAllDevicesListView.setOnItemClickListener (new AdapterView.OnItemClickListener() {
Related
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 learning about android swipe refresh layout. I post runabble on swipeRefreshLayout "setRefreshing(true)", then on method onRefresh i wrote fetchMovie(). But fetchMovie() didn't called. How to fix it?
package com.example.zihadrizkyef.belajarswiperefresh;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.example.zihadrizkyef.belajarswiperefresh.app.MyApplication;
import com.example.zihadrizkyef.belajarswiperefresh.helper.Movie;
import com.example.zihadrizkyef.belajarswiperefresh.helper.SwipeListAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
private String TAG = MainActivity.class.getSimpleName();
private String URL_TOP_250 = "http://api.androidhive.info/json/imdb_top_250.php?offset=";
private SwipeRefreshLayout swipeRefreshLayout;
private ListView listView;
private SwipeListAdapter adapter;
private List<Movie> movieList;
private int offSet = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
movieList = new ArrayList<Movie>();
adapter = new SwipeListAdapter(this, movieList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, "aaaaaaaaaa", Toast.LENGTH_SHORT).show();
}
});
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
}
});
}
#Override
public void onRefresh() {
fetchMovie();
}
private void fetchMovie() {
swipeRefreshLayout.setRefreshing(true);
String url = URL_TOP_250+offSet;
JsonArrayRequest req = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
System.out.println(TAG+response.toString());
if (response.length() > 0) {
for (int i=0; i<=response.length(); i++) {
try {
JSONObject movieObject = response.getJSONObject(i);
int rank = movieObject.getInt("rank");
String title = movieObject.getString("title");
Movie movie = new Movie(rank, title);
movieList.add(0, movie);
if (rank > offSet) {
offSet = rank;
}
} catch (JSONException e) {
System.out.println(TAG + " : JSON Parsing error : "+e.getMessage());
}
}
adapter.notifyDataSetChanged();
}
swipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(TAG+" : Server error : "+error.getMessage());
Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
swipeRefreshLayout.setRefreshing(false);
}
});
MyApplication.getInstance().addToRequestQueue(req);
}
}
As seen in the documentation about the SwipeRefreshLayout:
If an activity wishes to show just the progress animation, it should call setRefreshing(true).
Calling setRefreshing() will not call the OnRefreshListener. You can call fetchMovie() just after it though :
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
fetchMovie();
}
});
Related doc : https://developer.android.com/reference/android/support/v4/widget/SwipeRefreshLayout.html
I have a following problem. I build a listView that then uses custom laytout item_event which displays certain data. This all works. Now I want to make the app allow me to move to new activity everytime I click on one of the elements in the listView. My MainMenu extends ListActivity so I can use setListAdapter. How can I now use the setOnItemClickListener? I tried to create ListView object and then refer to it, but I cannot access it due to its android:id="#android:id/list"/>. How to do it?
package com.mysampleapp;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.app.ListActivity;
import com.userpreferencesom.AmazonClientManager;
import com.userpreferencesom.DynamoDBManager;
import java.util.ArrayList;
public class MainMenu extends ListActivity {
//ListView eventsList;
Button newEvent;
Event event= new Event();
//ArrayList<Event> eventList = new ArrayList();
public static AmazonClientManager clientManager = null;
private ArrayAdapter<String> arrayAdapter = null;
private ArrayList<String> labels = null; // list of names of events manly for test)
private ArrayList<Event> items = null; //stores events
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
clientManager = new AmazonClientManager(this); //CIPEK
new GetEventList().execute(); //calling GetEventList from included class below
newEvent = (Button) findViewById(R.id.new_event_button);
newEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainMenu.this, EventCreationActivity.class);
startActivity(intent);
}
});
}
private void setupActivity() {
Log.v("MOJEMOJEMOJE", event.getName());
}
private class GetEvent extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... voids) {
event = DynamoDBManager.getEvent(""); //in bracket ID number
return null;
}
protected void onPostExecute(Void result) {
setupActivity();
}
}
private class GetEventList extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... inputs) {
labels = new ArrayList<String>();
items = DynamoDBManager.getEventList();
for (Event up : items) {
labels.add(up.getName());
}
return null;
}
protected void onPostExecute(Void result) {
Log.v("Events:", labels.toString());
updateDisplay();
}
}
public void updateDisplay(){
//Using Event Adapter to display data
EventAdapter adapter = new EventAdapter(this, R.layout.item_event, items);
setListAdapter(adapter);
setOnItemClickListener(new AdapterView.OnItemClickListener() { //HERE IT CANNOT BUILD
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainMenu.this, EventViewActivity.class);
startActivity(intent);
}
});
}
}
Thank you in advance,
John
Here is the error log:
C:\Users\John\Desktop\trial\cos1\HangApp-0.5\app\src\main\java\com\mysampleapp\MainMenu.java
Error:(110, 9) error: cannot find symbol method setOnItemClickListener(<anonymous OnItemClickListener>)
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
:app:compileDebugJavaWithJavac FAILED
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
You can Override onListItemClick for handle event when you click in each item of your ListView
public class MainMenu extends ListActivity
...
...
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Toast.makeText(this, "click at " + position,Toast.LENGTH_LONG).show();
}
}
What I am are trying to do is:-
To show states in spinner load it from database and fill the spinner. on selection state, depending on state, the city must be filled in another spinner.
What I achieved is:
Spinner get filled with the values from database, but the setOnItemSelectedListener is not working.
setOnItemSelectedListener method works when I put data statically in the spinner.
My Source:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
public class MainActivity extends Activity {
Spinner sp_state,sp_city,sp_area;
Button ok;
int state_position;
String s_data,c_data,a_data,selected_state;
ArrayList<Satae_Pojo> new_data;
Network_Class net=new Network_Class();
ArrayList<Satae_Pojo> state=new ArrayList<Satae_Pojo>();
ArrayList<Integer> state_id=new ArrayList<Integer>();
ArrayList<String> state_name=new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.search_for_area);
sp_state=(Spinner)findViewById(R.id.spinner_state);
sp_city=(Spinner)findViewById(R.id.spinner_city);
sp_area=(Spinner)findViewById(R.id.spinner_area);
ok=(Button)findViewById(R.id.btn_ok);
List<String> list=new ArrayList<String>();
list.add("Please Select Area");
list.add("Phulewadi");
list.add("Vikramnagar");
list.add("Kadamwadi");
list.add("Rajarampuri");
getStates();
sp_state.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View arg1, int pos, long arg3)
{
System.out.println("This is spinner");
//String id=parent.getItemAtPosition(pos).toString();
//System.out.println("This is selected id "+id);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {}
});
ArrayAdapter<String> state_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, state_name);
state_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp_state.setAdapter(state_adapter);
}
public void getStates()
{
new Thread(new Runnable()
{
#Override
public void run()
{
s_data=net.getState();
ArrayList<Satae_Pojo> statedata = statepojo(s_data);
Iterator<Satae_Pojo> itr = statedata.iterator();
while(itr.hasNext())
{
Satae_Pojo s_pojo=(Satae_Pojo)itr.next();
int id=(Integer)s_pojo.getId();
String name=(String)s_pojo.getState();
state_id.add(id);
state_name.add(name);
}
}
}).start();
}
public ArrayList<Satae_Pojo> statepojo(String result)
{
ArrayList<Satae_Pojo> states=new ArrayList<Satae_Pojo>();
try
{
JSONArray jsonarray = new JSONArray(result);
for(int i=0; i<jsonarray.length(); i++)
{
JSONObject jsonobject=jsonarray.getJSONObject(i);
Satae_Pojo statepojo=new Satae_Pojo();
statepojo.setId(jsonobject.getInt("id"));
statepojo.setState(jsonobject.getString("s_name"));
states.add(statepojo);
}
}
catch(JSONException e)
{
Log.e("Log_tag", "Error Parsing in State....."+e.toString());
Log.e("Log_Answers","Second Error Parsing in State....."+result);
}
return states;
}
#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;
}
}
In above source when I pass "list" as argument to adapter it works fine.
but when dynamically filled state_name is passed setOnItemSelectedListener do not work.. what I am doing wrong..?
Whenever you are adding data (dynamically) to adapter you need to call Adapter.notifyDataSetChanged() so that the view will refresh it self.
add this code after while loop of getStates() method
runOnUiThread(new Runnable() {
#Override
public void run() {
state_adapter.notifyDataSetChanged();
}
});
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.