List view not refreshing when item is deleted [duplicate] - android

This question already has answers here:
ListView not "refreshing" after item is deleted from it
(6 answers)
Closed 5 years ago.
I Have a list view where i have loaded it with json array data. I have minus button to delete row from list. Here the problem is I am able to delete the item but list view is not getting refreshed. The list view gets refreshed once the application is closed or when I go back and navigate to that activity again.
Below is the custom adapter class code:
public class AddPassengerAdapater extends BaseAdapter implements ListAdapter {
private final JSONArray jsonArray;
ArrayList<String> data;
Context context;
JSONObject json_data;
LayoutInflater inflater;
public AddPassengerAdapater(Context context, JSONArray jsonArray,ArrayList<String> data) {
this.context = context;
this.jsonArray = jsonArray;
this.data = data;
String details = SessionManager.getPreferences(context,"splitfare_consumer");
data = new ArrayList<String>();
JSONArray jsonarray = null;
try {
jsonarray = new JSONArray(details);
for (int i=0; i < jsonarray.length() ; i++){
json_data = jsonarray.getJSONObject(i);
data.add(String.valueOf(json_data));
}
} catch (JSONException e) {
e.printStackTrace();
}
inflater = LayoutInflater.from(this.context);
}
#Override public int getCount() {
if(null==jsonArray)
return 0;
else
return jsonArray.length();
}
#Override public JSONObject getItem(int position) {
if(null==jsonArray) return null;
else
return jsonArray.optJSONObject(position);
}
#Override public long getItemId(int position) {
JSONObject jsonObject = getItem(position);
return jsonObject.optLong("id");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final MyViewHolder mViewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.addpassenger_row_layout, parent, false);
mViewHolder = new MyViewHolder(convertView);
convertView.setTag(mViewHolder);
}
else {
mViewHolder = (MyViewHolder) convertView.getTag();
}
json_data = getItem(position);
try {
String n = json_data.getString("name");
mViewHolder.name.setText(n);
String nu = json_data.getString("number");
mViewHolder.number.setText(nu);
} catch (JSONException e) {
e.printStackTrace();
}
mViewHolder.deletelist.setOnClickListener(new View.OnClickListener() {
JSONArray delete_jsonarray;
JSONObject jsonObject;
#Override
public void onClick(View v) {
String phonenumber = mViewHolder.number.getText().toString();
String jsonsetpreference_data = SessionManager.getPreferences(context,"splitfare_consumer");
Log.d("jsonsetpreference_data:::::::","" +jsonsetpreference_data);
try {
delete_jsonarray= new JSONArray(jsonsetpreference_data);
for (int i =0; i<= delete_jsonarray.length()-1 ; i++){
jsonObject = delete_jsonarray.getJSONObject(i);
String array_phonenumber = jsonObject.getString("number");
if (phonenumber.equals(array_phonenumber)){
delete_jsonarray.remove(i);
}
}
SessionManager.setPreferences(context,"splitfare_consumer",delete_jsonarray.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return convertView;
}
private class MyViewHolder {
TextView name, number;
ImageView deletelist;
public MyViewHolder(View item) {
name = (TextView) item.findViewById(R.id.consumername);
number = (TextView) item.findViewById(R.id.consumer_number);
deletelist = (ImageView) item.findViewById(R.id.dltconsumer);
}
}
}
Listview activity code:
public class AddPassengerList extends AppCompatActivity {
#BindView(R.id.listview)
ListView listview;
#BindView(R.id.btn_addmore)
CustomFontButton btn_addmore;
#BindView(R.id.donebtn)
CustomFontButton donebtn;
public static final String TAG = "AddPassengerList";
Activity activity=this;
Context context = this;
JSONArray js;
AddPassengerAdapater adapter;
LayoutInflater inflater;
String name ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_passenger_list);
ButterKnife.bind(this);
/*Status bar color*/
Window window = activity.getWindow();
// clear FLAG_TRANSLUCENT_STATUS flag:
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// add FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag to the window
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
// finally change the color
window.setStatusBarColor(ContextCompat.getColor(context,R.color.colorAccent));
String data = SessionManager.getPreferences(context,"splitfare_consumer");
Log.d(TAG,""+data);
ArrayList<String> details= new ArrayList<String>();
try {
js = new JSONArray(data);
} catch (JSONException e) {
e.printStackTrace();
}
adapter = new AddPassengerAdapater(context,js,details);
listview.setAdapter(adapter);
btn_addmore.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
btn_addmore.setBackgroundResource(R.drawable.addmorepassengerpressed);
break;
case MotionEvent.ACTION_UP:
btn_addmore.setBackgroundResource(R.drawable.addmorepassenger);
Intent i = new Intent(AddPassengerList.this,AddPassenger.class);
startActivity(i);
break;
}
return false;
}
});
}
}

