I want to show downloaded images in a ListView. Images are downloaded with a function DownloadImage and are bitmaps.
How do I show this in a ListView?
Images stored in folder htdocs in xampp and name images with book_id in a table book are equal(book_id=100 and name image=100.png).I want each book to have its own image.
I can show in the ListView book_name and book_price. The problem is with the image book.
class:
package bookstore.category;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
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 com.squareup.picasso.Picasso;
import android.R.drawable;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import bookstore.pack.JSONParser;
import bookstore.pack.R;
import android.app.Activity;
import android.app.ProgressDialog;
public class Computer extends Activity {
//Bitmap bm = null;
// progress dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> computerBookList;
private static String url_books = "http://10.0.2.2/project/computer.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_BOOK = "book";
private static final String TAG_BOOK_NAME = "book_name";
private static final String TAG_BOOK_PRICE = "book_price";
private static final String TAG_BOOK_ID = "book_id";
private static final String TAG_MESSAGE = "massage";
// category JSONArray
JSONArray book = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category);
Typeface font1 = Typeface.createFromAsset(getAssets(),
"font/bnazanin.TTF");
// Hashmap for ListView
computerBookList = new ArrayList<HashMap<String, String>>();
new LoadBook().execute();
}
class LoadBook extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Computer.this);
pDialog.setMessage("Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
List<Book> books=new ArrayList<Book>();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_books, "GET", params);
// Check your log cat for JSON reponse
Log.d("book:", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// books found
book = json.getJSONArray(TAG_BOOK);
for (int i = 0; i < book.length(); i++) {
JSONObject c = book.getJSONObject(i);
// Storing each json item in variable
String book_name = c.getString(TAG_BOOK_NAME);
String book_price = c.getString(TAG_BOOK_PRICE);
String book_id = c.getString(TAG_BOOK_ID);
DownloadImage("10.0.2.2/project/images
/"+book_id+".png");
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_BOOK_NAME, book_name);
map.put(TAG_BOOK_PRICE, book_price);
// map.put(TAG_AUTHOR_NAME, author_name);
// adding HashList to ArrayList
computerBookList.add(map);
}
return json.getString(TAG_MESSAGE);
} else {
System.out.println("no book found");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
ListView view1 = (ListView) findViewById(R.id.list_view);
public void run() {
ImageView iv = (ImageView) findViewById(R.id.list_image);
ListAdapter adapter = new SimpleAdapter(Computer.this,
computerBookList, R.layout.search_item,
new String[] { TAG_BOOK_NAME, TAG_BOOK_PRICE },
new int[] { R.id.book_name, R.id.book_price });
view1.setAdapter(adapter);
view1.setAdapter(adapter);
}
});
}
}
private Bitmap DownloadImage(String URL) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
private InputStream OpenHttpConnection(String urlString) throws IOException {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
} catch (Exception ex) {
throw new IOException("Error connecting");
}
return in;
}
}
For experience better modularity, first of all define a Book class with its properties and methods, For example here is an option:
public class Book {
String mName;
long mPrice;
Bitmap mPhoto;
}
Then collect all of your book information into a list of Book(i.e List<Book>).
Now it's time to declare a custom adapter for the ListView. For example you can try:
public class CustomAdapter extends ArrayAdapter<Book> {
public CustomAdapter(Context context, List<Book> books) {
super(context, 0, books);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if(row == null) {
// inflate row layout and assign to 'row'
}
final thisBook = getItem(position);
final ImageView photo = row.findViewById(R.id.photo);
photo.setImageBitmap(thisBook.mPhoto);
return row;
}
}
Use any library for this.
I recommend to use picasso library
just download the latest jar file from here
and use this code in your getView() method of your adapter
Picasso.with(context)
.load(url)
.placeholder(R.drawable.img_loading)
.error(R.drawable.img_error)
.into(imageView);
First store the bitmaps (from AsyncTask) to an Arraylist or any data structure. Then you have make a Custom adapter extending the "BaseAdapter" class and set it on your Listview so that you can show those bitmaps in your list.
Implementing custom adapters can be found here
Related
I'm working on udacity popular movies stage 1 project that will allow me to discover movies from themoviedb database.
I've created Movie, MovieAdapter, and MainActivity(with FetchMovieAsyncTask as inner class) classes. But I keep getting below error
java.lang.NullPointerException: Attempt to invoke interface method
'int java.util.List.size()' on a null object reference
These are my codes
Movie class:
public class Movie{
private String mMovieTitle;
private String mPosterPath;
private String mOverview;
private String mReleaseDate;
private double mRating;
public Movie(){
mMovieTitle = null;
mPosterPath = null;
mOverview = null;
mReleaseDate = null;
mRating = -1.0;
}
public Movie(String title){
mMovieTitle = title;
}
public Movie(String title, String posterPath, String overview, String releaseDate, double rating){
mMovieTitle = title;
mPosterPath = posterPath;
mOverview = overview;
mReleaseDate = releaseDate;
mRating = rating;
}
public String getMovieTitle(){
return mMovieTitle;
}
public String getPosterPath(){
return mPosterPath;
}
public String getOverview(){
return mOverview;
}
public String getReleaseData(){
return mReleaseDate;
}
public double getRating(){
return mRating;
}
}
MovieAdapter class:
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
/**
* Created by ibayp on 04/08/2017.
*/
public class MovieAdapter extends ArrayAdapter<Movie> {
Context context;
ArrayList<Movie> movies;
public MovieAdapter(Context context, ArrayList<Movie> movies){
super(context, 0, movies);
this.context = context;
this.movies = movies;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View view = convertView;
if(view == null){
view = LayoutInflater.from(getContext()).inflate(R.layout.poster_list, parent, false);
}
ImageView imageView = (ImageView)view.findViewById(R.id.movie_poster);
Picasso.with(getContext())
.load("https://image.tmdb.org/t/p/w500/kqjL17yufvn9OVLyXYpvtyrFfak.jpg")
.into(imageView);
return view;
}
}
and MainActivity class:
package com.android.ibayp.popularmovies;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
GridView gridView;
ArrayList<Movie> movies;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new FetchMovieAsyncTask().execute("popularity.desc");
MovieAdapter adapter = new MovieAdapter(this, movies);
gridView = (GridView)findViewById(R.id.grid_view);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long l) {
Movie movie = (Movie)parent.getItemAtPosition(position);
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
intent.putExtra("title", movie.getMovieTitle());
startActivity(intent);
}
});
}
private class FetchMovieAsyncTask extends AsyncTask<String, Void, ArrayList<Movie>> {
private final String TAG = com.android.ibayp.popularmovies.FetchMovieAsyncTask.class.getSimpleName();
private static final String API_KEY = "api key";
private static final String BASE_URL = "https://api.themoviedb.org/3/discover/movie?";
private String API_PARAM = "api_key";
private String SORT_BY = "sort_by";
public URL buildURL(String[] sortMethod){
Uri builtUri = Uri.parse(BASE_URL).buildUpon()
.appendQueryParameter(API_PARAM, API_KEY)
.appendQueryParameter(SORT_BY, sortMethod[0])
.build();
URL url = null;
try{
url = new URL(builtUri.toString());
}catch (MalformedURLException e){
e.printStackTrace();
}
Log.v(TAG, "BUILT URI: " +url);
return url;
}
private String makeHttpRequst(URL url)throws IOException {
String jsonResponse = "";
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try{
urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
inputStream = urlConnection.getInputStream();
jsonResponse = readStream(inputStream);
}catch (IOException e){
e.printStackTrace();
}finally {
if(urlConnection!=null){
urlConnection.disconnect();
}
if (inputStream!=null){
inputStream.close();
}
}
return jsonResponse;
}
private String readStream(InputStream inputStream) throws IOException{
StringBuilder results = new StringBuilder();
if(inputStream!=null){
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line!=null){
results.append(line);
line = reader.readLine();
}
}
return results.toString();
}
private ArrayList<Movie> getMovieFromJson(String movieJson){
movies = new ArrayList<Movie>();
try{
JSONObject baseResponse = new JSONObject(movieJson);
JSONArray resultsArray = baseResponse.getJSONArray("results");
Log.v(TAG, "Array Results: "+resultsArray.length());
if (resultsArray.length() > 0){
for (int i = 0; i<resultsArray.length(); i++ ){
JSONObject movieInformation = resultsArray.getJSONObject(i);
movies.add(new Movie(movieInformation.getString("title"),
movieInformation.getString("poster_path"),
movieInformation.getString("overview"),
movieInformation.getString("release_date"),
movieInformation.getDouble("vote_average")));
}
}
}catch (JSONException e){
Log.v(TAG, "Problem parsing Json" + e);
}
return movies;
}
#Override
protected ArrayList<Movie> doInBackground(String... strings) {
URL url = buildURL(strings);
String jsonResponse = "";
try{
jsonResponse = makeHttpRequst(url);
}catch (IOException e){
Log.v(TAG, "IO Exception error "+e);
}
movies = getMovieFromJson(jsonResponse);
return movies;
}
#Override
protected void onPostExecute(ArrayList<Movie> movies) {
if (movies==null){
return;
}
super.onPostExecute(movies);
}
}
}
I used logging and managed to get the correct json results, but I can't display it on the ui thread.
How can I solve this? Thanks
*note that I used dummy image for the poster
When you instantiate your adapter movies are null. Because asynctask is running in parallel thread. Instantiate your adapter in your asynctask's onPostExecute method. This way you will be sure asynctask is completed.
#Override
protected void onPostExecute(ArrayList<Movie> movies) {
if (movies==null){
return;
}
super.onPostExecute(movies);
MovieAdapter adapter = new MovieAdapter(MainActivity.this, movies);
gridView.setAdapter(adapter);
}
Call adapter.notifyDataSetChanged() after movies.add(...) or in onPostExecute
I finished the Android Nanodegree a while back and remember working on this project. When you instantiate an adapter it will call the getSize() method to determine how many rows to create for the views and then call getView() on each of them to bind the views.
Since your async Task may not have finished downloading the movies, you're passing an empty list to the adapter and thus getting a NullPointerException.
It's always a good approach to instantiate the adapter in the onPostExecute() method of AsyncTask. This method is called on the UI thread after the background thread has finished execution.
So put these two lines of code in onPostExecute() and it should work
MovieAdapter adapter = new MovieAdapter(MainActivity.this, movies);
gridView.setAdapter(adapter);
I'm developing an app and now I have to pass a parameter to a RESTful Service's URL. I'm using AsyncTask, and I need to pass a text from a list view as a parameter to the URL, for example: the URL is http://ip:7001/product?product_name=PARAM I need to get the text from the selected item from my list view, and pass as a parameter in PARAM, using AsyncTask. I've already got the text from the item in the listView, now I just need to pass it as a parameter.
This is my AsycTask class:
package com.tumta.henrique.teste;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import com.tumta.henrique.teste.ProdutoFragment;
/**
* Created by Henrique on 18/05/2015.
*/
public class FiltraProduto extends AsyncTask<String, Void, List<String>> {
private ConsultaConcluidaFiltroProdutoListener listener;
public static String URL_STRING = "http://192.168.0.20:7001/com.henrique.rest/api/v1/status/pro_filtro?pro_nome=";
public FiltraProduto(ConsultaConcluidaFiltroProdutoListener listener) {
this.listener = listener;
}
private List<String> InterpretaResultado(String resultado) throws JSONException {
JSONObject object = new JSONObject(resultado);
JSONArray jsonArray = object.getJSONArray("produto");
//JSONObject jsonProduto = jsonArray.getJSONObject(0);
// String id = jsonProduto.getString("pro_id");
//proId = id;
List<Object> listaNomes = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonProdutoInfo = jsonArray.getJSONObject(i);
String proNome= jsonProdutoInfo.getString("pro_nome");
double proPreco = jsonProdutoInfo.getDouble("pro_preco");
double proSdAtual = jsonProdutoInfo.getDouble("pro_sdAtual");
listaNomes.add(i, proNome);
listaNomes.add(i, proPreco);
listaNomes.add(i, proSdAtual);
}
List<String> strings = new ArrayList<String>();
for (Object o : listaNomes) {
strings.add(o != null ? o.toString() : null);
}
return strings;
}
private String ConsultaServidor() throws IOException {
InputStream is = null;
try {
URL url = new URL(URL_STRING);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(10000);
conn.setReadTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
conn.getResponseCode();
is = conn.getInputStream();
Reader reader = null;
reader = new InputStreamReader(is);
char[] buffer = new char[2048];
reader.read(buffer);
return new String(buffer);
} finally {
if (is != null) {
is.close();
}
}
}
#Override
protected List<String> doInBackground(String... params) {
try {
String resultado = ConsultaServidor();
return InterpretaResultado(resultado);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(List<String> result) {
listener.onConsultaConcluida(result);
super.onPostExecute(result);
}
public interface ConsultaConcluidaFiltroProdutoListener {
void onConsultaConcluida(List<String> result);
}
}
In the URL_STRING I need to pass the param at pro_nome=?
Here I get the item text. This is in my Fragment that has the List View:
public String retornaParam(String param){
return param;
}
#Override
public void onConsultaConcluida(List<String> result) {
final ListView listaProdutos = (ListView) getView().findViewById(R.id.listaprodutos);
ArrayAdapter arrayAdapter = new ArrayAdapter<>(getView().getContext(),android.R.layout.simple_list_item_1, result);
listaProdutos.setAdapter(arrayAdapter);
listaProdutos.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parentAdapter, View view, int position,
long id) {
String nomeProduto = listaProdutos.getItemAtPosition(position).toString();
retornaParam(nomeProduto);
Intent intent = new Intent(getActivity(), DetalhesProdutoActivity.class);
//intent.putExtra("pro_nome", listaProdutos.getItemAtPosition(position).toString());
startActivity(intent);
}
});
}
I get the text and store it in param from the retornaParam method.
Does somebody know how to do it?
If you need more information, just let me know.
You pass in params to an AsyncTask using:
YourAsyncTask.execute(yourview.getText(), "and", "more", "params");
You can then access them in
#Override
protected String doInBackground(String... params) {
URL_STRING += params[0];
...
Just add the following code before sending executing your httpClient:
URL_STRING + = textInsideYourTextView;
It should work, just avoid to manipulate your ui elements outside your UI thread.
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 having a problem with my gallery, it's to slow and it lags. I 'm loading images from server with Image Adapter:
package com.example.ocenitaksi;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import org.apache.http.client.utils.URLEncodedUtils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class ImageAdapter extends BaseAdapter {
private Context context;
private final String[] mobileValues;
public ImageAdapter(Context context, String[] mobileValues) {
this.context = context;
this.mobileValues = mobileValues;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = new View(context);
// get layout from mobile.xml
gridView = inflater.inflate(R.layout.mobile, null);
// set image based on selected text
ImageView imageView = (ImageView) gridView
.findViewById(R.id.grid_item_image);
// ubacivanje slika za string
String mobile = mobileValues[position];
if (mobile.equals(MainActivity.imena[position])) {
//imageView.setImageURI("http://24.media.tumblr.com/avatar_a400b4dbb80e_64.png");
Bitmap bitmap=null;;
mobile = mobile.replace(" ", "_");
bitmap = DownloadImage("http://android.yunews.net/images/"+mobile+".png");
imageView.setImageBitmap(bitmap);
}
}
else {
gridView = (View) convertView;
}
return gridView;
}
#Override
public int getCount() {
return mobileValues.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
private InputStream OpenHttpConnection(String urlString) throws IOException {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
} catch (Exception ex) {
throw new IOException("Error connecting");
}
return in;
}
private Bitmap DownloadImage(String URL) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return bitmap;
}
}
and this is part of my main activity.
private class LongOperation extends AsyncTask<String, Void, String>
{
protected void onPreExecute()
{
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setTitle("Molimo sacekajte...");
progressDialog.setMessage("Ucitavam taksi sluzbe...");
progressDialog.setCancelable(true);
progressDialog.show();
}
protected String doInBackground(String... params)
{
niz = new JSONFunkcije().ListaSluzbi();
imena= new String[niz.size()];
Iterator<String> it= niz.iterator();
for (int i=0;i<niz.size();i++)
imena[i]=it.next();
slicice = new ImageAdapter(MainActivity.this, imena);
return null;
}
protected void onPostExecute(String result)
{
progressDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
//Button dugme1 = (Button) findViewById(R.id.dugme1);
///params.height = "50dpi";
//dugme1.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 100));
Gallery gridView = (Gallery) findViewById(R.id.gallery1);
gridView.setAdapter(slicice);
//kraj ucitvanja
//gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
// Sending image id to FullScreenActivity
Intent i = new Intent(getApplicationContext(), TaksiDetalji.class);
// passing array index
i.putExtra("id", imena[position]);
startActivity(i);
}
});
}
});
System.gc();
}
}
I 'm calling LongOperation from OnCrate:
mytask = new LongOperation();
mytask.execute();
Is something wrong with ImageAdapter? Too many calls, downloads? I tried to cache images but I failed.
From your code, I would say there are many reasons and because all these below reasons its running slow:
You haven't followed ViewHolder pattern. Read documentation also for Making ListView Scrolling Smooth
You haven't followed standard way of loading images (i.e. Cached images in local, load from local if its already cached)
Better you try any library available (Universal Image loader or any) on web to load images in your ListView.
I am new to android. I am implementing a project in which I want to get the data from the back end and display on my android screen.
The Json I am trying to call is:-
[{"admin":null,"card_no":"8789","created_at":"2013-04-09T12:55:54Z","deleted":0,"email":"dfds#fgfd.com","entered_by":null,"first_name":"Gajanan","id":8,"last_name":"Bhat","last_updated_by":null,"middle_name":"","mobile":87981,"updated_at":"2013-04-13T05:26:25Z","user_type_id":null},{"admin":{"created_at":"2013-04-10T09:02:00Z","deleted":0,"designation":"Sr software Engineer","email":"admin#qwe.com","first_name":"Chiron","id":1,"last_name":"Synergies","middle_name":"Sr software Engineer","office_phone":"98789765","super_admin":false,"updated_at":"2013-04-10T12:03:04Z","username":"Admin"},"card_no":"66","created_at":"2013-04-08T09:47:15Z","deleted":0,"email":"rajaarun1991","entered_by":1,"first_name":"Arun","id":1,"last_name":"Raja\n","last_updated_by":1,"middle_name":"Nagaraj","mobile":941,"updated_at":"2013-04-08T09:47:15Z","user_type_id":1}]
My JsonParser.java is as follows:-
package com.example.library;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONArray jarray = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONArray getJSONFromUrl(String url) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e("==>", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// try parse the string to a JSON object
try {
jarray = new JSONArray( builder.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jarray;
}
}
/* public void writeJSON() {
JSONObject object = new JSONObject();
try {
object.put("name", "");
object.put("score", new Integer(200));
object.put("current", new Double(152.32));
object.put("nickname", "Programmer");
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println(object);
}
*/
And my activity.java is as follows:-
package com.example.library;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
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.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class SecondActivity extends Activity
{
private Context context;
private static String url = "http://192.168.0.100:3000/users.json";
private static final String TAG_ID = "id";
private static final String TAG_FIRST_NAME = "first_name";
private static final String TAG_MIDDLE_NAME = "middle_name";
private static final String TAG_LAST_NAME = "last_name";
// private static final String TAG_POINTS = "experiencePoints";
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
ListView lv ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new ProgressTask(SecondActivity.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
public ProgressTask(SecondActivity secondActivity) {
Log.i("1", "Called");
context = secondActivity;
dialog = new ProgressDialog(context);
}
/** progress dialog to show user that the backup is processing. */
/** application context. */
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
ListAdapter adapter = new SimpleAdapter(context, jsonlist,
R.layout.list_item, new String[] { TAG_ID, TAG_FIRST_NAME,
TAG_MIDDLE_NAME, TAG_LAST_NAME }, new int[] {
R.id.id, R.id.first_name, R.id.middle_name,
R.id.last_name });
setListAdapter(adapter);
// selecting single ListView item
lv = getListView();
}
private void setListAdapter(ListAdapter adapter) {
// TODO Auto-generated method stub
}
protected Boolean doInBackground(final String... args) {
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url);
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
String id = c.getString(TAG_ID);
String first_name = c.getString(TAG_FIRST_NAME);
String middle_name = c.getString(TAG_MIDDLE_NAME);
String last_name = c.getString(TAG_LAST_NAME);
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_FIRST_NAME, first_name);
map.put(TAG_MIDDLE_NAME, middle_name);
map.put(TAG_LAST_NAME, last_name);
jsonlist.add(map);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
}
public ListView getListView() {
// TODO Auto-generated method stub
return null;
}
}
I am not able to show anything on the emulators for users,whereas I am able to fetch the data from the server
Actually in the project I want to display all the users present in the library.I am accessing the server which is on Ubuntu.
The following message is displayed on the console(Terminal):-
Started GET "/users.json" for 192.168.0.104 at 2013-05-05 22:05:01 -0700
Processing by UsersController#index as JSON
User Load (0.4ms) SELECT "users".* FROM "users" WHERE (users.deleted = 0) ORDER BY users.id DESC
Admin Load (0.3ms) SELECT "admins".* FROM "admins" WHERE "admins"."id" = 1 AND (admins.deleted = 0) ORDER BY admins.id DESC LIMIT 1
Completed 200 OK in 4ms (Views: 2.1ms | ActiveRecord: 0.6ms)
[2013-05-05 22:05:01] WARN Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true
However i am not able to display the data on the android screen/emulator.
Please help me with this.
I missed your setAdapterList()method.
Any error for your json pasers? and can you put your activity which is inherited from SecondActivity?
//modify getListView
public ListView getListView() {
// TODO Auto-generated method stub
listView = (ListView)findViewById(r.your.listview);
return listView;
}
//modify setListAdapter
private void setListAdapter(ListAdapter adapter) {
// TODO Auto-generated method stub
lv.setAdapter(adapter);
}