my asynctask is not working. The dialog wont dismiss and the list is not being updated (i think because onPostExecute is not being called).I googled it, but without result.
package com.example.whs;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class Albums extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
// Array for the list
ArrayList<HashMap<String, String>> itemList;
// url to get the items
private static String url_all_products = "<my url here>";
// JSON variables
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private static final String TAG_ITEMS = "items";
private static final String TAG_NAME = "name";
private static final String TAG_ID = "id";
private static final String TAG_USERNAME = "username";
//JSON array
JSONArray items = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_albums);
// HashMap for the items
itemList = new ArrayList<HashMap<String, String>>();
// Loading the items on the background
new LoadAllItems().execute();
// Get list-view
ListView lv = getListView();
// On item click
lv.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
//do
}
});
}
// class for loading all items
class LoadAllItems extends AsyncTask<String, String, String> {
// Before
#Override
protected void onPreExecute(){
super.onPreExecute();
pDialog = new ProgressDialog(Albums.this);
pDialog.setMessage("Albums laden...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
// Get the products
#Override
protected String doInBackground(String... params) {
// Build Parameters
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
//Get the JSON string
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params1);
// Check for response
Log.d("All Items: ", json.toString());
try {
// check for success tag
int success = json.getInt(TAG_SUCCESS);
if(success == 1) {
// found the items
items = json.getJSONArray(TAG_ITEMS);
// loop through the items
for (int i = 0; items.length() > i; i++){
// Get the item in variable c
JSONObject c = items.getJSONObject(i);
// Store in a variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String username = c.getString(TAG_USERNAME);
if(username == ""){
username = "onbekend";
}
// Create the HashMap
HashMap<String, String> map = new HashMap<String, String>();
// add it
map.put(TAG_ID, id);
map.put(TAG_USERNAME, username);
map.put(TAG_NAME, name);
// to arraylist
itemList.add(map);
}
}else{
// nothing found
Intent i = new Intent(getApplicationContext(), Index.class);
// close the previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e){
e.printStackTrace();
}
return null;
}
}
protected void onPostExecute(String result){
// dismiss dialog
pDialog.dismiss();
runOnUiThread(new Runnable(){
public void run(){
// Add adapter to the list
MenuAdapter adapter = new MenuAdapter(Albums.this, itemList);
ListView list = (ListView)findViewById(R.id.list);
list.setAdapter(adapter);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.albums, menu);
return true;
}
}
the loop is working correctly.
How to fix this?
1) you are trying to start an activity within the background thread, don't do this.
2) you are probably getting a json exception, just log more things so you can see what is happening
these may be why it never reaches onPostExecute
you can not perform UI related action in doInBackGround(), like you are strating a new activity in doInBaclground,
Intent i = new Intent(getApplicationContext(), Index.class);
// close the previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
Related
I understand that we cannot set ImageView in AsyncTask. But I need to add the ImageView into HashMap and the HashMap need to add into an ArrayList inside the for loop. I cannot do that in onPostExecute(). Does anyone know how to do?
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class AllProductsActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://192.168.1.132/retEqp.php";
ImageView iv;
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "equipments";
private static final String TAG_PID = "item_ID";
private static final String TAG_NAME = "item_Name";
private static final String TAG_DESC = "item_Desc";
private static final String TAG_LOC = "item_Location";
private static final String TAG_STATUS = "item_Status";
private static final String TAG_IMAGE = "item_Image";
// products JSONArray
JSONArray equipments = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
iv = (ImageView)findViewById(R.id.img2);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent previousScreen = new Intent(getApplicationContext(), NewProductActivity.class);
//Sending the data to NewProductActivity
previousScreen.putExtra("id",pid);
setResult(1000, previousScreen);
finish();
// starting new activity and expecting some response back
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllProductsActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
// Log.d("All Products: ", json.toString());
try {
equipments = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < equipments.length(); i++) {
JSONObject c = equipments.getJSONObject(i);
// Storing each json item in variable
String id = "ID: "+c.getString(TAG_PID);
String name = "Name: "+c.getString(TAG_NAME);
String desc = "Description: "+c.getString(TAG_DESC);
String loc = "Location: "+c.getString(TAG_LOC);
String status = "Status: "+c.getString(TAG_STATUS);
String image = c.getString(TAG_IMAGE);
byte[] rawImage = Base64.decode(image, Base64.DEFAULT);
Bitmap bmp12 = BitmapFactory.decodeByteArray(rawImage, 0, rawImage.length);
iv.setImageBitmap(bmp12);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
// map.put(TAG_IMAGE, rawImage.length);
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
map.put(TAG_DESC, desc);
map.put(TAG_LOC, loc);
map.put(TAG_STATUS, status);
map.put(TAG_IMAGE, iv.toString());
// adding HashList to ArrayList
productsList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllProductsActivity.this, productsList,
R.layout.list_item, new String[] { TAG_IMAGE,TAG_PID,
TAG_NAME,TAG_DESC,TAG_LOC,TAG_STATUS},
new int[] {R.id.img,R.id.pid, R.id.name,R.id.desc,R.id.loc,R.id.status});
// updating listview
setListAdapter(adapter);
}
});
}
}
}
You can't access the UI in a background thread.
The idea behind AsyncTask is that doInBackground does the background work, then you can return something that will be passed as a parameter to onPostExecute which is executed in the main thread.
In this case you have to return the parsed model objects from doInBackground (I would create a custom class), receive in onPostExecute. Also, create a custom adapter, which will take care of creating views. You should generate bitmaps there (probably you have to put the parsing to bitmap in another async task).
I am working trying to solve an issue on an activity, but I am not able to find the reason for the behaviour.
I have a list view activity (Activity A), if the app user taps on a list row, a second list view activity (Activity B) is shown and all expected list objects are on the list.
Then, if the user navigates from activity B back to activity A, and selects the same or another row, then activity B is shown again, but none object is shown on the list.
I was told by another SO user to include a onResume method. I have done it, but the issue is not solved.
Here you have the activity B code:
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
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.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class ofertas_list extends ListActivity {
private ProgressDialog pDialog;
// JSON node keys
private static final String TAG_NAME = "nombreCategoria";
private static final String TAG_ID = "idCategoria";
private static final String TAG_CATEGORIAS = "Categorias";
// URL to get contacts JSON
private static String url = "http://xxxxx/android_ofertaslist.php?id=";
// JSON Node names
private static final String TAG_NOMBREEMPRESA = "nombreEmpresa";
private static final String TAG_IDEMPRESA = "idEmpresa";
private static final String TAG_DESCRIPCIONEMPRESA = "descripcionEmpresa";
private static final String TAG_STRIMAGEN = "strImagen";
private static final String TAG_DIRECCIONEMPRESA = "direccionEmpresa";
private static final String TAG_TELEFONOEMPRESA = "telefonoEmpresa";
private static final String TAG_FACEBOOKEMPRESA = "facebookEmpresa";
private static final String TAG_EMAILEMPRESA = "emailEmpresa";
private static final String TAG_TEXTOOFERTA = "textoOferta";
private static final String TAG_HORARIOEMPRESA = "horarioEmpresa";
private static final String TAG_CATEGORIAEMPRESA = "categoriaEmpresa";
private static final String TAG_LATITUDEMPRESA = "latitudEmpresa";
private static final String TAG_LONGITUDEMPRESA = "longitudEmpresa";
private static final String TAG_VALORACIONEMPRESA = "valoracionEmpresa";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onResume(){
super.onResume();
new GetContacts().execute();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_categorias);
// getting intent data
Intent in = getIntent();
// JSON node keys
// Get JSON values from previous intent
String name = in.getStringExtra(TAG_NAME);
String email = in.getStringExtra(TAG_ID);
// URL to get contacts JSON
this.url = url+email;
this.setTitle(name);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
//cambiar por los nuevos campos
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
//Starting single contact activity
//cambiar por los nuevos campos
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_ID, cost);
startActivity(in);
}
});
// Calling async task to get json
//new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(ofertas_list.this);
pDialog.setMessage("Cargando datos...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CATEGORIAS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String nombreEmpresa = c.getString(TAG_NOMBREEMPRESA);
String descripcionEmpresa = c.getString(TAG_DESCRIPCIONEMPRESA);
String strImagen = c.getString(TAG_STRIMAGEN);
String direccionEmpresa = c.getString(TAG_DIRECCIONEMPRESA);
String telefonoEmpresa = c.getString(TAG_TELEFONOEMPRESA);
String facebookEmpresa = c.getString(TAG_FACEBOOKEMPRESA);
String emailEmpresa = c.getString(TAG_EMAILEMPRESA);
String textoOferta = c.getString(TAG_TEXTOOFERTA);
String horarioEmpresa = c.getString(TAG_HORARIOEMPRESA);
String categoriaEmpresa = c.getString(TAG_CATEGORIAEMPRESA);
String valoracionEmpresa = c.getString(TAG_VALORACIONEMPRESA);
String latitudEmpresa = c.getString(TAG_LATITUDEMPRESA);
String longitudEmpresa = c.getString(TAG_LONGITUDEMPRESA);
String idEmpresa = c.getString(TAG_IDEMPRESA);
// Phone node is JSON Object
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_IDEMPRESA, idEmpresa);
contact.put(TAG_NOMBREEMPRESA, nombreEmpresa);
contact.put(TAG_DESCRIPCIONEMPRESA,descripcionEmpresa);
contact.put(TAG_STRIMAGEN,strImagen);
contact.put(TAG_DIRECCIONEMPRESA,direccionEmpresa);
contact.put(TAG_TELEFONOEMPRESA,telefonoEmpresa);
contact.put(TAG_FACEBOOKEMPRESA,facebookEmpresa);
contact.put(TAG_EMAILEMPRESA,emailEmpresa);
contact.put(TAG_TEXTOOFERTA,textoOferta);
contact.put(TAG_HORARIOEMPRESA,horarioEmpresa);
contact.put(TAG_CATEGORIAEMPRESA,categoriaEmpresa);
contact.put(TAG_VALORACIONEMPRESA,valoracionEmpresa);
contact.put(TAG_LATITUDEMPRESA,latitudEmpresa);
contact.put(TAG_LONGITUDEMPRESA,longitudEmpresa);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
ofertas_list.this, contactList,
R.layout.list_item_ofertas, new String[] { TAG_NOMBREEMPRESA, TAG_DIRECCIONEMPRESA}, new int[] { R.id.name,
R.id.email });
setListAdapter(adapter);
}
}
}
I am trying to solve the issue for two days but still no success. Please you are kindly requested to give me an advice on how to solve the issue.
CODE FOR ACTIVITY A:
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
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.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class categorias_list extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://XXXX/android_categoriaslist.php";
// JSON Node names
private static final String TAG_NAME = "nombreCategoria";
private static final String TAG_ID = "idCategoria";
private static final String TAG_CATEGORIAS = "Categorias";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_categorias);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
//Starting single contact activity
Intent in = new Intent(getApplicationContext(),
ofertas_list.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_ID, cost);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(categorias_list.this);
pDialog.setMessage("Cargando datos...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CATEGORIAS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
// Phone node is JSON Object
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
categorias_list.this, contactList,
R.layout.list_item, new String[] { TAG_NAME, TAG_ID}, new int[] { R.id.name,
R.id.email });
setListAdapter(adapter);
}
}
}
CODE FOR SERVICE HANDLER:
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
You have to need maintain arraylist globalaly use
Adapter.notifyDatasetChanged(); for updating the list:
List view can be updated by updating your array adapt
YourArrayAdapterName.notifyDataSetChanged;
Above code must be added in your Activities onResume Method, Which is your firt activity for the List
Example:
#Override
protected void onResume() {
super.onResume();
yourAdapterName.notifyDataSetChanged();
// do other stuffs here.
}
i'm trying to build android app which has tab layout which also has listfragment. i want total of three tabs, first home, second listview and third when clicked on listview it switches to third tabs and show some information all using json parsing.
i'm using this tutorials as a reference http://www.androidhive.info/2013/10/android-tab-layout-with-swipeable-views-1/
and for listview i'm using following - http://www.androidhive.info/2012/10/android-multilevel-listview-tutorial/
Now the question is that how can i change listActivity to listFragment?
How can i turn this code from Listactivity to Listfragment?
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
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.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import com.example.androidhive.helper.AlertDialogManager;
import com.example.androidhive.helper.ConnectionDetector;
import com.example.androidhive.helper.JSONParser;
public class AlbumsActivity extends ListActivity {
// Connection detector
ConnectionDetector cd;
// Alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> albumsList;
// albums JSONArray
JSONArray albums = null;
// albums JSON url
private static final String URL_ALBUMS = "http://api.androidhive.info/songs/albums.php";
// ALL JSON node names
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_SONGS_COUNT = "songs_count";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_albums);
cd = new ConnectionDetector(getApplicationContext());
// Check for internet connection
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(AlbumsActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Hashmap for ListView
albumsList = new ArrayList<HashMap<String, String>>();
// Loading Albums JSON in Background Thread
new LoadAlbums().execute();
// get listview
ListView lv = getListView();
/**
* Listview item click listener
* TrackListActivity will be lauched by passing album id
* */
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
// on selecting a single album
// TrackListActivity will be launched to show tracks inside the album
Intent i = new Intent(getApplicationContext(), TrackListActivity.class);
// send album id to tracklist activity to get list of songs under that album
String album_id = ((TextView) view.findViewById(R.id.album_id)).getText().toString();
i.putExtra("album_id", album_id);
startActivity(i);
}
});
}
/**
* Background Async Task to Load all Albums by making http request
* */
class LoadAlbums extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AlbumsActivity.this);
pDialog.setMessage("Listing Albums ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Albums JSON
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
String json = jsonParser.makeHttpRequest(URL_ALBUMS, "GET",
params);
// Check your log cat for JSON reponse
Log.d("Albums JSON: ", "> " + json);
try {
albums = new JSONArray(json);
if (albums != null) {
// looping through All albums
for (int i = 0; i < albums.length(); i++) {
JSONObject c = albums.getJSONObject(i);
// Storing each json item values in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String songs_count = c.getString(TAG_SONGS_COUNT);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_SONGS_COUNT, songs_count);
// adding HashList to ArrayList
albumsList.add(map);
}
}else{
Log.d("Albums: ", "null");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all albums
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AlbumsActivity.this, albumsList,
R.layout.list_item_albums, new String[] { TAG_ID,
TAG_NAME, TAG_SONGS_COUNT }, new int[] {
R.id.album_id, R.id.album_name, R.id.songs_count });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
please could you help me to found what is the problem with the following code !
when the item from spinner selected nothing occurs
i.e : the body of spinner.setOnItemSelectedListener is not seen !
code :
package com.example.spinner;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import java.util.HashMap;
import org.apache.http.NameValuePair;
import org.json.JSONException;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.AsyncTask;
public class MainActivity extends Activity {
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://10.0.2.2/RPM-connect/get_all_patients.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_DOCTOR = "products";
private static final String TAG_ID = "id";
private static final String TAG_F_NAME = "F_name";
private static final String TAG_S_NAME = "S_name";
private static final String TAG_L_NAME = "L_name";
// products JSONArray
JSONArray doctor = null;
ArrayList<String> spinnerArray ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
spinnerArray = new ArrayList<String>();
// Loading products in Background Thread
new LoadAllProducts().execute();
Spinner spinner = new Spinner(this);
//ArrayAdapter <HashMap<String, String>> spinnerArrayAdapter = new ArrayAdapter<HashMap<String, String>>(
ArrayAdapter <String> spinnerArrayAdapter = new ArrayAdapter <String >(
this, android.R.layout.simple_spinner_item, spinnerArray );
spinnerArrayAdapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
spinner = (Spinner) findViewById( R.id.spinner1 );
spinner.setAdapter(spinnerArrayAdapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int arg2, long arg3) {
Toast.makeText(MainActivity.this, "You have selected : " ,
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
} );
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
#SuppressLint("NewApi")
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
doctor = json.getJSONArray(TAG_DOCTOR);
// looping through All Products
for (int i = 0; i < doctor.length(); i++) {
JSONObject c = doctor.getJSONObject(i);
// Storing each json item in variable
String ID = c.getString(TAG_ID);
String F_name = c.getString(TAG_F_NAME);
String S_name = c.getString(TAG_S_NAME);
String L_name = c.getString(TAG_L_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, ID);
map.put(TAG_F_NAME, F_name);
map.put(TAG_S_NAME, S_name);
map.put(TAG_L_NAME, L_name);
// adding HashList to ArrayList
productsList.add(map);
Log.d("Before temp", productsList.toString());
spinnerArray.add(F_name + " " + L_name);
// temp[i]= F_name+" "+L_name ;
Log.d("TT",spinnerArray.get(i) );
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
MainActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
}
Your ArrayList may not be populated from the AsyncTask before you set the adapter. Implement onPostExecute() in your AsyncTask and call notifyDataSetChanged() on your adapter there. Also, you create a new Spinner then use one that exists in your xml
Spinner spinner = new Spinner(this);
this is not needed. Just declare your Spinner like this
public class MainActivity extends Activity {
Spinner spinner;
then initialize it from xml as you are doing later
spinner = (Spinner) findViewById( R.id.spinner1 );
notifyDataSetChanged() Docs
After your done with loading the items into the SpinnerAdapter inside your AsyncTask you need to tell the Adapter to refresh itself to load the new values.
This can be done by calling: spinnerArrayAdapter.notifyDataSetChanged().
Because the AsyncTask is running on another thread, you will need to implement
#Override
public void onPostExecute(String result) {
spinnerArrayAdapter.notifyDataSetChanged()
}
and call the spinnerArrayAdapter.notifyDataSetChanged() inside it, as seen above.
onPostExecute and onPreExecute is run on the main thread, so they can change Views on the UI thread.
As if combining checkbox and listview wasn't difficult enough. I've faced this stupid problem: " my list items are suppose to be downloaded from an HTTP request (done) but I don't know now where I should put the checkbox on the code so each list item has its own checkbox and how can I memorize each item was cheacked ". The following are the used code for the HTTP request:
package com.example.androidhive;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
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.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class AllProductsActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://10.0.2.2:8080/android_connect/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PID= "name";
private static final String TAG_CATEGORY = "category";
/*private static final String TAG_UNIT = "unit";
private static final String TAG_CALORY = "calory";
private static final String TAG_CARBOHYDRATE = "carbohydrate";
private static final String TAG_CATEGORY = "category";*/
// the array was defined in PHP file
private static final String TAG_PRODUCT = "product";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditProductActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
Log.d("NUN complete","tyt");
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllProductsActivity.this);
pDialog.setMessage("Loading items. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... Args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
Log.d("All Products: ", json.toString());
products = json.getJSONArray(TAG_PRODUCT);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID); // also name
String category = c.getString(TAG_CATEGORY );
// NO NEED FOR THEM !!
/*
String unit = c.getString(TAG_UNIT );
String category = c.getString(TAG_CATEGORY );
String calory = c.getString(TAG_CALORY );
String carbohydrate = c.getString(TAG_CARBOHYDRATE ); */
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_CATEGORY, category);
//map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
Log.d("All Products: ", json.toString());
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllProductsActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_CATEGORY},
new int[] { R.id.pid, R.id.category});
// updating listview
setListAdapter(adapter);
}
});
}
}
}
You can create a custom adapter, where you put all items you got from your HTTP request. and a checkbox per each item, you can use BaseAdapter instead of SimpleAdapter.
Create an xml with the TextView that you are using to display the products and a CheckBox then it will be generated for every item in your list. Just be sure to use a ListView with theandroid:id`
<ListView
android:id=#android:id/list
.../>
or you will get an error.
Also, you shouldn't need runOnUiThread() in onPostExecute() as it already runs on the UI thread