Pull to refresh GridView infinite loading/ fails to pull data - android

I can't seem to figure out what is going wrong with this, the code is pretty clean/ simple, but for some reason when I pull to refresh, it just shows me the loading icon infinity. Not only that, but I don't even receive any errors. The library I used for pull to refresh is this one.
I've spent several hours trying to figure this out, but the fact that it's not even giving me errors is making it very hard for me to track down.
And yes, I am sure the rest request is working.
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
public final class PullToRefresh extends Activity {
static final int MENU_SET_MODE = 0;
static final String KEY_FEED = "feed"; // parent node
static final String KEY_UID_FK = "uid_fk";
static final String KEY_FIRST_NAME = "first_name";
static final String KEY_LAST_NAME = "last_name";
public static final String KEY_NAME = "name";
static final String KEY_MESSAGE = "message";
static final String KEY_CREATED = "created";
static final String KEY_THUMB_URL = "thumb_img";
static final String KEY_DATA = "data";
static final String KEY_HOMETOWN = "hometown";
static final String KEY_BIO = "bio";
private ArrayList<HashMap<String, String>> feedList = new ArrayList<HashMap<String, String>>();
private PullToRefreshGridView mPullRefreshGridView;
private GridView mGridView;
private GridAdapter adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ptr_grid);
mPullRefreshGridView = (PullToRefreshGridView) findViewById(R.id.pull_refresh_grid);
mGridView = mPullRefreshGridView.getRefreshableView();
// Set a listener to be invoked when the list should be refreshed.
mPullRefreshGridView
.setOnRefreshListener(new OnRefreshListener2<GridView>() {
#Override
public void onPullDownToRefresh(
PullToRefreshBase<GridView> refreshView) {
Toast.makeText(PullToRefresh.this, "Pull Down!",
Toast.LENGTH_SHORT).show();
try {
new RestClientUsage().getPublicTimeline();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onPullUpToRefresh(
PullToRefreshBase<GridView> refreshView) {
Toast.makeText(PullToRefresh.this, "Pull Up!",
Toast.LENGTH_SHORT).show();
try {
new RestClientUsage().getPublicTimeline();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
ArrayList<HashMap<String, String>> feedList = new ArrayList<HashMap<String, String>>();
TextView tv = new TextView(this);
tv.setGravity(Gravity.CENTER);
tv.setText("Empty View, Pull Down/Up to Add Items");
mPullRefreshGridView.setEmptyView(tv);
adapter = new GridAdapter(PullToRefresh.this, feedList);
mGridView.setAdapter(adapter);
}
class RestClientUsage {
public void getPublicTimeline() throws JSONException {
RequestParams params = new RequestParams();
params.put("loggedin_uid", TabHostFragmentActivity.loggedin_uid);
RestClient.post("http://localhost/basic/rest/request/format/json",
params, new JsonHttpResponseHandler() {
private JSONArray feed;
#Override
public void onSuccess(JSONObject json) {
try {
Log.i("JSON->TRAILS RESPONSE", json.toString(3));
// Getting Feed Array
feed = json.getJSONArray(KEY_FEED);
/*
* Log & Debug Code String feed_log =
* feed.toString(3); int feed_length =
* feed.length(); String string_length =
* Integer.toString(feed_length);
* Log.i("JSON PROFILE FEED RESPONSE", feed_log
* ); Log.i("JSON PROFILE FEED LENGTH",
* string_length);
*/
// looping through Feed of Updates
for (int i = 0; i < feed.length(); i++) {
JSONObject c = feed.getJSONObject(i);
String jFeedObj = c.toString(3);
Log.i("JSON FEED OBJ", jFeedObj);
// Storing each json item in variable
String uid = c.getString(KEY_UID_FK);
String first_name = c
.getString(KEY_FIRST_NAME);
String last_name = c
.getString(KEY_LAST_NAME);
String name = first_name + ' ' + last_name;
String http = "http://10.0.2.2/CI_REST_LOGIN/UPLOADS/thumbs/";
String base_url = c
.getString(KEY_THUMB_URL);
String thumb_url = http + base_url;
String message = c.getString(KEY_MESSAGE);
String created = c.getString(KEY_CREATED);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key =>
// value
map.put(KEY_UID_FK, uid);
map.put(KEY_NAME, name);
map.put(KEY_MESSAGE, message);
map.put(KEY_CREATED, created);
map.put(KEY_THUMB_URL, thumb_url);
Log.i("Trails - line 130", "Success");
// adding HashList to ArrayList
feedList.add(map);
}
adapter.notifyDataSetChanged();
// Call onRefreshComplete when the list has been
// refreshed.
mPullRefreshGridView.onRefreshComplete();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(
0,
MENU_SET_MODE,
0,
mPullRefreshGridView.getMode() == Mode.BOTH ? "Change to MODE_PULL_DOWN"
: "Change to MODE_PULL_BOTH");
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem setModeItem = menu.findItem(MENU_SET_MODE);
setModeItem
.setTitle(mPullRefreshGridView.getMode() == Mode.BOTH ? "Change to MODE_PULL_FROM_START"
: "Change to MODE_PULL_BOTH");
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_SET_MODE:
mPullRefreshGridView
.setMode(mPullRefreshGridView.getMode() == Mode.BOTH ? Mode.PULL_FROM_START
: Mode.BOTH);
break;
}
return super.onOptionsItemSelected(item);
}
}
And here is the code for my GridView adapter:
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.loopj.android.image.SmartImageView;
public class GridAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
public GridAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.mobile, null);
TextView name = (TextView) vi.findViewById(R.id.grid_item_label); // title
SmartImageView thumb_image = (SmartImageView) vi
.findViewById(R.id.grid_item_image);
HashMap<String, String> update = new HashMap<String, String>();
update = data.get(position);
// Setting all values in listview
name.setText(update.get("name"));
thumb_image.setImageUrl(update.get("thumb_img"));
name.setOnClickListener(new myOnClickListener(position));
thumb_image.setOnClickListener(new myOnClickListener(position));
return vi;
}
public class myOnClickListener implements OnClickListener {
private int position;
private String clicked_uid;
public myOnClickListener(int position) {
this.position = position;
}
#Override
public void onClick(View v) { // TODO Auto-generated method stub
HashMap<String, String> update = new HashMap<String, String>();
update = data.get(position);
Log.i("Update Position:", update.toString());
clicked_uid = update.get("uid");
Log.d("Clicked UID:", clicked_uid + "");
Intent i = new Intent(activity.getApplicationContext(),
TabHostFragmentActivity.class);
i.putExtra("profile_uid", clicked_uid);
activity.startActivity(i);
}
}
}

You should POST to 10.0.2.2 instead of localhost in the call to RestClient.post in RestClientUsage.
I am not familiar withJsonHttpResponseHandler, but I would image there's an onFailure method (or something similar) that you may want to override. If there is, you may way to call mPullRefreshGridView.onRefreshComplete() in it.

Related

ERROR get item in ListView when OnClick item

my name ari.. i am newbie in Android development. maybe you can help me to answer my problem. I want to display data from the listview adapter, but when i click the data. my app force close.
i have a adapter for show data in listview like :
ListAdapter.java
package com.santosa.sapasantosa.components;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.santosa.sapasantosa.R;
import java.util.ArrayList;
/**
* Created by muhammadaa on 10/14/2017.
*/
public class ListAdapter extends BaseAdapter {
private Activity activity;
private static ArrayList nik;
private static ArrayList nama;
private static ArrayList email;
private static ArrayList phone;
private static ArrayList jabatan;
private static ArrayList departement;
private static ArrayList gender;
private static ArrayList status;
private static ArrayList label;
private static LayoutInflater inflater = null;
public ListAdapter(Activity a, ArrayList b, ArrayList c, ArrayList d, ArrayList e, ArrayList f, ArrayList g, ArrayList h, ArrayList i, ArrayList j) {
activity = a;
this.nik = b;
this.nama = c;
this.email = d;
this.gender = e;
this.status = f;
this.label = g;
this.phone = h;
this.jabatan = i;
this.departement = j;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return nik.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.listview_data_profile, null);
TextView nik2 = (TextView) vi.findViewById(R.id.profNik); // nik
String ambilNik = nik.get(position).toString();
nik2.setText(ambilNik);
TextView nama2 = (TextView) vi.findViewById(R.id.profNama); // nama
String ambilNama = nama.get(position).toString();
nama2.setText(ambilNama);
TextView email2 = (TextView) vi.findViewById(R.id.profEmail); // email
String ambilEmail = email.get(position).toString();
email2.setText(ambilEmail);
TextView phone2 = (TextView) vi.findViewById(R.id.profPhone); // phone
String ambilPhone = phone.get(position).toString();
phone2.setText(ambilPhone);
TextView gender2 = (TextView) vi.findViewById(R.id.profGender); // gender
String ambilGender = gender.get(position).toString();
gender2.setText(ambilGender);
TextView bagian = (TextView) vi.findViewById(R.id.profBagian); // Bagian
String ambilJabatan = jabatan.get(position).toString();
String ambilDepartement = departement.get(position).toString();
bagian.setText(ambilJabatan+"/"+ambilDepartement);
TextView status2 = (TextView) vi.findViewById(R.id.profStatus); // status
String ambilStatus = status.get(position).toString();
status2.setText(ambilStatus);
TextView label2 = (TextView) vi.findViewById(R.id.countNumber); // label
String ambilLabel = label.get(position).toString();
label2.setText(ambilLabel);
return vi;
}
}
And this class fragment for using adapter
AdminHomeFragment
package com.santosa.sapasantosa.view.admin;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.StringDef;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import com.santosa.sapasantosa.R;
import com.santosa.sapasantosa.components.ListAdapter;
import com.santosa.sapasantosa.components.RequestHandler;
import com.santosa.sapasantosa.components.SharedPrefManager;
import com.santosa.sapasantosa.configs.Constrant;
import com.santosa.sapasantosa.models.Employee;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import static android.provider.AlarmClock.EXTRA_MESSAGE;
/**
* A simple {#link Fragment} subclass.
*/
public class AdminHomeFragment extends Fragment {
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
ArrayList<String> nik_array = new ArrayList<String>();
ArrayList<String> nama_array = new ArrayList<String>();
ArrayList<String> email_array = new ArrayList<String>();
ArrayList<String> phone_array = new ArrayList<String>();
ArrayList<String> gender_array = new ArrayList<String>();
ArrayList<String> jabatan_array = new ArrayList<String>();
ArrayList<String> departement_array = new ArrayList<String>();
ArrayList<String> status_array = new ArrayList<String>();
ArrayList<Integer> label_array = new ArrayList<>();
com.santosa.sapasantosa.components.ListAdapter adapter;
ListView listPeg;
public AdminHomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_admin_home, container, false);
listPeg = (ListView) view.findViewById(R.id.pegListView);
listPeg.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(getActivity(),ProfileEmployeeActivity.class);
HashMap<String,String> map = (HashMap) parent.getItemAtPosition(position);
Log.e("","adad "+map);
String empId = map.get("nik");
i.putExtra("nik",empId);
startActivity(i);
}
});
loadDataPegawai();
return view;
}
private void loadDataPegawai() {
// get parameter
final String users = SharedPrefManager.getInstance(getContext()).getUserEmployee().getNik();
class LoadPegawai extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... voids) {
//creating request handler object
RequestHandler requestHandler = new RequestHandler();
//creating request parameters
HashMap<String, String> params = new HashMap<>();
params.put("username", users);
//returing the response
return requestHandler.sendPostRequest(Constrant.URL_PROFIL, params);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
int n = 1;
try {
JSONObject obj = new JSONObject(s);
if (!obj.getBoolean("error")) {
// get data user dari respone
JSONArray userJson = obj.getJSONArray("user");
for (int i = 0, count = userJson.length(); i < count; i++) {
try {
JSONObject jsonObject = userJson.getJSONObject(i);
if (jsonObject.getString("employeeStatus").toString().equals("0")) {
nik_array.add(jsonObject.getString("employeeID").toString());
nama_array.add(jsonObject.getString("employeeNama").toString());
email_array.add(jsonObject.getString("employeeEmail").toString());
gender_array.add(jsonObject.getString("employeeGender").toString());
status_array.add(jsonObject.getString("employeeStatus").toString());
phone_array.add(jsonObject.getString("employeePhone").toString());
jabatan_array.add(jsonObject.getString("employeeJabatan").toString());
departement_array.add(jsonObject.getString("employeeDepartement").toString());
label_array.add(n++);
String id = jsonObject.getString("employeeID").toString();
// adding to hashmap
HashMap<String,String> employees = new HashMap<>();
employees.put("nik",id);
list.add(employees);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
/* Set data to listview */
adapter = new com.santosa.sapasantosa.components.ListAdapter( getActivity(),
nik_array,
nama_array,
email_array,
gender_array,
status_array,
label_array,
phone_array,
jabatan_array,
departement_array);
listPeg.setAdapter(adapter);
listPeg.setTextFilterEnabled(true);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
//executing the async task
LoadPegawai ru = new LoadPegawai();
ru.execute();
}
}
when i clik data adapter in ListView, i have a Error like:
Can you help me for resolve the error. I say very very thanks you for your help...
Seems you're trying to display all employees as a ListView... If my understanding is't wrong, you should :
Create an EmployeeBean
Put all your employee into a collection...maybe ArrayList.
After that, when you click an item on ListView, the integer you get is the index of EmployeeBean in your collection, so that you can access it from your collection.

Trying to understand list view behaviours in Android

I need help implementing my app. There are different activities. On one activity, a list view is shown, then if the user clicks on a row, another list view activity is shown.
The list view activities may need a variable that is used as param to a URL to retrieve JSON data to feed the list view. I will try to explain it better.
Activity 1: ListView with objects retrieve from JSON (no need for URL param). User clicks on row and opens Activity 2 ( a variable is passed from activity 1 to activity 2).
Activity 2: ListView with objects retrieve from JSON, URL includes param (variable passed from A1 to A2). List view objects are shown.
Now the user clicks on back button (hardware button). Activity 1 list view objects shown.
If the user clicks again on the same row at A1 as before, then A2 doesn't show anything.
If you need me to show my code, no problem...but I need more an explanation to the behaviour rather than code examples. Thank you
EDIT HERE:
ACTIVITY 1 LISTVIEW ADAPTER
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class DondeEsta_ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public DondeEsta_ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView id_categoria_donde_esta_textView;
TextView nombre_categoria_donde_esta_textView;
ImageView imagen_categoria_donde_esta;
TextView tipo_menu;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.dondeesta_listview_item, parent, false);
// Get the position
resultp = data.get(position);
RelativeLayout myLayout = (RelativeLayout) itemView.findViewById(R.id.milayout);
if (position % 2 == 1) {
myLayout.setBackgroundResource(R.color.fondo);
//lugar_evento.setBackgroundResource(R.color.fondo);
} else {
myLayout.setBackgroundResource(R.color.blanco);
//titulo_evento.setBackgroundResource(R.color.blanco);
//lugar_evento.setBackgroundResource(R.color.blanco);
}
String tipo_de_menu = resultp.get(DondeEsta_MainActivity.TIPO_MENU);
String id_categoria_donde_esta =resultp.get(DondeEsta_MainActivity.ID_CATEGORIA_DONDE_ESTA);
// Locate the TextViews in listview_item.xml
nombre_categoria_donde_esta_textView = (TextView) itemView.findViewById(R.id.textView1);
imagen_categoria_donde_esta = (ImageView) itemView.findViewById(R.id.imageView1);
nombre_categoria_donde_esta_textView.setText (resultp.get(DondeEsta_MainActivity.NOMBRE_CATEGORIA_DONDE_ESTA));
imageLoader.DisplayImage(resultp.get(DondeEsta_MainActivity.IMAGEN_CATEGORIA_DONDE_ESTA), imagen_categoria_donde_esta);
// Capture ListView item click
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
String tipo_de_menu = resultp.get(DondeEsta_MainActivity.TIPO_MENU);
Log.i("TIPO DE MENU =", tipo_de_menu);
if (tipo_de_menu.equals("1")){
Log.i("PULSADO =", tipo_de_menu);
//TIPO 1
String idPrueba = resultp.get(DondeEsta_MainActivity.ID_CATEGORIA_DONDE_ESTA);
System.out.println("la id en DONDEESTA_LV ANTES DE PASARLA A T1 ++++++++++++++++++ ES: " + idPrueba);
Intent intent = new Intent(context, DondeEsta_T1_MainActivity.class);
intent.putExtra("idPrueba", idPrueba);
context.startActivity(intent);
}
else
//TIPO 2
if (tipo_de_menu.equals("2")){
Log.i("PULSADO =", tipo_de_menu);
//TIPO 2
String idPrueba = resultp.get(DondeEsta_MainActivity.ID_CATEGORIA_DONDE_ESTA);
System.out.println("la id en DONDEESTA_LV ANTES DE PASARLA A T1 ++++++++++++++++++ ES: " + idPrueba);
Intent intent = new Intent(context, DondeEsta_T2_MainActivity.class);
intent.putExtra("idPrueba", idPrueba);
context.startActivity(intent);
}
else {
Intent intent = new Intent(context, DondeEsta_SingleItemView.class);
}
}
});
return itemView;
}
}
ACTIVITY 2 MAIN ACTIVITY
import java.util.ArrayList;
import java.util.HashMap;
import java.util.StringTokenizer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
public class DondeEsta_T1_MainActivity extends Activity {
// Declare Variables
private static final String TAG_NAME = "nombreCategoria";
private static final String TAG_ID = "idPrueba";
private String name = "Categoria";
private String id = "id";
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
DondeEsta_T1_ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String ID_DES= "id_des";
static String TITULO_DES = "titulo_des";
static String CATEGORIAS_DES = "categoria_des";
static String LUGAR_DES = "lugar_des";
static String LATITUD_DES = "latitud_des";
static String LONGITUD_DES = "longitud_des";
static String IMAGEN_DES = "imagen_des";
static String DESCRIPCION_DES = "descripcion_des";
static String WEB_DES = "web_des";
static String MAIL_DES = "mail_des";
static String TEL_DES = "tel_des";
static String LUGAR_CORTO = "lugar_corto";
static String idPrueba = "idPrueba";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v("MVASCO", "context is null!");
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
name = in.getStringExtra(TAG_NAME);
id = in.getStringExtra(TAG_ID);
idPrueba =in.getStringExtra(idPrueba);
setContentView(R.layout.dondeesta_t1_listview_main);
// Execute DownloadJSON AsyncTask
//new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
// Log.v("categoria para pasar a la URL", id_categoria_donde_esta);
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://..URL hidden.../casajuventud/app_php_files/recuperar_categorias_donde_esta_t1.php?cat="+idPrueba);
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("Categorias");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("id_des", jsonobject.getString("id_des"));
map.put("titulo_des", jsonobject.getString("titulo_des"));
map.put("categoria_des", jsonobject.getString("categoria_des"));
map.put("lugar_des", jsonobject.getString("lugar_des"));
map.put("latitud_des", jsonobject.getString("latitud_des"));
map.put("longitud_des", jsonobject.getString("longitud_des"));
map.put("descripcion_des", jsonobject.getString("descripcion_des"));
map.put("web_des", jsonobject.getString("web_des"));
map.put("mail_des", jsonobject.getString("mail_des"));
map.put("imagen_des", "http://www.solinpromex.com/casajuventud/sitios/"+jsonobject.getString("imagen_des"));
map.put("tel_des", jsonobject.getString("tel_des"));
map.put("lugar_corto", jsonobject.getString("lugar_corto"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new DondeEsta_T1_ListViewAdapter(DondeEsta_T1_MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
new DownloadJSON().execute();
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
}
}
ACTIVITY 2 LISTVIEWADAPTER
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class DondeEsta_T1_ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public DondeEsta_T1_ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView id_des;
TextView titulo_des;
TextView categoria_des;
TextView lugar_des;
TextView latitud_des;
TextView longitud_des;
ImageView imagen_des;
TextView descripcion_des;
TextView web_des;
TextView tel_des;
TextView lugar_corto;
TextView mail_des;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.dondeesta_t1_listview_item, parent, false);
// Get the position
resultp = data.get(position);
RelativeLayout myLayout = (RelativeLayout) itemView.findViewById(R.id.milayout);
if (position % 2 == 1) {
myLayout.setBackgroundResource(R.color.fondo);
//lugar_evento.setBackgroundResource(R.color.fondo);
} else {
myLayout.setBackgroundResource(R.color.blanco);
//titulo_evento.setBackgroundResource(R.color.blanco);
//lugar_evento.setBackgroundResource(R.color.blanco);
}
String tipo_de_menu = resultp.get(DondeEsta_MainActivity.TIPO_MENU);
// Locate the TextViews in listview_item.xml
titulo_des = (TextView) itemView.findViewById(R.id.textView1);
lugar_corto = (TextView) itemView.findViewById(R.id.textView2);
titulo_des.setText (resultp.get(DondeEsta_T1_MainActivity.TITULO_DES));
lugar_corto.setText (resultp.get(DondeEsta_T1_MainActivity.LUGAR_CORTO));
// imageLoader.DisplayImage(resultp.get(DondeEsta_MainActivity.IMAGEN_CATEGORIA_DONDE_ESTA), imagen_categoria_donde_esta);
// Capture ListView item click
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, DondeEsta_T1_SingleItemView.class);
// Pass all data rank
intent.putExtra("titulo_des", resultp.get(DondeEsta_T1_MainActivity.TITULO_DES));
intent.putExtra("lugar_des", resultp.get(DondeEsta_T1_MainActivity.LUGAR_DES));
intent.putExtra("latitud_des", resultp.get(DondeEsta_T1_MainActivity.LATITUD_DES));
intent.putExtra("longitud_des", resultp.get(DondeEsta_T1_MainActivity.LONGITUD_DES));
intent.putExtra("imagen_des", resultp.get(DondeEsta_T1_MainActivity.IMAGEN_DES));
intent.putExtra("descripcion_des", resultp.get(DondeEsta_T1_MainActivity.DESCRIPCION_DES));
intent.putExtra("web_des", resultp.get(DondeEsta_T1_MainActivity.WEB_DES));
intent.putExtra("tel_des", resultp.get(DondeEsta_T1_MainActivity.TEL_DES));
intent.putExtra("mail_des", resultp.get(DondeEsta_T1_MainActivity.MAIL_DES));
intent.putExtra("lugar_corto", resultp.get(DondeEsta_T1_MainActivity.LUGAR_CORTO));
// Start SingleItemView Class
context.startActivity(intent);
}
});
return itemView;
}
}
just put
#Override
public void onBackPressed(){
finish();
}
somewhere inside second Activity.
also after idPrueba =in.getStringExtra(idPrueba); you might try in.removeExtra("idPrueba");
and the last: why idPrueba is static? code key as other variable, static final, and get your passed value to another variable. when you starting second Activity for the first time you fetching newly arrived varriable and assigning it to key variable. this value is static, so second call of Activity have previosly overwritten key (not "idPrueba", but value of previously passed variable under "idPrueba" key). probably this is your issue
for this code the easiest way is to remove static before String idPrueba = "idPrueba"; but I suggest you to separate key and value variables. also check setOnItemClickListener method, more convenient

