android - ListView Item not showing in fragment - android

I have Navigation Drawer with Fragment.
I set custom ListView from URL In Fragment.
But when I am running this, Items in ListView are not showing .
Data shows in log cat as well. i donot get any error on logcat
Fragment:
public class HomeFragment extends Fragment {
JSONArray post = null;
private ArrayList<HashMap<String, String>> PostList = new ArrayList<HashMap<String, String>>();
private View rootView;
private ListView list;
private StringRequest sr;
private RequestQueue queue;
private JSONArray laporanListObj;
private int Jumlah_list_Data;
private Adapter_Post adapter;
private Animation animstatuskoneksi;
private TextView statusKoneksi;
private ImageView nodata;
private ProgressBar load;
private Handler handler;
public HomeFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_home, container, false);
// adapter list
adapter = new Adapter_Post(getActivity(), PostList);
// animasi
animstatuskoneksi = AnimationUtils.loadAnimation(getActivity(),
R.anim.anim_status_koneksi);
// View Declare
list = (ListView) rootView.findViewById(android.R.id.list);
statusKoneksi = (TextView) rootView.findViewById(R.id.status_koneksi);
nodata = (ImageView) rootView.findViewById(R.id.NoData);
load = (ProgressBar) rootView.findViewById(R.id.load);
// set adapter
list.setAdapter(adapter);
// Listview on item click listener
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
TextView judul = (TextView) view.findViewById(R.id.judul);
TextView waktu_post = (TextView) view
.findViewById(R.id.waktu_post);
TextView id_post = (TextView) view.findViewById(R.id.id_post);
TextView link_detail_post = (TextView) view
.findViewById(R.id.link_detail_post);
String var_judul = judul.getText().toString();
String var_waktu_post = waktu_post.getText().toString();
String var_id_post = id_post.getText().toString();
String var_link_detail_post = link_detail_post.getText()
.toString();
// Starting single contact activity
// Intent in = new Intent(getActivity(), DetailActivity.class);
// in.putExtra(Variabel.KEY_JUDUL, var_judul);
// in.putExtra(Variabel.KEY_WAKTU_POST, var_waktu_post);
// in.putExtra(Variabel.KEY_ID_POST, var_id_post);
// in.putExtra(Variabel.KEY_LINK_DETAIL_POST,
// var_link_detail_post);
// startActivity(in);
Toast.makeText(getActivity(), "oke", Toast.LENGTH_LONG).show();
}
});
// Calling async task to get json
GetDataPost(Variabel.url_post);
return rootView;
}
public void GetDataPost(String url) {
if (queue != null) {
queue.cancelAll(sr);
}
// adapter.delete_all();
load.setVisibility(View.VISIBLE);
Log.v("Get Data", url);
queue = Volley.newRequestQueue(getActivity());
sr = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.v("hasil", response);
load.setVisibility(View.GONE);
DrawData(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NetworkError) {
statusKoneksi("Koneksi bermasalah");
} else if (error instanceof ServerError) {
statusKoneksi("Server Error");
} else if (error instanceof AuthFailureError) {
statusKoneksi("Koneksi Timeout");
} else if (error instanceof ParseError) {
statusKoneksi("Ada masalah dalam mengambil data");
} else if (error instanceof NoConnectionError) {
statusKoneksi("Tidak ada koneksi");
} else if (error instanceof TimeoutError) {
statusKoneksi("Koneksi Timeout");
}
load.setVisibility(View.GONE);
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> jsonParams = new HashMap<String, String>();
jsonParams.put("tag", Variabel.tag_default);
return jsonParams;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
};
queue.add(sr);
}
protected void DrawData(String response) {
JSONObject json = null;
try {
json = new JSONObject(response);
String res = json.getString(Variabel.KEY_SUCCESS);
String msg_err = json.getString(Variabel.KEY_ERROR_MSG);
if (Integer.parseInt(res) == 1) {
laporanListObj = json.getJSONArray(Variabel.KEY_POST);
Jumlah_list_Data = laporanListObj.length();
if (Jumlah_list_Data > 0) {
// count_data.setText(Jumlah_list_Data+" Data");
list.setVisibility(View.VISIBLE);
nodata.setVisibility(View.GONE);
for (int i = 0; i < Jumlah_list_Data; i++) {
JSONObject c = laporanListObj.getJSONObject(i);
// Storing each json item in variable
Variabel.judul_post = c.getString(Variabel.KEY_JUDUL);
Variabel.waktu_post = c
.getString(Variabel.KEY_WAKTU_POST);
Variabel.id_post = c.getString(Variabel.KEY_ID_POST);
Variabel.link_detail_post = c
.getString(Variabel.KEY_LINK_DETAIL_POST);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(Variabel.KEY_JUDUL, Variabel.judul_post);
map.put(Variabel.KEY_WAKTU_POST, Variabel.waktu_post);
map.put(Variabel.KEY_ID_POST, Variabel.id_post);
map.put(Variabel.KEY_LINK_DETAIL_POST,
Variabel.link_detail_post);
// adding HashList to ArrayList
PostList.add(map);
}
adapter.notifyDataSetChanged();
}
} else {
list.setVisibility(View.GONE);
nodata.setVisibility(View.VISIBLE);
statusKoneksi(msg_err);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Listview Adapter:
public class Adapter_Post extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private ImageLoaderDetailImage ImageLoader;
private int loader;
private static LayoutInflater inflater = null;
public Adapter_Post(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ImageLoader = new ImageLoaderDetailImage(activity.getBaseContext());
loader = R.drawable.ic_drawer;
}
public int getCount() {
return data.size();
}
public void delete_all() {
int count = getCount();
if (count > 0) {
data.clear();
notifyDataSetChanged();
}
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/* private view holder class */
private class ViewHolder {
public TextView judul;
public TextView waktu_post;
public TextView id_post;
public TextView link_detail_post;
// public RoundedImageView foto_bus;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View vi = convertView;
final ViewHolder holder;
if (convertView == null) {
vi = inflater.from(activity)
.inflate(R.layout.list_item, null, true);
holder = new ViewHolder();
// holder.foto_bus =
// (RoundedImageView)vi.findViewById(R.id.foto_bus);
holder.judul = (TextView) vi.findViewById(R.id.judul);
holder.waktu_post = (TextView) vi.findViewById(R.id.waktu_post);
holder.id_post = (TextView) vi.findViewById(R.id.id_post);
holder.link_detail_post = (TextView) vi
.findViewById(R.id.link_detail_post);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
HashMap<String, String> kendaraan = new HashMap<String, String>();
kendaraan = data.get(position);
// set data
holder.judul.setText(kendaraan.get(Variabel.KEY_JUDUL));
holder.waktu_post.setText(kendaraan.get(Variabel.KEY_WAKTU_POST));
holder.id_post.setText(kendaraan.get(Variabel.KEY_ID_POST));
holder.link_detail_post.setText(kendaraan
.get(Variabel.KEY_LINK_DETAIL_POST));
// ImageLoader.DisplayImage(kendaraan.get(Variabel.KEY_FOTO_BUS),loader,
// holder.foto_bus);
return vi;
}
}
UPDATED
Fragment XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#null"
android:cacheColorHint="#android:color/transparent"
android:divider="#android:color/transparent"
android:dividerHeight="1px"
android:listSelector="#null"
android:visibility="visible" >
</ListView>
<ProgressBar
android:id="#+id/load"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
<ImageView
android:id="#+id/NoData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:background="#null"
android:src="#drawable/nodata"
android:visibility="visible" />
<TextView
android:id="#+id/status_koneksi"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:background="#99000000"
android:gravity="center"
android:padding="8dp"
android:text="msg."
android:textColor="#ffffff"
android:visibility="visible" />
</RelativeLayout>
any mistake in my code ?
How to fix it ?
sorry for my english .. thanks

you should change this
list=(ListView)rootView.findViewById(android.R.id.list);
to
list=(ListView)rootView.findViewById(R.id.list);
and make sure you have ListView with id list in your fragment_home layout.

In getview method of adapter change the parameters of this:
vi = inflater.from(activity).inflate(R.layout.list_item, null, true);
to:
vi = inflater.from(activity).inflate(R.layout.list_item, parent, false);

Related

EditText AutoCompleteTextView When Typing Using Custom Adapter Json Fragment

I want EditText become AutoComplete when user start typing in the EditText field. I have create this code
public class PegawaiFragment extends Fragment {
public static PegawaiFragment newInstance() {
PegawaiFragment fragment = new PegawaiFragment();
return fragment;
}
String namapegawai;
AutoCompleteTextView textAutoComplete;
ListView StudentListView;
ProgressBar progressBar;
String HttpUrl = "http://192.168.43.241/Android/MyKoperasi/PegawaiDashboard.php";
List<String> IdList = new ArrayList<>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_pegawai, container, false);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
namapegawai = prefs.getString(MainActivity.UserName,MainActivity.UserName);
TextView NamaPegawai = v.findViewById(R.id.TextViewNamaPegawai);
NamaPegawai.setText(namapegawai);
textAutoComplete = v.findViewById(R.id.autoCompleteTextView1);
ArrayAdapter adapter = new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1);
textAutoComplete.setAdapter(adapter);
textAutoComplete.setThreshold(1);
StudentListView = v.findViewById(R.id.listview2);
progressBar = v.findViewById(R.id.progressBar1);
new GetHttpResponse(getActivity()).execute();
//Adding ListView Item click Listener.
StudentListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
//Intent intentSemuaMemberLihat = new Intent(getActivity(),SemuaMemberLihat.class);
// Sending ListView clicked value using intent.
//intentSemuaMemberLihat.putExtra("ListViewValue", IdList.get(position).toString());
//startActivity(intentSemuaMemberLihat);
}
});
return v;
}
// JSON parse class started from here.
class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
String JSonResult;
List<Member> studentList;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
// Passing HTTP URL to HttpServicesClass Class.
HttpServicesClass httpServicesClass = new HttpServicesClass(HttpUrl);
try
{
httpServicesClass.ExecutePostRequest();
if(httpServicesClass.getResponseCode() == 200)
{
JSonResult = httpServicesClass.getResponse();
if(JSonResult != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(JSonResult);
JSONObject jsonObject;
Member member;
studentList = new ArrayList<Member>();
for(int i=0; i<jsonArray.length(); i++)
{
member = new Member();
jsonObject = jsonArray.getJSONObject(i);
// Adding Student Id TO IdList Array.
IdList.add(jsonObject.getString("id").toString());
//Adding Student Name.
member.nama = jsonObject.getString("nama").toString();
//member.nrp = jsonObject.getString("nrp").toString();
studentList.add(member);
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else
{
Toast.makeText(context, httpServicesClass.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressBar.setVisibility(View.GONE);
StudentListView.setVisibility(View.VISIBLE);
if(studentList != null) {
ListAdapterClass adapter = new ListAdapterClass(studentList, context);
StudentListView.setAdapter(adapter);
}else
{
Toast.makeText(context, "Tidak ada data ditampilkan", Toast.LENGTH_SHORT).show();
}
}
}
}
This code shows perfect, but when I start typing in EditText which in autoCompleteTextView1, no suggestion name come out. I think this is in here
textAutoComplete = v.findViewById(R.id.autoCompleteTextView1);
ArrayAdapter adapter = new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1);
textAutoComplete.setAdapter(adapter);
textAutoComplete.setThreshold(1);
But why the EditText doesn't show the suggestions? instead, my ListView works perfect there.
Here is my XML code
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.network.poeja.mykoperasi.PegawaiFragment">
<TextView
android:id="#+id/TextViewNamaPegawai"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<AutoCompleteTextView
android:layout_weight="1"
android:id="#+id/autoCompleteTextView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Text Auto Complete"
android:layout_below="#+id/TextViewNamaPegawai">
<requestFocus />
</AutoCompleteTextView>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="50dp"
android:layout_below="#+id/autoCompleteTextView1">
<!-- TODO: Update blank fragment layout -->
<ListView
android:id="#+id/listview2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_below="#+id/logos"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dip"/>
<ProgressBar
android:id="#+id/progressBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="visible" />
</RelativeLayout>
</FrameLayout>
===============ADAPTER CLASS
public class ListAdapterClass extends BaseAdapter {
Context context;
List<Member> valueList;
public ListAdapterClass(List<Member> listValue, Context context)
{
this.context = context;
this.valueList = listValue;
}
#Override
public int getCount()
{
return this.valueList.size();
}
#Override
public Object getItem(int position)
{
return this.valueList.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewItem viewItem = null;
if(convertView == null)
{
viewItem = new ViewItem();
LayoutInflater layoutInfiater = (LayoutInflater)this.context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = layoutInfiater.inflate(R.layout.listview_item, null);
viewItem.TextViewNama = convertView.findViewById(R.id.textViewNama);
viewItem.TextViewNrp = convertView.findViewById(R.id.textViewNrp);
convertView.setTag(viewItem);
}
else
{
viewItem = (ViewItem) convertView.getTag();
}
viewItem.TextViewNama.setText(valueList.get(position).nama);
viewItem.TextViewNrp.setText(valueList.get(position).nrp);
return convertView;
}
}
class ViewItem
{
TextView TextViewNama, TextViewNrp;
}
You need to provide Array containing data on ArrayAdapter. Its the source of data where adapter will search. Here is an example how to use ArrayAdapter and AutoCompleteTextView -
public class MainActivity extends Activity {
String[] data = {"Apple", "Banana", "Cherry", "Date", "Grape", "Kiwi", "Mango", "Pear"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Creating the instance of ArrayAdapter containing list of fruit names
ArrayAdapter<String> adapter = new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1, data);
//Getting the instance of AutoCompleteTextView
AutoCompleteTextView actv = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
actv.setThreshold(1);//will start working from first character
actv.setAdapter(adapter);//setting the adapter data into the AutoCompleteTextView
actv.setTextColor(Color.RED);
}
}
Based on your code of AutoCompleteTextView. I made a solution.
String[] data = {"Apple", "Banana", "Cherry", "Date", "Grape", "Kiwi", "Mango", "Pear"};
GetHttpResponse getHttpResponse = new GetHttpResponse(getActivity());
getHttpResponse.execute();
textAutoComplete = v.findViewById(R.id.autoCompleteTextView1);
List<Member> studentList = getHttpResponse.getStudentList();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, studentList.toArray(new String[studentList.size()]));
textAutoComplete.setAdapter(adapter);
textAutoComplete.setThreshold(1);
Add a method to get studentList from GetHttpResponse class -
// JSON parse class started from here.
class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
String JSonResult;
List<Member> studentList;
public GetHttpResponse(Context context)
{
this.context = context;
}
public ArrayList<Member> getStudentList(){
return this.studentList;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
// Passing HTTP URL to HttpServicesClass Class.
HttpServicesClass httpServicesClass = new HttpServicesClass(HttpUrl);
try
{
httpServicesClass.ExecutePostRequest();
if(httpServicesClass.getResponseCode() == 200)
{
JSonResult = httpServicesClass.getResponse();
if(JSonResult != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(JSonResult);
JSONObject jsonObject;
Member member;
studentList = new ArrayList<Member>();
for(int i=0; i<jsonArray.length(); i++)
{
member = new Member();
jsonObject = jsonArray.getJSONObject(i);
// Adding Student Id TO IdList Array.
IdList.add(jsonObject.getString("id").toString());
//Adding Student Name.
member.nama = jsonObject.getString("nama").toString();
//member.nrp = jsonObject.getString("nrp").toString();
studentList.add(member);
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else
{
Toast.makeText(context, httpServicesClass.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressBar.setVisibility(View.GONE);
StudentListView.setVisibility(View.VISIBLE);
if(studentList != null) {
ListAdapterClass adapter = new ListAdapterClass(studentList, context);
StudentListView.setAdapter(adapter);
}else
{
Toast.makeText(context, "Tidak ada data ditampilkan", Toast.LENGTH_SHORT).show();
}
}
}

Unable to view the content in listview

I am using a list view in fragment which loads data using json in that i cannot able to view the list view.In the sched it shows the constructor is never used i don't know where i have done wrong in the code.The server part works fine.
Fragment:
public class SchedulessFragment extends Fragment{
private static final String TAG = MatAct.class.getSimpleName();
private static final String url = "http://nammakovai2015-001-site1.1tempurl.com/iplspin/schedules.php";
ProgressDialog pDialog;
List<Sched> movieList = new ArrayList<Sched>();
ListView listview;
CustomListAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.schedule_frag, container, false);
adapter = new CustomListAdapter(getActivity(), movieList);
listview = (ListView) v.findViewById(R.id.listView1);
listview.setAdapter(adapter);
// TextView tv = (TextView) v.findViewById(R.id.tvfrag);
// tv.setText(getArguments().getString("msg"));
// tv.setText("Hello");
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// changing action bar color
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Sched m = new Sched();
m.setTeama(obj.getString("teama"));
m.setTeamb(obj.getString("teamb"));
m.setTdate(obj.getString("tdate"));
m.setTtime(obj.getString("ttime"));
m.setThumbnailUrl(obj.getString("thumbnailUrl"));
m.setTeambthumbnailUrl(obj.getString("teambthumbnailUrl"));
m.setVenue(obj.getString("venue"));
// adding movie to movies array
movieList.add(m);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
return v;
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public static SchedulessFragment newInstance(String text) {
SchedulessFragment f = new SchedulessFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}}
ListAdapter:
public class CustomListAdapter extends BaseAdapter{
private Activity activity;
private LayoutInflater inflater;
List<Sched> movieItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<Sched> movieItems) {
this.activity = activity;
this.movieItems = movieItems;
}
#Override
public int getCount() {
return movieItems.size();
}
#Override
public Object getItem(int location) {
return movieItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.listitem_ros, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.pict);
NetworkImageView teambthumbnail=(NetworkImageView) convertView.findViewById(R.id.pict1);
TextView teama = (TextView) convertView.findViewById(R.id.scheduleteama_name);
TextView teamb = (TextView) convertView.findViewById(R.id.schduleteamb_name);
TextView tdate = (TextView) convertView.findViewById(R.id.datess);
TextView ttime = (TextView) convertView.findViewById(R.id.timess);
TextView venue=(TextView)convertView.findViewById(R.id.schedulevenue);
// getting movie data for the row
Sched m = movieItems.get(position);
// thumbnail image
thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
teambthumbnail.setImageUrl(m.getTeambthumbnailUrl(),imageLoader);
// title
teama.setText(m.getTeama());
teamb.setText(m.getTeamb());
tdate.setText(m.getTdate());
ttime.setText(m.getTtime());
venue.setText(m.getVenue());
return convertView;
}}
Sched:
public class Sched {
private String teama,teamb,tdate,ttime,thumbnailUrl,teambthumbnailUrl,venue;
public Sched(){}
public Sched(String teama, String teamb, String tdate, String ttime, String thumbnailUrl, String teambthumbnailurl, String venue)
{
this.teama=teama;
this.teamb=teamb;
this.tdate=tdate;
this.ttime=ttime;
this.thumbnailUrl=thumbnailUrl;
this.teambthumbnailUrl=teambthumbnailurl;
this.venue=venue;
}
public String getTeama(){
return teama;
}
public void setTeama(String teama){
this.teama=teama;
}
public String getTeamb(){
return teamb;
}
public void setTeamb(String teamb){
this.teamb=teamb;
}
public String getTdate(){
return tdate;
}
public void setTdate(String tdate){
this.tdate=tdate;
}
public String getTtime(){
return ttime;
}
public void setTtime(String ttime){
this.ttime=ttime;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
}
public String getTeambthumbnailUrl() {
return teambthumbnailUrl;
}
public void setTeambthumbnailUrl(String teambthumbnailUrl){
this.teambthumbnailUrl=teambthumbnailUrl;
}
public String getVenue(){
return venue;
}
public void setVenue(String venue){
this.venue=venue;
}}
xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ListView
android:id="#+id/listView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:dividerHeight="1dp"
>
</ListView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="#+id/tvfrag"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="219dp" />
Your problem is that you are creating the adapter before the movieList has been populated. Move these two lines:
adapter = new CustomListAdapter(getActivity(), movieList);
listview.setAdapter(adapter);
after the for loop in which you're adding the Movies to the list:
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Sched m = new Sched();
m.setTeama(obj.getString("teama"));
m.setTeamb(obj.getString("teamb"));
m.setTdate(obj.getString("tdate"));
m.setTtime(obj.getString("ttime"));
m.setThumbnailUrl(obj.getString("thumbnailUrl"));
m.setTeambthumbnailUrl(obj.getString("teambthumbnailUrl"));
m.setVenue(obj.getString("venue"));
// adding movie to movies array
movieList.add(m);
} catch (JSONException e) {
e.printStackTrace();
}
//PUT THOSE TWO LINES HERE
Assuming your Request is good and it returns a non-empty JSONArray, this should work.

How to show JSON objects in listview?

Main class
Using volley library to fetch JSON data from URL.
public class MyActivity extends Activity {
ListView listView;
List<Details> rowItems;
RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details2);
url = getIntent().getStringExtra("key");
if(savedInstanceState!=null){
Log.d("STATE",savedInstanceState.toString());
}
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jor = new JsonObjectRequest(url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray ja = response.getJSONArray("results");
ArrayList<Details> myModelList = new ArrayList<Details>();
Details mymodel = null;
for (int i = 0; i < ja.length(); i++) {
JSONObject jsonObject = ja.getJSONObject(i);
mymodel = new Details();
mymodel.id = Integer.parseInt(jsonObject.optString("id").toString());
mymodel.url = jsonObject.getString("resLink");
mymodel.resType = jsonObject.getString("resType");
mymodel.name = jsonObject.getString("resName");
myModelList.add(mymodel);
setData();
}
}catch(JSONException e){e.printStackTrace();}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley","Error");
}
}
);
requestQueue.add(jor);
}
private void setData() {
listView = (ListView) findViewById(R.id.list);
CustomListViewAdapter adapter = new CustomListViewAdapter(this,
R.layout.list_item, rowItems);
listView.setAdapter(adapter);
//listView.setOnItemClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
My CustomListViewAdapter claas is below
public class CustomListViewAdapter extends ArrayAdapter<Details> {
Context context;
public CustomListViewAdapter(Context context, int resourceId,
List<Details> items) {
super(context, resourceId, items);
this.context = context;
}
/*private view holder class*/
private class ViewHolder {
TextView txtTitle;
TextView txtDesc;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Details rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView.findViewById(R.id.desc);
holder.txtTitle = (TextView) convertView.findViewById(R.id.title);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.txtDesc.setText(rowItem.getResType());
holder.txtTitle.setText(rowItem.getName());
return convertView;
}
My Details class
public class Details extends Results {
String name;
String resType;
String url;
int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getResType() {
return resType;
}
public void setResType(String resType) {
this.resType = resType;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
* want to showthe data I received in list view*
my XML
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
list_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/icon"
android:paddingBottom="10dp"
android:textColor="#CC0033"
android:textSize="16dp" />
<TextView
android:id="#+id/desc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/title"
android:layout_toRightOf="#+id/icon"
android:paddingLeft="10dp"
android:textColor="#3399FF"
android:textSize="14dp" />
You are doing everything right but not passing your myModelList which contains the data and are passing the empty rowItems list. Once you fetch all data and create your myModelList, call
setData(myModelList);
And change your setData method as follows
private void setData(List<Details> mList) {
listView = (ListView) findViewById(R.id.list);
CustomListViewAdapter adapter = new CustomListViewAdapter(this,
R.layout.list_item, mList);
listView.setAdapter(adapter);
}
use following line in your adapter class getView()
Details rowItem = (Details) getItem(position);
instead of
Details rowItem = getItem(position);
Update your setData methode as you are not getting list to set data.
private void setData(List<Details> list) {
listView = (ListView) findViewById(R.id.list);
CustomListViewAdapter adapter = new CustomListViewAdapter(this,
R.layout.list_item, list);
listView.setAdapter(adapter);
}
Also change setData(); to setData(myModelList);
In adapter you are using List rowItems;
so code of onResponse method should be like as follows
JSONArray ja = response.getJSONArray("results");
rowItems = new ArrayList<Details>();
Details mymodel = null;
for (int i = 0; i < ja.length(); i++) {
JSONObject jsonObject = ja.getJSONObject(i);
mymodel = new Details();
mymodel.id = Integer.parseInt(jsonObject.optString("id").toString());
mymodel.url = jsonObject.getString("resLink");
mymodel.resType = jsonObject.getString("resType");
mymodel.name = jsonObject.getString("resName");
rowItems.add(mymodel);
}
setData();
To make the json parsing easy you can use Gson library as explained here
http://www.mysamplecode.com/2013/07/android-json-stream-data-parsing.html

ListView not displaying data in fragment

I am using listview to populate data coming from the server. This listview will show that data in a fragmentTab. Now the data is parsing fine and logcat is also showing the data. But the data is not being populated by listview. I tried to see the error through debugging but there is no problem. Even the Holder in adapter catches the data but it's not displayed. I don't know what the problem is. I tried the following questions but didn't got the answer.
Android - ListView in Fragment does not showing up
Android - ListView in Fragment does not show
ListView in Fragment Not Displayed
Below is my fragment and the adapter.
Tastemaker Fragment:
public class TasteMakersFragment extends Fragment
{
CommonClass commonTasteMakers;
String tasteMaker_url = CommonClass.url+ URLConstants.Host.URL_ALL_SUGGESTED_TASTEMAKERS;
String user_token = "8aa0dcd5aaf54c8a5aaef1aa242f342f";
ListView suggested_list;
List<SuggestedUserModel> suggestedUsers_list = new ArrayList<>();
SuggestedUsersAdapter mAdapter;
int selectedPosition = 0;
public TasteMakersFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.from(getActivity()).inflate(R.layout.suggested_users_tastemakers, null);
commonTasteMakers = new CommonClass(getActivity().getApplicationContext());
suggested_list = (ListView)v.findViewById(R.id.lst_suggestedUsers);
new GetSuggestedUsers().execute(tasteMaker_url);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
}
private class GetSuggestedUsers extends AsyncTask< String, Void, Void>
{
private ProgressDialog Dialog = new ProgressDialog(getActivity());
protected void onPreExecute() {
if (suggestedUsers_list.isEmpty())
{
Dialog = ProgressDialog.show(getActivity(),"Please be patient!","Fetching for first time...");
}
}
#Override
protected Void doInBackground(String... params)
{
if (suggestedUsers_list.isEmpty())
{
getSuggestedUsers();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
else{
Log.d("---- Already Fetched --", "---- Already Fetched ----");
return null;
}
}
protected void onPostExecute(Void unused)
{
Dialog.dismiss();
mAdapter = new SuggestedUsersAdapter(getActivity(), suggestedUsers_list);
suggested_list.setAdapter(mAdapter);
suggested_list.setSelection(selectedPosition);
mAdapter.notifyDataSetChanged();
//startMainActivity();
}
}
private List<SuggestedUserModel> getSuggestedUsers()
{
StringRequest postRequest = new StringRequest(Request.Method.POST, tasteMaker_url, new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
try {
//JSONObject jsonResponse = new JSONObject(response).getJSONObject("form");
JSONObject jsonResponse = new JSONObject(response);
if (jsonResponse.has("data"))
{
JSONObject data = jsonResponse.getJSONObject("data");
String code = jsonResponse.getString("code");
if(code.equals("200"))
{
if(data.has("tasteMakers"))
{
JSONArray tastemakers = data.getJSONArray("tasteMakers");
for (int i =0; i<tastemakers.length(); i++)
{
JSONObject jsnObj = tastemakers.getJSONObject(i);
String id = jsnObj.getString("userId");
String name = jsnObj.getString("name");
String profilePic = jsnObj.getString("imgUrl");
Boolean isFollowed = jsnObj.getBoolean("isFollowed");
suggestedUsers_list.add(new SuggestedUserModel(id,
name,
profilePic,
isFollowed));
Log.d("Names are ----", "size is=" + name +" and their id are: "+id);
}
// Log.d("Adapter list ----", "size is=" + suggestedUsers_list.size());
}
}
else {
Log.d("Error0 Error Error", "response------:" + jsonResponse);
}
}
// Log.d("response222---------","response22222------:"+jsonResponse);
} catch (JSONException e) {
Log.d("-----Stop------", "!!!");
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<>();
// the POST parameters:
params.put("sessionToken", user_token);
return params;
} };
postRequest.setRetryPolicy(new DefaultRetryPolicy(20000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Volley.newRequestQueue(getActivity().getApplicationContext()).add(postRequest);
return suggestedUsers_list;
}
}
Adapter Class:
public class SuggestedUsersAdapter extends BaseAdapter {
Context context;
int count = 1;
private List<SuggestedUserModel> allUsers;
public SuggestedUsersAdapter(FragmentActivity activity, List<SuggestedUserModel> suggestUserModel)
{
Log.d("Custom Adapter called", "" + suggestUserModel.size());
context = activity;
allUsers = suggestUserModel;
//FragmentActivity mActivity = activity;
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return allUsers.size();
// return imageId.length;
}
#Override
public Object getItem(int position) {
return allUsers.get(position);
// return position;
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint({"ViewHolder", "InflateParams", "CutPasteId"})
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final mHolder holder;
// int type = getItemViewType(position);
LayoutInflater layoutInflater;
getItemViewType(position);
if (convertView == null)
{
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.suggested_users_tastemaker_cell, null);
holder = new mHolder();
// convertView.setTag(mFeedsListItemViewHolder);
holder.txt_suggestUserName = (TextView) convertView.findViewById(R.id.tv_tasteMakerName);
holder.imgV_userProfile = (ImageView) convertView.findViewById(R.id.imgBtn_tasteMaker_pic);
holder.btnFollow = (Button) convertView.findViewById(R.id.btnFollow_tasteMaker);
holder.btnFollowing = (Button) convertView.findViewById(R.id.btnFollowing);
convertView.setTag(holder);
} else {
holder = (mHolder) convertView.getTag();
}
final SuggestedUserModel suggestUser = allUsers.get(position);
holder.txt_suggestUserName.setText(allUsers.get(position).getSuggested_UserName());
/*if(suggestUser.getSuggested_UserImage().equals(""))
{
Picasso
.with(context)
.load(R.mipmap.ic_launcher)
.transform(new CropSquareTransformationHomePage())
.into(holder.imgV_userProfile);
}
else {
Picasso
.with(context)
.load(suggestUser.getSuggested_UserImage())
.transform(new CropSquareTransformationHomePage())
.into(holder.imgV_userProfile);
}*/
holder.pos = position;
//mFeedsListItemViewHolder.setData(allPersons.get(position));
return convertView;
}
private class mHolder {
TextView txt_suggestUserName;
ImageView imgV_userProfile;
Button btnFollow;
Button btnFollowing;
int pos;
}
}
Note: I already tried declaring listview and assigning adapter in onActivityCreated() method of fragment but no effect.
Any Help will be appreciated.

how to Listview Refresh after Delete an item on Button Click event in android?

I want to delete an item from Listview, and at a time Refresh Listview after deleting an item. How to possible?
I am using get all item using JSON Parsing from database and delete an selected an item on click of button. delete successfully from database but Listview not refresh at a time. how to do?
I am using Json Parsing. not local database.
In This case, How to refresh Listview when Deleting Item?
please Guide me.
Thanks in Advance.
My Code is,
Detail.java File
public class Detail extends Activity {
ListView lstDetail = null;
/** String */
String urlGetDetailData = null;
/** Declare another variable for Listview */
Adapter1 adapter1 = null;
ArrayList<Detail> myList = new ArrayList<Detail>();
/** Hashmap for ListView */
ArrayList<HashMap<String, String>> dataList = null;
/** JSON Node names */
public static final String TAG_MEMBER_ID = "mem_id";
public static final String TAG_ID = "id";
public static final String TAG_USER_ID = "userid";
public static final String TAG_STATUS = "Status";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
onCreateActivity(R.layout.detail);
initializeWidgets();
}
private void initializeWidgets() {
/** ListView */
lstDetail = (ListView) findViewById(R.id.lstDetail);
urlGetDetailData = "http://example.com/getdata.php?id="
+ strId;
new GetDetailData().execute();
myList.remove(position);
Adapter1.this.notifyDataSetChanged();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetDetailData extends AsyncTask<Void, Void, Void> {
JSONObject jsonobject;
JSONArray jsonarray;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
dataList = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONFunctions.getJSONfromURL(urlGetDetailData);
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("data");
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("mem_id", String.valueOf(jsonobject
.getString(TAG_MEMBER_ID)));
map.put("id",
jsonobject.getString(TAG_ID));
map.put("userid", jsonobject.getString(TAG_USER_ID));
map.put("Status", jsonobject.getString(TAG_STATUS));
dataList.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (dataList.size() != 0) {
lstDetail.setVisibility(View.VISIBLE);
Adapter1 = new Adapter1(Detail.this,
dataList);
lstDetail.setAdapter(Adapter1);
} else {
lstDetail.setVisibility(View.GONE);
}
}
}
}
And Adapter Class is,
Adapter1.java File
public class Adapter1 extends BaseAdapter {
public ArrayList<HashMap<String, String>> arrData = null;
Context context = null;
LayoutInflater layoutInflater = null;
HashMap<String, String> getDetailData = new HashMap<String, String>();
/** String */
String strMemberId = null, urlDelete = null;
/** Constructor */
public Adapter1(Context context,
ArrayList<HashMap<String, String>> arrData) {
layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.context = context;
this.arrData = arrData;
}
#Override
public int getCount() {
return arrData.size();
}
#Override
public Object getItem(int position) {
return arrData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
convertView = layoutInflater.inflate(
R.layout.list_item, null);
viewHolder = new ViewHolder();
getData = arrData.get(position);
/** Initialize Widgets */
viewHolder.imgCancel = (ImageView) convertView
.findViewById(R.id.imgCancel);
viewHolder.imgCancel
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
strMemberId = arrData.get(
position).get(
Detail.TAG_MEMBER_ID);
urlDelete = "http://example.com/delete.php?mem_id="
+ strMemberId;
new DeleteComments().execute();
}
});
/** TextView */
viewHolder.txtMemberId = (TextView) convertView
.findViewById(R.id.txtMemberId);
viewHolder.txtId = (TextView) convertView
.findViewById(R.id.txtId);
viewHolder.txtDesc = (TextView) convertView
.findViewById(R.id.txtDesc);
/** Set Value */
viewHolder.txtMemberId.setText(getDetailData
.get(Detail.TAG_MEMBER_ID));
viewHolder.txtId.setText(getDetailData
.get(Detail.TAG_ID));
viewHolder.txtDesc.setText(getDetailData
.get(Detail.TAG_STATUS));
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
return convertView;
}
/** ViewHolder Class */
#SuppressLint("NewApi")
public static class ViewHolder {
ImageView imgCancel = null;
TextView txtMemberId = null, txtId = null,txtDesc = null;
}
public class DeleteComments extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(urlDelete,
ServiceHandler.GET);
Log.d("Response : delete join comments", ">" + jsonStr);
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
};
}
}
detail.xml File is,
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/re/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ListView
android:id="#+id/lstDetail"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>
</RelativeLayout>
list_item.xml file is,
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/re/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:id="#+id/contentLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="vertical" >
<TextView
android:id="#+id/txtId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="111" />
<TextView
android:id="#+id/txtDesc"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<ImageView
android:id="#+id/imgCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:src="#drawable/cancel" />
<TextView
android:id="#+id/txtMemberId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/txtUserEventId"
android:layout_alignBottom="#+id/txtUserEventId"
android:layout_alignParentLeft="true"
android:text="222" />
</RelativeLayout>
in your custom adapter call this.notifyDataSetChanged(); where you are performing delete functionality and deleting that element from arrayList which is set to that adapter
You are writing delete action, in that function only call adapter.notifyDataSetChanged again.So it refr
on delete action fetch the data once again and then again call adapter.notifyDataSetChanged it will work
First of all Put you adapter code in Details.java class
then change this,
public class DeleteComments extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(urlDelete,
ServiceHandler.GET);
Log.d("Response : delete join comments", ">" + jsonStr);
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Adapter1.remove(Adapter1.getItem(position));
};
}
hope it will help you
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
convertView = layoutInflater.inflate(
R.layout.list_item, null);
viewHolder = new ViewHolder();
getData = arrData.get(position);
/** Initialize Widgets */
viewHolder.imgCancel = (ImageView) convertView
.findViewById(R.id.imgCancel);
viewHolder.imgCancel
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
strMemberId = arrData.get(
position).get(
Detail.TAG_MEMBER_ID);
urlDelete = "http://example.com/delete.php?mem_id="
+ strMemberId;
new DeleteComments().execute();
}
});
/** TextView */
viewHolder.txtMemberId = (TextView) convertView
.findViewById(R.id.txtMemberId);
viewHolder.txtId = (TextView) convertView
.findViewById(R.id.txtId);
viewHolder.txtDesc = (TextView) convertView
.findViewById(R.id.txtDesc);
/** Set Value */
viewHolder.txtMemberId.setText(getDetailData
.get(Detail.TAG_MEMBER_ID));
viewHolder.txtId.setText(getDetailData
.get(Detail.TAG_ID));
viewHolder.txtDesc.setText(getDetailData
.get(Detail.TAG_STATUS));
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
bDelete.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View view)
{
arrData.remove(position);
notifyDataSetChanged():
}
});
return convertView;
}
Why make it that complicated?
Just call remove(Obj); in OnClickListener of your customized adapter Adapter1's. And notifyDataSetChanged will be called in removed method too.

Categories

Resources