Recall your adapter again after delete item...
mViewHolder.deletelist.setOnClickListener(new View.OnClickListener() {
JSONArray delete_jsonarray;
JSONObject jsonObject;
#Override
public void onClick(View v) {
String phonenumber = mViewHolder.number.getText().toString();
String jsonsetpreference_data = SessionManager.getPreferences(context,"splitfare_consumer");
Log.d("jsonsetpreference_data:::::::","" +jsonsetpreference_data);
try {
delete_jsonarray= new JSONArray(jsonsetpreference_data);
for (int i =0; i<= delete_jsonarray.length()-1 ; i++){
jsonObject = delete_jsonarray.getJSONObject(i);
String array_phonenumber = jsonObject.getString("number");
if (phonenumber.equals(array_phonenumber)){
delete_jsonarray.remove(i);
}
}
SessionManager.setPreferences(context,"splitfare_consumer",delete_jsonarray.toString());
} catch (JSONException e) {
e.printStackTrace();
}
notifyDataSetChanged();
}
});

Related

android ListActivity how to populate data with Json Volley Library

android ListActivity how to make Custom Adapter getter setter using ,call json Volley library populate data ListActivity ? could not populate data with Json how to implement ,Please Help me
my code
ItemFragment Class
public class ItemFragment extends ListActivity {
RequestParse requestParse;
MySharedPreferences prefs;
String UsrId;
Context context;
ArrayList<BizForumArticleInfo> list = new ArrayList<>();
private List<BizForumArticleInfo> CountryCodeNumber = new ArrayList<>();
MobileArrayAdapter adapter;
LinearLayoutManager mLayoutManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view_android_example);
requestParse = new RequestParse();
prefs = MySharedPreferences.getInstance(this, SESSION);
UsrId = prefs.getString("UsrID", "");
context = getApplicationContext();
setListAdapter(new MobileArrayAdapter(this,0, list));
getJson(60);
}
public void getJson(final int limit){
requestParse.postJson(ConfigApi.postArticleBiz(), new RequestParse.VolleyCallBackPost() {
#Override
public void onSuccess(String result) {
list = parseResponse(result);
}
#Override
public void onRequestError(String errorMessage) {
}
#Override
public Map OnParam(Map<String, String> params) {
params.put("sessionid", UsrId);
params.put("offset", "0");
params.put("limit", String.valueOf(limit));
params.put("viewtype", "all");
params.put("access_token","e3774d357aa7d4bd14e9763b5459ee9cf7ebe36161c142551836ee510d98814a:b349b76b334a94b2");
return params;
}
});
}
public static ArrayList<BizForumArticleInfo> parseResponse(String response) {
ArrayList<BizForumArticleInfo> bizList = new ArrayList<>();
try {
JSONObject json = new JSONObject(response);
JSONArray data = json.getJSONArray(DATA);
for (int i = 0; i < data.length(); i++) {
BizForumArticleInfo ls = new BizForumArticleInfo();
JSONObject item = data.getJSONObject(i);
String ArticleTitle = item.getString("ArticleTitle");
String Article = item.getString("Article");
M.i("===================",ArticleTitle);//working
ls.setArticleTitle(ArticleTitle);
ls.setArticleArticle(Article);
bizList.add(ls);
}
} catch (JSONException e) {
e.printStackTrace();
}
return bizList;
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String selectedValue = (String) getListAdapter().getItem(position);
Toast.makeText(this, selectedValue, Toast.LENGTH_SHORT).show();
Intent intent = new Intent();
intent.putExtra("selectedValue", selectedValue);
setResult(RESULT_OK, intent);
finish();
//startActivity(new Intent(v.getContext(), MainActivity.class));
}
}
Adapter Class
public class MobileArrayAdapter extends ArrayAdapter<BizForumArticleInfo> {
private Activity activity;
private ArrayList<BizForumArticleInfo> lPerson;
private static LayoutInflater inflater = null;
public MobileArrayAdapter (Activity activity, int textViewResourceId,ArrayList<BizForumArticleInfo> _lPerson) {
super(activity, textViewResourceId, _lPerson);
try {
this.activity = activity;
this.lPerson = _lPerson;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
} catch (Exception e) {
}
}
public int getCount() {
return lPerson.size();
}
public BizForumArticleInfo getItem(BizForumArticleInfo position) {
return position;
}
public long getItemId(int position) {
return position;
}
public static class ViewHolder {
public TextView display_name;
public TextView display_number;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
final ViewHolder holder;
try {
if (convertView == null) {
vi = inflater.inflate(R.layout.list_mobile, null);
holder = new ViewHolder();
holder.display_name = (TextView) vi.findViewById(R.id.label);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
holder.display_name.setText(lPerson.get(position).getArticleTitle());
} catch (Exception e) {
}
return vi;
}
}

android ListView is empty Logcat shows nothing

i am trying to display json data in listview but listview is empty logcat shows no error and app also don't get crashed i am unable to find the error here is the method that adds json data to the adapter
public void setTextToTextView(JSONArray jsonArray) {
contactAdapter = new ContactAdapter(this,R.layout.row_layout);
listView.setAdapter(contactAdapter);
try {
int count = 0;
String stop;
while(count < jsonArray.length())
{
JSONObject JO = jsonArray.getJSONObject(count);
stop = JO.getString("stop");
Contacts contacts = new Contacts(stop);
contactAdapter.add(contacts);
count++;
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
here is the Adapter class
public class ContactAdapter extends ArrayAdapter{
List list = new ArrayList();
public ContactAdapter(Context context, int resources){
super(context,resources);
}
public void add(Contacts object)
{
super.add(object);
list.add(object);
}
#Override
public int getCount() {return list.size();}
#Override
public Object getItem(int position) {return list.get(position);}
#Override
public View getView(int position,View convertView,ViewGroup parent)
{
View row;
row = convertView;
ContactHolder contactHolder;
if(row == null)
{
LayoutInflater layoutInflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout,parent,false);
contactHolder = new ContactHolder();
contactHolder.tx_stop = (TextView)row.findViewById(R.id.tx_stop);
row.setTag(contactHolder);
}
else
{
contactHolder = (ContactHolder)row.getTag();
}
Contacts contacts = (Contacts)this.getItem(position);
contactHolder.tx_stop.setText(contacts.getStop());
return row;
}
static class ContactHolder
{
TextView tx_stop;
}
}
Call
contactAdapter.notifyDataSetChanged();
after your while loop.
You can create ArrayList<Contacts> contactsArray = new ArrayList<Contacts>(); then push all objects in it after that to set your adapter with passed array. Your method should look like:
public void setTextToTextView(JSONArray jsonArray) {
ArrayList<Contacts> contactsArray = new ArrayList<Contacts>();
try {
int count = 0;
String stop;
while(count < jsonArray.length()) {
JSONObject JO = jsonArray.getJSONObject(count);
stop = JO.getString("stop");
Contacts contacts = new Contacts(stop);
contactsArray.add(contacts);
count++;
}
contactAdapter = new ContactAdapter(this,R.layout.row_layout, contactsArray);
listView.setAdapter(contactAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
In your adapter do the following:
ArrayList<Contacts> list = new ArrayList<Contacts>();
public ContactAdapter(Context context, int resources, ArrayList<Contacts> list){
super(context,resources);
this.list = list;
}
That's all. Hope to help!

Android Data is repeating in my spinner while switching between activities

Below is the code where i m parsing JSON and this method gets called onResume() method.
private void parseJSONSubTypeEventsSelect(String response)
throws JSONException {
JSONObject jsonObject = new JSONObject(response);
JSONArray columns = jsonObject.getJSONArray("columns");
JSONArray rowsWrapper = jsonObject.getJSONArray("rows");
JsonHelper jsonHelper = new JsonHelper();
List<List<String>> listOfListRow = new ArrayList<List<String>>();
Map<String, List<String>> map = new HashMap<>();
try {
for (int i = 0; i < rowsWrapper.length(); i++) {
if (i == rowsWrapper.length()) {
break;
} else {
map.put(rowsWrapper.get(i).toString(),jsonHelper.toList(rowsWrapper.getJSONArray(i)));
rowListSubTypeEvents = jsonHelper.toList(rowsWrapper.getJSONArray(i));
listOfListRow.add(rowListSubTypeEvents);
}
}
// System.out.println(listOfListRow);
} catch (Exception e1) {
e1.printStackTrace();
}
I am Clearing the data here but the same data is printed twice
StandName.clear();
slNo.clear();
Rate.clear();
System.out.println("StandName before"+StandName);
System.out.println("slNo before"+slNo);
System.out.println("Rate before"+Rate);
StandName.add("Select Stand Name");
slNo.add("");
Rate.add("");
System.out.println("StandName after"+StandName);
System.out.println("slNo after"+slNo);
System.out.println("Rate after"+Rate);
for (List<String> listRows : listOfListRow) {
int k = 0;
for (String value : listRows) {
k++;
switch (k) {
case 1:
imageMapCoords.add(value);
// listOfListRow.add(logoFileNameList);
break;
case 2:
slNo.add(value);
// listOfListRow.add(logoFileName1List);
break;
case 3:
StandName.add(value);
// listOfListRow.add(logoFileName1List);
break;
case 4:
Rate.add(value);
// listOfListRow.add(logoFileName1List);
break;
case 5:
avail.add(value);
// listOfListRow.add(logoFileName1List);
break;
case 6:
allowSeatSelection.add(value);
// listOfListRow.add(logoFileName1List);
break;
case 7:
panaromicView.add(value);
// listOfListRow.add(logoFileName1List);
break;
}
}
}
tvVenue.setText(Venue.get(Venue.size() - 1));
System.out.println("Stand names from third activity"+StandName);
System.out.println("data sending to pojo slNo "+slNo);
System.out.println("data sending to pojo StandName"+StandName);
System.out.println("data sending to pojo Rate"+Rate);
for (int i = 0; i <= rowsWrapper.length(); i++) {
RowItemThird item = new RowItemThird(slNo.get(i),StandName.get(i), Rate.get(i));
rowItems.add(item);
}
adapter = new CustomBaseAdapterThird(this, rowItems);
adapter.notifyDataSetChanged();
// lvThird.setAdapter(adapter);
spinner.setAdapter(adapter);
pDialog.hide();
pDialog.dismiss();
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
positionCheckStandName = StandName.get(position);
System.out.println("positionCheckStandName"+positionCheckStandName);
positionSlNo = slNo.get(position);
stringRate = Rate.get(position);
System.out.println("SLNO"+positionSlNo);
/* spinner.getSelectedItemPosition();*/
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Below is the pojo class
public class RowItemThird {
private String mSlNo;
private String mStandName;
private String mRate;
public RowItemThird(String slNo, String StandName, String Rate) {
mSlNo = slNo;
mStandName = StandName;
mRate = Rate;
}
public String getmSlNo() {
return mSlNo;
}
public void setmSlNo(String mSlNo) {
this.mSlNo = mSlNo;
}
public String getmStandName() {
return mStandName;
}
public void setmStandName(String mStandName) {
this.mStandName = mStandName;
}
public String getmRate() {
return mRate;
}
public void setmRate(String mRate) {
this.mRate = mRate;
}
}
Below is the BaseAdapter class to add items to spinner
public class CustomBaseAdapterThird extends BaseAdapter
{
private Context mContext;
private List<RowItemThird> mRowItems;
TextView slNO;
TextView StandName;
TextView Rate;
public CustomBaseAdapterThird(Context context, List<RowItemThird> rowItems)
{
mContext = context;
mRowItems = rowItems;
}
#Override
public int getCount() {
return mRowItems.size();
}
#Override
public Object getItem(int position) {
return mRowItems.get(position);
}
#Override
public long getItemId(int position) {
return mRowItems.indexOf(getItem(position));
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = null;
LayoutInflater mInflator = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = mInflator.inflate(R.layout.event_list_item_third_sub_type_event_select, null);
slNO = (TextView) convertView.findViewById(R.id.textViewSLNo);
StandName = (TextView) convertView.findViewById(R.id.textViewStand);
Rate = (TextView) convertView.findViewById(R.id.textViewRate);
RowItemThird row = (RowItemThird) getItem(position);
slNO.setText(row.getmSlNo());
StandName.setText(row.getmStandName());
Rate.setText(row.getmRate());
return convertView;
}
}
Every time you are adding the data to the rowItems object, which you are passing to the spinner adapter
adapter = new CustomBaseAdapterThird(this, rowItems);
adapter.notifyDataSetChanged();
So clear the ``rowItems` data before adding the new data
rowItems.clear();
for (int i = 0; i <= rowsWrapper.length(); i++) {
RowItemThird item = new RowItemThird(slNo.get(i),StandName.get(i), Rate.get(i));
rowItems.add(item);
}

onitemclick does not work in fragment (custom list view)

I have created an activity to get and show data to a custom list view.
Now I have changed this to fragment but onItemclick does not work.
SiteNews.java
public class SiteNews extends Fragment implements OnTabChangeListener,
OnPageChangeListener {
private TabHost tabHost;
private ViewPager viewPager;
private FragmentPagerNewsAdapter fragmentPagerNewsAdapter;
int i = 0;
View v;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.tabs_news_layout, container, false);
// put tabhost here:
// ***************************** part 1
// ***************************************************
i++;
// init tabhost
this.initializeTabHost(savedInstanceState);
// init ViewPager
this.initializeViewPager();
// ***************************** part 1
// ***************************************************
return v;
}
private void initializeViewPager() {
List<Fragment> fragmentsnews = new Vector<Fragment>();
fragmentsnews.add(new FragmentAllNews());
fragmentsnews.add(new FragmentUnreadNews());
this.fragmentPagerNewsAdapter = new FragmentPagerNewsAdapter(
getChildFragmentManager(), fragmentsnews);
this.viewPager = (ViewPager) v.findViewById(R.id.viewPagernews);
this.viewPager.setAdapter(this.fragmentPagerNewsAdapter);
this.viewPager.setOnPageChangeListener(this);
}
// fake content for tabhost
class FakeContent implements TabContentFactory {
private final Context mContext;
public FakeContent(Context context) {
mContext = context;
}
#Override
public View createTabContent(String tag) {
View v = new View(mContext);
v.setMinimumHeight(0);
v.setMinimumWidth(0);
return v;
}
}
private void initializeTabHost(Bundle args) {
tabHost = (TabHost) v.findViewById(android.R.id.tabhost);
tabHost.setup();
for (int i = 1; i <= 2; i++) {
TabHost.TabSpec tabSpec;
tabSpec = tabHost.newTabSpec("Tab " + i);
tabSpec.setIndicator("Tab " + i);
tabSpec.setContent(new FakeContent(getActivity()));
tabHost.addTab(tabSpec);
}
tabHost.setOnTabChangedListener(this);
}
#Override
public void onTabChanged(String tabId) {
int pos = this.tabHost.getCurrentTab();
this.viewPager.setCurrentItem(pos);
HorizontalScrollView hScrollView = (HorizontalScrollView) v
.findViewById(R.id.hScrollViewnews);
View tabView = tabHost.getCurrentTabView();
int scrollPos = tabView.getLeft()
- (hScrollView.getWidth() - tabView.getWidth()) / 2;
hScrollView.smoothScrollTo(scrollPos, 0);
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageSelected(int position) {
this.tabHost.setCurrentTab(position);
}
}
FragmentAllnews.java
public class FragmentAllNews extends Fragment implements View.OnClickListener {
ViewGroup v;
ListView list;
CustomAdapterAllNews adapter;
JSONObject json_data;
JSONArray jArray;
NewsGetData newsGetData;
ArrayList<String> id, title_news, text_news, cat_id, status;
String data, url, msg, check, readnumber, ACTION_SCAN, contents;
ArrayList<News> newsha;
News n;
int sizearray;
Resources res;
ArrayList<News> items;
News ne;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = (ViewGroup) inflater.inflate(R.layout.tabfragmentallnews,
container, false);
list = (ListView) v.findViewById(R.id.listallnews);
res = getResources();
createarray();
/* items = new ArrayList<News>();
for (int k = 0; k < 25; k++) {
ne = new News();
ne.setTitle_news("title_news " + String.valueOf(k));
ne.setText_news("text_news " + String.valueOf(k));
ne.setCat_id(k);
ne.setStatus(k);
items.add(ne);
}*/
ReadData task1 = new ReadData();
task1.execute(new String[] { "url address" });
return v;
}
private void createarray() {
id = new ArrayList<String>();
title_news = new ArrayList<String>();
text_news = new ArrayList<String>();
cat_id = new ArrayList<String>();
status = new ArrayList<String>();
id.clear();
title_news.clear();
text_news.clear();
cat_id.clear();
status.clear();
}
private class ReadData extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog = new ProgressDialog(getActivity());
#Override
protected void onPreExecute() {
dialog.setMessage("Reading Data...");
dialog.show();
}
String text = "";
ArrayList<String> list1;
#Override
protected Boolean doInBackground(String... urls) {
url = "php url address";
InputStream is1;
for (String url1 : urls) {
// Read from web to InputStream
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// HttpPost post = new HttpPost(url1);
HttpResponse response = client.execute(post);
is1 = response.getEntity().getContent();
} catch (ClientProtocolException e) {
Toast.makeText(getActivity(), e.toString(),
Toast.LENGTH_LONG).show();
return false;
} catch (IOException e) {
Toast.makeText(getActivity(), e.toString(),
Toast.LENGTH_LONG).show();
return false;
}
// end of Read from web to InputStream
// Convert from InputStream to String Text
BufferedReader reader;
try {
reader = new BufferedReader(new InputStreamReader(is1,
"iso-8859-1"), 8);
String line = null;
while ((line = reader.readLine()) != null) {
text += line + "\n";
}
is1.close();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// end of Convert from InputStream to String Text
// Convert from Text to JSON and add to ArrayList list1
list1 = new ArrayList<String>();
try {
JSONArray jArray = new JSONArray(text);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonData = jArray.getJSONObject(i);
list1.add(jsonData.getString("title_news") + " - "
+ jsonData.getString("text_news"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// end of Convert from Text to JSON and add to ArrayList list1
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
if (result == true) {
// add list1 to ArrayAdapter
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(
getActivity(), android.R.layout.simple_list_item_1,
list1);
// set adapter into listStudent
// list.setAdapter(adapter1);
Toast.makeText(getActivity(), text, Toast.LENGTH_LONG).show();
data = text;
newsha = parseJSON3(data);
adddata(newsha);
} else {
Toast.makeText(getActivity(), "Error", Toast.LENGTH_LONG)
.show();
}
dialog.dismiss();
}
}
/*
* #Override public void onItemClick(AdapterView<?> parent, View
* clickedView, int pos, long id) { TextView tv1 = (TextView)clickedView;
* int commaIndex = tv1.getText().toString().indexOf(","); String st_id =
* tv1.getText().toString().substring(0, commaIndex);
*
* Intent in = new Intent(this, EditDataActivity.class);
* in.putExtra("st_id", st_id); startActivity(in);
*
* }
*/
public void onItemClick(int mPosition) {
try {
News tempValues = (News) newsha.get(mPosition);
Toast.makeText(getActivity(), tempValues.getText_news(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
// Toast.makeText(CustomListView,"no", Toast.LENGTH_LONG).show();
}
}
public ArrayList<News> parseJSON3(String result) {
ArrayList<News> userha = new ArrayList<News>();
try {
jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
n = new News();
n.setId(json_data.getInt("id"));
id.add(String.valueOf(json_data.getInt("id")));
n.setTitle_news(json_data.getString("title_news"));
title_news.add(json_data.getString("title_news"));
n.setText_news(json_data.getString("text_news"));
text_news.add(json_data.getString("text_news"));
n.setCat_id(json_data.getInt("cat_id"));
cat_id.add(String.valueOf(json_data.getInt("cat_id")));
n.setStatus(json_data.getInt("status"));
status.add(String.valueOf(json_data.getInt("status")));
userha.add(n);
}
sizearray = text_news.size();
if (sizearray <= 0) {
Toast.makeText(getActivity(), "get data error",
Toast.LENGTH_LONG).show();
} else {
}
} catch (JSONException e) {
// toast(9);
}
return userha;
}
private void adddata(ArrayList<News> newsha2) {
adapter = new CustomAdapterAllNews(getActivity(), newsha2, newsha2, res);
list.setAdapter(adapter);
}
#Override
public void onClick(View v) {
}
}
CustomAdapterAllNews.java
public class CustomAdapterAllNews extends BaseAdapter implements OnClickListener {
/*********** Declare Used Variables *********/
private Activity activitynews;
private ArrayList datanews;
private static LayoutInflater inflaternews=null;
public Resources resnews;
News tempValuesnews=null;
int i=0;
TableLayout tableLayout1news;
private List<News> worldpopulationlistnews = null;
private ArrayList<News> arraylistnews;
/************* CustomAdapter Constructor *****************/
public CustomAdapterAllNews(Activity a, ArrayList d, List<News> worldpopulationlist, Resources resLocal) {
/********** Take passed values **********/
activitynews = a;
datanews=d;
resnews = resLocal;
this.arraylistnews = new ArrayList<News>();
this.worldpopulationlistnews = worldpopulationlist;
this.arraylistnews.addAll(worldpopulationlist);
/*********** Layout inflator to call external xml layout () **********************/
inflaternews = (LayoutInflater)activitynews.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/******** What is the size of Passed Arraylist Size ************/
public int getCount() {
if(datanews.size()<=0)
return 1;
return datanews.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/********* Create a holder to contain inflated xml file elements ***********/
public static class ViewHolder{
public TextView text;
public TextView text1;
public ImageView image;
}
/*********** Depends upon data size called for each row , Create each ListView row ***********/
#SuppressLint("InflateParams")
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holder;
if(convertView==null){
/********** Inflate tabitem.xml file for each row ( Defined below ) ************/
vi = inflaternews.inflate(R.layout.list_news, null);
/******** View Holder Object to contain tabitem.xml file elements ************/
holder=new ViewHolder();
holder.text=(TextView)vi.findViewById(R.id.textlistnews);
holder.text1=(TextView)vi.findViewById(R.id.text1listnews);
holder.image=(ImageView)vi.findViewById(R.id.imagelistnews);
/************ Set holder with LayoutInflater ************/
vi.setTag(holder);
}
else
holder=(ViewHolder)vi.getTag();
if(datanews.size()<=0)
{
holder.text.setText("No Data");
holder.text1.setText("نتیجه یافت نشد");
holder.image.setImageResource(resnews.getIdentifier("com.iranvizhe:drawable/"+"image00",null,null));
}
else
{
/***** Get each Model object from Arraylist ********/
tempValuesnews=null;
tempValuesnews = (News) datanews.get(position);
/************ Set Model values in Holder elements ***********/
holder.text.setText(tempValuesnews.getTitle_news());
holder.text1.setText(tempValuesnews.getText_news());
holder.image.setImageResource(resnews.getIdentifier("com.iranvizhe:drawable/image0",null,null));
/******** Set Item Click Listner for LayoutInflater for each row ***********/
vi.setOnClickListener(new OnItemClickListener(position));
}
return vi;
}
#Override
public void onClick(View v) {
Log.v("CustomAdapter", "=====Row button clicked");
}
/********* Called when Item click in ListView ************/
private class OnItemClickListener implements OnClickListener{
private int mPosition;
OnItemClickListener(int position){
mPosition = position;
}
#Override
public void onClick(View arg0) {
// FragmentAllNews sct = (FragmentAllNews)activitynews;
// Tab1Fragment sct = (Tab1Fragment)activity;
// sct.onItemClick(mPosition);
}
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
worldpopulationlistnews.clear();
if (charText.length() == 0) {
worldpopulationlistnews.addAll(arraylistnews);
}
else
{
for (News wp : arraylistnews)
{
if (wp.getTitle_news().toLowerCase(Locale.getDefault()).contains(charText)
| wp.getText_news().toLowerCase(Locale.getDefault()).contains(charText))
{
worldpopulationlistnews.add(wp);
}
}
}
notifyDataSetChanged();
}
}
When I put this code:
// FragmentAllNews sct = (FragmentAllNews)activitynews;
// Tab1Fragment sct = (Tab1Fragment)activity;
// sct.onItemClick(mPosition);
on click does not work for me and I need on click in list view.
Don't use v.setOnclicklistener() in adapter, better use in fragment only as below
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
try {
News tempValues = (News) newsha.get(mPosition);
Toast.makeText(getActivity(), tempValues.getText_news(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
// Toast.makeText(CustomListView,"no", Toast.LENGTH_LONG).show();
}
}
});

ListView shows wrong placement of images taken from URL

My listview doesn't show exact placement of images on its individual custom adapters. I am trying to load the images using AsyncTask. Sometimes the images duplicates and I don't have any idea why. Here is my ArrayAdapter code:
public class NewsPromoAdapter extends ArrayAdapter<NewsPromosDTO> {
private final Context context;
List<NewsPromosDTO> npList;
LayoutInflater inflater;
Bitmap src;
public NewsPromoAdapter(Context context, List<NewsPromosDTO> npList) {
super(context, R.layout.news_and_promos, npList);
this.context = context;
this.npList = npList;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public static class ViewHolder {
TextView nameText;
TextView date1Text;
ImageView imageView;
ProgressBar prg;
LoadImage loadImg;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.news_and_promos, parent,
false);
holder = new ViewHolder();
holder.nameText = (TextView) convertView
.findViewById(R.id.newspromo_name);
holder.date1Text = (TextView) convertView
.findViewById(R.id.newspromo_date);
holder.imageView = (ImageView) convertView
.findViewById(R.id.newspromo_imageView);
holder.prg = (ProgressBar) convertView
.findViewById(R.id.progressBar1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
holder.loadImg.cancel(true);
}
if (!(npList.get(position).getName().equals(""))) {
holder.nameText.setVisibility(View.VISIBLE);
holder.nameText.setText(npList.get(position).getName());
} else {
holder.nameText.setVisibility(View.GONE);
}
if (!(npList.get(position).getDate().equals(""))) {
holder.date1Text.setVisibility(View.VISIBLE);
holder.date1Text.setText(npList.get(position).getDate());
} else {
holder.date1Text.setVisibility(View.GONE);
}
if (!(npList.get(position).getImageURL().equals(""))) {
holder.imageView.setVisibility(View.VISIBLE);
holder.loadImg = new LoadImage(holder.imageView, npList.get(
position).getImageURL(), holder);
holder.loadImg.execute();
} else {
holder.imageView.setVisibility(View.GONE);
holder.prg.setVisibility(View.GONE);
}
return convertView;
}
class LoadImage extends AsyncTask<Object, Void, Bitmap> {
ViewHolder viewH;
private ImageView imv;
private String url;
public LoadImage(ImageView imv, String imageURL, ViewHolder viewH) {
this.imv = imv;
this.url = imageURL;
this.viewH = viewH;
}
#Override
protected Bitmap doInBackground(Object... params) {
BitmapFromURL bmpURL = new BitmapFromURL();
src = bmpURL.getBitmapFromURL(url);
return src;
}
#Override
protected void onPostExecute(Bitmap result) {
// imv.setImageBitmap(result);
// viewH.prg.setVisibility(View.GONE);
viewH.prg.setVisibility(View.GONE);
imv.setImageBitmap(result);
}
}
}
Here is the Activity that handles the ADAPTER. I am implementing the Endless listview approach that some big sites uses. Like Facebook, Twitter, etc..New Items loaded into the listview when scrolling into the bottom. I am not sure if I did it well.
public class ListNewsPromoActivity extends Activity {
List<NewsPromosDTO> npList;
String url, user_email;
Bundle extras;
int user_points;
List<Integer> npIDs;
private ProgressDialog progressDialog;
BitmapFromURL bmpURL;
JSONArray users = null;
String TAG_ID = "id";
String TAG_NAME = "name";
String TAG_PHOTO = "photo";
String TAG_DATE = "date";
String TAG_DESC = "description";
ListView list;
NewsPromoAdapter newsAdapter;
boolean loadingMore = false;
private Runnable returnRes;
int itemsPerPage = 3;
int currentIndex = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.news_promo_listview);
list = (ListView) findViewById(R.id.mainView);
extras = getIntent().getExtras();
if (extras != null) {
user_points = extras.getInt("user_points");
user_email = extras.getString("user_email");
}
url = getString(R.string.app_url_news_promos);
npIDs = new ArrayList<Integer>();
npList = new ArrayList<NewsPromosDTO>();
View footerView = ((LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
R.layout.footer, null, false);
newsAdapter = new NewsPromoAdapter(ListNewsPromoActivity.this, npList);
list.addFooterView(footerView);
list.setAdapter(newsAdapter);
list.setOnScrollListener(new OnScrollListener() {
// useless here, skip!
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// what is the bottom item that is visible
int lastInScreen = firstVisibleItem + visibleItemCount;
// is the bottom item visible & not loading more already ? Load
if ((lastInScreen == totalItemCount) && !(loadingMore)) {
Thread thread = new Thread(null, getRunnable());
thread.start();
}
}
});
// Runnable to load the items
// Since we cant update our UI from a thread this Runnable takes care of
// that!
returnRes = new Runnable() {
#Override
public void run() {
// Loop thru the new items and add them to the adapter
for (NewsPromosDTO np : npList) {
System.out.println(np.getName() + " andito ako!!");
newsAdapter.add(np);
}
newsAdapter.notifyDataSetChanged();
// Done loading more.
loadingMore = false;
}
};
}
protected class loadNewsPromo extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(Void... params) {
// Creating JSON Parser instance
loadingMore = true;
JSONParser jParser = new JSONParser();
JSONObject json;
if (jParser.checkServer(url)) {
try {
// Getting Array of UserNews
json = jParser.getJSONFromUrl(url);
users = json.getJSONArray(user_email);
// looping through All UserNews
for (int i = currentIndex; i < itemsPerPage; i++) {
if (itemsPerPage == i) {
// currentIndex--;
break;
} else {
JSONObject c = users.getJSONObject(i);
// Storing each json item in variable
NewsPromosDTO npDTO = new NewsPromosDTO();
npDTO.setImageURL(c.getString(TAG_PHOTO));
npDTO.setId(c.getInt(TAG_ID));
npDTO.setName(c.getString(TAG_NAME));
npDTO.setDate(c.getString(TAG_DATE));
npDTO.setDescription(c.getString(TAG_DESC));
npList.add(npDTO);
currentIndex++;
}
}
} catch (JSONException e) {
e.printStackTrace();
return null;
} finally {
}
}
}
return null;
}
#Override
protected void onPostExecute(String result) { //
// progressDialog.dismiss();
loadingMore = false;
list();
}
}
public void list() {
// add the footer before adding the adapter, else the footer will not
// load!
View footerView = ((LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
R.layout.footer, null, false);
newsAdapter = new NewsPromoAdapter(ListNewsPromoActivity.this, npList);
list.addFooterView(footerView);
list.setAdapter(newsAdapter);
}
public Runnable getRunnable() {
Runnable loadMoreListItems = new Runnable() {
#Override
public void run() {
// Set flag so we cant load new items 2 at the same time
loadingMore = true;
// Reset the array that holds the new items
// Simulate a delay, delete this on a production environment!
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
// Get 15 new listitems
JSONParser jParser = new JSONParser();
JSONObject json;
npList = new ArrayList<NewsPromosDTO>();
if (jParser.checkServer(url)) {
try {
// Getting Array of Contacts
json = jParser.getJSONFromUrl(url);
users = json.getJSONArray(user_email);
// looping through All Contacts
// if (itemsPerPage > users.length() - currentIndex) {
// itemsPerPage = users.length();
// }
npList = new ArrayList<NewsPromosDTO>();
System.out.println(users.length() + " Laman ng users");
int counter = 0;
for (int i = currentIndex; i < users.length(); i++) {
if (itemsPerPage == counter) {
break;
} else {
JSONObject c = users.getJSONObject(i);
// Storing each json item in variable
NewsPromosDTO npDTO = new NewsPromosDTO();
npDTO.setImageURL(c.getString(TAG_PHOTO));
npDTO.setId(c.getInt(TAG_ID));
npDTO.setName(c.getString(TAG_NAME));
npDTO.setDate(c.getString(TAG_DATE));
npDTO.setDescription(c.getString(TAG_DESC));
npList.add(npDTO);
currentIndex++;
}
counter++;
}
} catch (JSONException e) {
e.printStackTrace();
} finally {
}
}
// Done! now continue on the UI thread
runOnUiThread(returnRes);
}
};
return loadMoreListItems;
}
}

Categories

Resources