Issues with Filtering listview with edittext

Hello I'm working on an app which has an edittext to search for items on the listview. If the user types a letter in the edittext the listview is getting filtered perfectlty.Have used Adapter also.Now i have following issues:
1)when i m clearing letters edittext my listview is not getting Updated..
2) if i enter wrong letter or letter which does not corrorsponds to any item of a listview the listview is getting clear.
Have gone thorugh exmaples in SO
Android filter listview custom adapter
And googled also for same problem but not getting solved it..Plz anybody help me..
Here is my code:
package com.AAAAA.AAAAA;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.AdapterView.OnItemClickListener;
import com.AAAAA.adapter.UpdateSingleItemViewActivity;
import com.AAAAA.adapter.UpdatesAdapterList;
import com.AAAAA.local.database.DBController;
import com.AAAAA.AAAAA.AAAAA.constant.Constant;
import com.AAAAA.AAAAA.AAAAA.utils.Utility;
public class Cardiology_updates extends Activity implements OnClickListener,
OnRefreshListener {
EditText et ;
private Context appContext;
// ProgressDialog mProgressDialog;
private Dialog dialog;
private boolean isFinish = false;
String result = "";
JSONObject jsonobject;
JSONArray jsonArray;
ArrayList<HashMap<String, String>> UpdatesHmList;
public static ArrayList<HashMap<String, String>> FinalLocalDataList;
ArrayList<HashMap<String, String>> LocalDataList;
DBController controller = new DBController(this);
HashMap<String, String> queryValues;
ListView list;
UpdatesAdapterList adapter;
public static String UpdateID = "UpdateID";
public static String UpdateTitle = "Title";
/*
* public static String UpdateDescription = "Description"; public static
* String POPULATION = "UpdateDate"; public static String UpdateImage =
* "Photo";
*/
public static String UpdateDescription = "Description";
public static String POPULATION = "Title";
public static String UpdateImage = "Complete_imagePath";
public static String Complete_imagePath;
public static String Title;
public static String Description;
SwipeRefreshLayout swipeLayout;
private ProgressBar progressbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cardiology_updates);
// controller.deleteAllJsonData();
appContext = this;
animationView();
initComponent();
}
private void animationView() {
// TODO Auto-generated method stub
progressbar = (ProgressBar) findViewById(R.id.loading);
}
private void initComponent() {
// TODO Auto-generated method stub
swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
dialog = new Dialog(appContext);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.alert_dialog);
((Button) findViewById(R.id.Button01)).setOnClickListener(this);
((Button) dialog.findViewById(R.id.btnOk)).setOnClickListener(this);
new GetUpdatesInfo().execute();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.Button01) {
finish();
// finishActivity() ;
} else if (v.getId() == R.id.btnOk) {
dialog.dismiss();
if (isFinish) {
this.finish();
}
}
}
public class GetUpdatesInfo extends AsyncTask<String, Void, String> {
protected void onPreExecute() {
super.onPreExecute();
if (progressbar.getVisibility() != View.VISIBLE) {
progressbar.setVisibility(View.VISIBLE);
}
}
#Override
protected String doInBackground(String... params) {
// Create an array
UpdatesHmList = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
String url = null;
url = Constant.serverUrl + "/GetUpdateList";
result = Utility.postParamsAndfindJSON(url);
Log.e("result doInBackground", "" + result);
if (!(result == null)) {
try {
controller.deleteAllJsonData();
// Locate the array name in JSON
jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonArray.getJSONObject(i);
// Retrive JSON Objects
map.put("UpdateID", jsonobject.getString("UpdateID"));
map.put("Title", jsonobject.getString("Title"));
String Upadates_Photo = jsonobject.optString("Photo")
.toString();
String Complete_imagePath = Constant.prifixserverUrl
+ Upadates_Photo;
String Title = jsonobject.getString("Title").toString();
String Description = jsonobject
.getString("Description").toString();
String noHtml = Description.replaceAll("<[^>]*>", "");
String parseResponse = noHtml.replaceAll(" ", "");
map.put("Photo", Complete_imagePath);
map.put("Description", Description);
map.put("UpdateDate",
jsonobject.getString("UpdateDate"));
Log.e("UpdateID ",
" "
+ jsonobject.getString("UpdateID")
.toString());
Log.e("Title ", " "
+ jsonobject.getString("Title").toString());
Log.e("Complete_imagePath ",
" " + Complete_imagePath.toString());
Log.e("Description ", " " + parseResponse);
Log.e("UpdateDate ",
" "
+ jsonobject.getString("UpdateDate")
.toString());
queryValues = new HashMap<String, String>();
queryValues.put("Complete_imagePath",
Complete_imagePath);
queryValues.put("Title", Title);
queryValues.put("Description", Description);
controller.insertAllJsonData(queryValues);
// Set the JSON Objects into the array
UpdatesHmList.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
return result;
}
#Override
protected void onPostExecute(String result) {
// Locate the listview in listview_main.xml
if (progressbar.getVisibility() == View.VISIBLE) {
progressbar.setVisibility(View.GONE);
}
/*
* if (result == null) { //mProgressDialog.dismiss();
* localalldata();
*
* }
*/
localalldata();
/*
* list = (ListView) findViewById(R.id.list_Upadates); // Pass the
* results into ListViewAdapter.java adapter = new
* UpdatesAdapterList(Cardiology_updates.this, FinalLocalDataList);
* // Set the adapter to the ListView list.setAdapter(adapter);
*/
// Close the progressdialog
// mProgressDialog.dismiss();
}
}
#Override
public void onRefresh() {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
getSomeData();
// localalldata();
swipeLayout.setRefreshing(false);
}
}, 5000);
}
protected void getSomeData() {
// TODO Auto-generated method stub
// localalldata();
new GetUpdatesInfo().execute();
adapter.notifyDataSetChanged();
/*
* if (LocalDataList == null) { Log.e("LocalDataList inside if ",
* "LocalDataList inside if "); new GetUpdatesInfo().execute();
*
* } else { // adapter.imageLoader.clearCache();
* Log.e("LocalDataList else ", "LocalDataList else ");
*
* adapter.notifyDataSetChanged(); }
*/
}
private void localalldata() {
// TODO Auto-generated method stub
LocalDataList = controller.getAllJsonData();
FinalLocalDataList = new ArrayList<HashMap<String, String>>();
for (HashMap<String, String> hashMap : LocalDataList) {
System.out.println(hashMap.keySet());
HashMap<String, String> map = new HashMap<String, String>();
for (String key : hashMap.keySet()) {
System.out.println(hashMap.get(key));
Complete_imagePath = hashMap.get("Complete_imagePath");
Title = hashMap.get("Title");
Description = hashMap.get("Description");
map.put("Complete_imagePath", Complete_imagePath);
map.put("Title", Title);
map.put("Description", Description);
Log.v("All Json CodiateUpdate Title", "" + Complete_imagePath);
Log.v("All Json CodiateUpdate Title", "" + Title);
}
FinalLocalDataList.add(map);
}
list = (ListView) findViewById(R.id.list_Upadates);
// Pass the results into ListViewAdapter.java
adapter = new UpdatesAdapterList(Cardiology_updates.this,
FinalLocalDataList);
// Set the adapter to the ListView
list.setTextFilterEnabled(true);
list.setAdapter(adapter);
// adapter.notifyDataSetChanged();
et = (EditText) findViewById(R.id.search);
// Capture Text in EditText
et.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
adapter.filter(arg0.toString());
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
//String text = et.getText().toString().toLowerCase(Locale.getDefault());
//adapter.getFilter().filter(arg0);
}
});
}
}
Here is my Adapter:
package com.AAAA.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import com.AAAA.AAAA.Cardiology_updates;
import com.AAAA.AAAA.R;
import com.AAAA.imageloader.ImageLoader;
public class UpdatesAdapterList extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
public ImageLoader imageLoader;
private Activity activity;
//HashMap<String, String> resultp = new HashMap<String, String>();
private ArrayList<HashMap<String,String>> filterData;
public UpdatesAdapterList(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context.getApplicationContext());
filterData = new ArrayList<HashMap<String,String>>();
filterData.addAll(this.data);
}
#Override
public int getCount() {
return filterData.size();
}
#Override
public Object getItem(int position) {
return filterData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.listview_updateitem, null);
holder.UpdateTitle = (TextView) convertView.findViewById(R.id.txtUpdatetitle);
holder.UpdateImage = (ImageView) convertView.findViewById(R.id.list_UpdateImage);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.UpdateTitle.setText(filterData.get(position).get(Cardiology_updates.UpdateTitle));
imageLoader.DisplayImage(filterData.get(position).get(Cardiology_updates.UpdateImage), holder.UpdateImage);
// Capture ListView item click
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
//resultp = data.get(position);
Intent intent = new Intent(context, UpdateSingleItemViewActivity.class);
// Pass all data rank
intent.putExtra("UpdateTile", filterData.get(position).get(Cardiology_updates.UpdateTitle));
// Pass all data country
intent.putExtra("UpdateDescription", filterData.get(position).get(Cardiology_updates.UpdateDescription));
// Pass all data population
intent.putExtra("population",filterData.get(position).get(Cardiology_updates.POPULATION));
// Pass all data flag
intent.putExtra("UpdateImage", filterData.get(position).get(Cardiology_updates.UpdateImage));
// Start SingleItemView Class
intent.putExtra("position", position);
context.startActivity(intent);
}
}); return convertView;
}
class ViewHolder{
TextView UpdateTitle;
ImageView UpdateImage;
}
public void filter(String constraint) {
filterData.clear();
if (constraint.length() == 0) {
filterData.addAll(data);
}else{
for (HashMap<String,String> row: data) {
if(row.get(Cardiology_updates.UpdateTitle).toUpperCase().startsWith(constraint.toString().toUpperCase())){
filterData.add(row);
}
}
}
notifyDataSetChanged();
}
}
Activity opens on cliking listview items:
package com.AAAAA.adapter;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import com.AAAAA.AAAAA.Cardiology_updates;
import com.AAAAA.AAAAA.R;
public class UpdateSingleItemViewActivity extends Activity {
int position;
String UpdateTile;
String UpdateDescription;
String population;
String UpdateImage;
//String position;
ViewPager viewPager;
PagerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_update_single_item_view);
Log.e("UpdateSingleItemViewActivity class",
"UpdateSingleItemViewActivity class");
/*
* WebView webview = new WebView(this); setContentView(webview);
*/
Button btnback = (Button) findViewById(R.id.Button01);
btnback.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
//WebView webview = (WebView) findViewById(R.id.webview);
Intent i = getIntent();
// Get the result of rank
UpdateTile = i.getStringExtra("UpdateTile");
// Get the result of country
UpdateDescription = i.getStringExtra("UpdateDescription");
// Get the result of population
population = i.getStringExtra("population");
// Get the result of flag
UpdateImage = i.getStringExtra("UpdateImage");
//i.putExtra("POSITION_KEY", position);
position = i.getExtras().getInt("position");
//webview.loadData(UpdateDescription, "text/html", null);
viewPager = (ViewPager) findViewById(R.id.viewpager_layout);
// Pass results to ViewPagerAdapter Class
adapter = new ViewPagerAdapter(UpdateSingleItemViewActivity.this, Cardiology_updates.FinalLocalDataList);
// Binds the Adapter to the ViewPager
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(position);
}
}
its Corrosponding adapter:
package com.AAAAA.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import com.AAAAA.AAAAA.Cardiology_updates;
import com.AAAAA.AAAAA.R;
import com.AAAAA.imageloader.ImageLoader;
import android.app.Activity;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.LinearLayout;
public class ViewPagerAdapter extends PagerAdapter {
String UpdateTile;
String UpdateDescription;
//String population;
String UpdateImage;
String position;
LayoutInflater inflater;
Context context;
ArrayList<HashMap<String, String>> data;
public ImageLoader imageLoader;
private Activity activity;
//HashMap<String, String> resultp = new HashMap<String, String>();
ArrayList<HashMap<String,String>> filterData;
public ViewPagerAdapter(Context context, ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
filterData = new ArrayList<HashMap<String,String>>();
filterData.addAll(this.data);
}
#Override
public int getCount() {
return filterData.size();
}
public Object getItem(int position) {
return filterData.get(position);
}
public long getItemId(int position) {
return position;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((LinearLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
WebView webview;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.viewpager_item, container,
false);
//resultp =data.get(position);
webview=(WebView)itemView.findViewById(R.id.webview1);
//webview.setText(webview[position]);
webview.loadData(filterData.get(position).get(Cardiology_updates.UpdateDescription), "text/html", null);
((ViewPager) container).addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// Remove viewpager_item.xml from ViewPager
((ViewPager) container).removeView((LinearLayout) object);
}
}
When used custom adapter always try to implement ViewHolder design pattern for ListView performance and use custom filter function instead Filterable implementation :
Custom filter funcation required two array list one is filterable data list and another one is for orignal data list :
public void filter(String constraint) {
filterData.clear();
if (constraint.length() == 0) {
filterData.addAll(orignalData);
}else{
for (HashMap<String,String> row: orignalData) {
if(row.get(Cardiology_updates.UpdateTitle).toUpperCase().startsWith(constraint.toString().toUpperCase())){
filterData.add(row);
}
}
}
notifyDataSetChanged();
}
Example :
et.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
adapter.filter(arg0.toString());
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,int arg2, int arg3) {
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,int arg3) {
}
});
public class UpdatesAdapterList extends BaseAdapter {
private Context context;
private ArrayList<HashMap<String,String>> filterData;
private ArrayList<HashMap<String,String>> orignalData;
public ImageLoader imageLoader;
public UpdatesAdapterList(Context context,ArrayList<HashMap<String, String>> orignalData) {
this.context = context;
this.orignalData = orignalData;
filterData = new ArrayList<HashMap<String,String>>();
filterData.addAll(this.orignalData);
imageLoader = new ImageLoader(this.context);
}
#Override
public int getCount() {
return filterData.size();
}
#Override
public Object getItem(int position) {
return filterData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.listview_updateitem, null);
holder.UpdateTitle = (TextView) convertView.findViewById(R.id.txtUpdatetitle);
holder.UpdateImage = (ImageView) convertView.findViewById(R.id.list_UpdateImage);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.UpdateTitle.setText(filterData.get(position).get(Cardiology_updates.UpdateTitle));
imageLoader.DisplayImage(filterData.get(position).get(Cardiology_updates.UpdateImage), holder.UpdateImage);
// Capture ListView item click
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context, UpdateSingleItemViewActivity.class);
// Pass all data rank
intent.putExtra("UpdateTile", filterData.get(position).get(Cardiology_updates.UpdateTitle));
// Pass all data country
intent.putExtra("UpdateDescription", filterData.get(position).get(Cardiology_updates.UpdateDescription));
// Pass all data population
intent.putExtra("population",filterData.get(position).get(Cardiology_updates.POPULATION));
// Pass all data flag
intent.putExtra("UpdateImage", filterData.get(position).get(Cardiology_updates.UpdateImage));
// Start SingleItemView Class
intent.putExtra("position", position);
context.startActivity(intent);
}
});
return convertView;
}
class ViewHolder{
TextView UpdateTitle;
ImageView UpdateImage;
}
public void filter(String constraint) {
filterData.clear();
if (constraint.length() == 0) {
filterData.addAll(orignalData);
}else{
for (HashMap<String,String> row: orignalData) {
if(row.get(Cardiology_updates.UpdateTitle).toUpperCase().startsWith(constraint.toString().toUpperCase())){
filterData.add(row);
}
}
}
notifyDataSetChanged();
}
}

i need to change my listview to extend baseAdapter using the ArrayList<HashMap<String, String>>

i have an activity that use list view and display values after fetching from mysql database the application work fine but now i wnat to changed the list activity to extends BaseAdapter because i need to add in the row 2 text view.
can anyone help me to make this change ????
this is my code
User.java
package com.devleb.loginDemo;
import java.util.Date;
public class User {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
Date date;
}
CustomAdapter.java
package com.devleb.loginDemo;
import java.util.ArrayList;
import java.util.Date;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class CustomAdapter extends BaseAdapter {
private static ArrayList<User> usersList;
// private static ArrayList name, date;
LayoutInflater layoutInflater;
String[] userName;
Date[] createdDate;
Context context;
public CustomAdapter(ArrayList<User> result, Context c) {
usersList = result;
context = c;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return usersList.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return usersList.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int position, View arg1, ViewGroup parent) {
// TODO Auto-generated method stub
layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = null;
row = layoutInflater.inflate(R.layout.list_item, parent, false);
TextView txtCreateDate = (TextView) row
.findViewById(R.id.txtCreateDate);
txtCreateDate.setText(usersList.get(position).getDate().toString());
TextView txtName = (TextView) row.findViewById(R.id.name);
txtName.setText(usersList.get(position).getName());
return row;
}
}
now how to add this custom adapter to my UserListActivity ???
UserListActivity.java
package com.devleb.loginDemo;
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.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
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;
import android.widget.TextView;
import android.widget.Toast;
public class UserListActivity extends ListActivity {
JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> usersList;
private static String url_display_user = "http://10.0.3.2/android_connect/display_user.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private static final String TAG_ID = "id";
private static final String TAG_USERS = "userlist";
private static final String TAG_USER = "user";
private static final String TAG_DATE = "create_date";
// private static final String TAG_NAME = "name";
// employees JSONArray
JSONArray users = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_list);
usersList = new ArrayList<HashMap<String, String>>();
new getUserList().execute();
// getListView
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
// String id = ((TextView)
// view.findViewById(R.id.uid)).getText()
// .toString();
// Intent in = new Intent(getBaseContext(), StatusList.class);
// in.putExtra(TAG_ID, uid);
// startActivity(in);
}
});
}
class getUserList extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
UserListActivity.this.setProgressBarIndeterminateVisibility(true);
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
// Building Parameters
List<NameValuePair> parametres = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jsonParser.makeHttpRequest(url_display_user,
"GET", parametres);
// Check your log cat for JSON reponse
Log.d("All Users: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
users = json.getJSONArray(TAG_USERS);
// looping through All Users
for (int i = 0; i < users.length(); i++) {
JSONObject c = users.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String user = c.getString(TAG_USER);
// 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_USER, user);
// adding HashList to ArrayList
usersList.add(map);
}
return json.getString(TAG_MESSAGE);
} else {
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String result) {
// dismiss the dialog after getting all products
if (result != null) {
UserListActivity.this
.setProgressBarIndeterminateVisibility(false);
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(UserListActivity.this,
usersList, R.layout.list_item, new String[] { TAG_ID,
TAG_USER }, new int[] { R.id.uid, R.id.name });
// updating listview
setListAdapter(adapter);
Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG)
.show();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.user_list, menu);
return true;
}
}
i know that the change must be done in OnPostExecute()
Is that your problem??
public class CustomAdapter extends BaseAdapter {
private static ArrayList<User> usersList;
// private static ArrayList name, date;
LayoutInflater layoutInflater;
String[] userName;
Date[] createdDate;
Context context;
public CustomAdapter(ArrayList<HashMap<String,String> result, Context c) {
usersList = result;
context = c;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return usersList.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return usersList.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int position, View arg1, ViewGroup parent) {
//Get the HashMap
HashMap<String,String> map = userList.get(position);
//do what ever you want with the hashmap
return row;
}
}

ListView not refreshed on Adapter Load

I have a tab host that loads following file into one of the tabs
package com.api.view;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import com.api.api.api;
import com.api.app.R;
import com.api.communication.reports;
import com.api.sync.data.reportsList;
import com.api.tools.serverCommunication;
import com.api.tools.urlbuilder;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class EquipmentTabHistory extends Activity{
ListView lv;
ListViewAdapter adapter;
ArrayList<HashMap<String, String>> menuItems;
ProgressDialog pDialog;
static final String KEY_ITEM = "item"; // parent node
static final String KEY_ID = "id";
static final String KEY_NAME = "name";
private class ListViewAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private LayoutInflater inflater=null;
public ListViewAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.list_item, null);
TextView name = (TextView)vi.findViewById(R.id.name);
HashMap<String, String> item = new HashMap<String, String>();
item = data.get(position);
//Setting all values in listview
name.setText(item.get("name"));
return vi;
}
}
private class loadMoreListView extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... unused) {
try {
reportsList al;
int eid = Integer.parseInt(getIntent().getStringExtra("eid"));
String[][] surl = new String[1][2];
surl[0][0] = "eid";
surl[0][1] = ""+eid;
String url;
url = urlbuilder.buildurl("getEquipmentHistory", surl);
api.debug("com.api.view.EquipmentTabHistory","URL: "+url,"info");
String pull = serverCommunication.pull(url);
reports reports;
reports = new reports(pull);
for(int i=0;i<reports.getList().size();i++){
al = reports.getList().get(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put(KEY_ID,reports.getList().get(i).did);
long timestamp = Integer.parseInt(al.date) * 1000; // msec
java.util.Date d = new java.util.Date(timestamp);
map.put(KEY_NAME,al.ReportId + " - "+al.Typ + " - " + al.description + "("+d.getMonth()+". "+cT(d.getDay())+" "+(1900 + d.getYear())+" - "+d.getHours()+":"+cT(d.getMinutes())+")");
menuItems.add(map);
}
} catch (Exception e) {
api.debug("com.api.view.EquipmentTabHistory","NSAE: "+e.getMessage(),"error");
}
return (null);
}
private String cT(int time){
String r = "";
r += (time>9)?time:(time>0)?"0"+time:time;
return r;
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.api_tab_history);
lv = (ListView) findViewById(R.id.listViewEquipment);
menuItems = new ArrayList<HashMap<String, String>>();
adapter = new ListViewAdapter(this, menuItems);
lv.setAdapter(adapter);
new loadMoreListView().execute();
lv.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
api.debug("com.api.view.EquipmentTabHistory","Clicked: "+arg2+"-"+arg3,"warn");
api.debug("com.api.view.EquipmentTabHistory","Clicked: "+((TextView)findViewById(R.id.name)).getText().toString(),"warn");
api.debug("com.api.view.EquipmentTabHistory","Selected: "+menuItems.get(arg2).get(KEY_ID),"warn");
String[][] surl = new String[2][2];
surl[0][0] = "did";
surl[0][1] = menuItems.get(arg2).get(KEY_ID);
surl[1][0] = "eid";
surl[1][1] = getIntent().getStringExtra("eid");
String docurl;
try {
docurl = urlbuilder.buildurlNoXml("getDocument",surl,true);
api.debug(com.api.view.EquipmentTabHistory.class.toString(),"URL: "+docurl,"info");
System.out.println(docurl);
Intent browser = new Intent(Intent.ACTION_VIEW , Uri.parse( docurl ) );
startActivity(browser);
} catch (NoSuchAlgorithmException e) {
api.debug("com.api.view.EquipmentTabHistory","No Such Algorithm "+e.getMessage(),"error");
}
}
});
}
}
The page loads without any exceptions.
In the log (through api.debug) I can see that the file is loaded and also that it get's parsed.
But I have to switch the tabs to see the changes.
How should I modify the code that it refreshes the listview as soon as the async method stops to load?
You have to override another method onPostExecute() inside AsyncTask like this:
#Override
protected Void onPostExecute(Void... unused) {
adpater.notifyDatasetChanged(); // will tell the adapter to refresh itself
}

Categories

Resources